xref: /freebsd/contrib/llvm-project/lld/ELF/Arch/PPC64.cpp (revision 5956d97f4b3204318ceb6aa9c77bd0bc6ea87a41)
1 //===- PPC64.cpp ----------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "SymbolTable.h"
10 #include "Symbols.h"
11 #include "SyntheticSections.h"
12 #include "Target.h"
13 #include "Thunks.h"
14 #include "lld/Common/CommonLinkerContext.h"
15 #include "llvm/Support/Endian.h"
16 
17 using namespace llvm;
18 using namespace llvm::object;
19 using namespace llvm::support::endian;
20 using namespace llvm::ELF;
21 using namespace lld;
22 using namespace lld::elf;
23 
24 constexpr uint64_t ppc64TocOffset = 0x8000;
25 constexpr uint64_t dynamicThreadPointerOffset = 0x8000;
26 
27 // The instruction encoding of bits 21-30 from the ISA for the Xform and Dform
28 // instructions that can be used as part of the initial exec TLS sequence.
29 enum XFormOpcd {
30   LBZX = 87,
31   LHZX = 279,
32   LWZX = 23,
33   LDX = 21,
34   STBX = 215,
35   STHX = 407,
36   STWX = 151,
37   STDX = 149,
38   ADD = 266,
39 };
40 
41 enum DFormOpcd {
42   LBZ = 34,
43   LBZU = 35,
44   LHZ = 40,
45   LHZU = 41,
46   LHAU = 43,
47   LWZ = 32,
48   LWZU = 33,
49   LFSU = 49,
50   LD = 58,
51   LFDU = 51,
52   STB = 38,
53   STBU = 39,
54   STH = 44,
55   STHU = 45,
56   STW = 36,
57   STWU = 37,
58   STFSU = 53,
59   STFDU = 55,
60   STD = 62,
61   ADDI = 14
62 };
63 
64 constexpr uint32_t NOP = 0x60000000;
65 
66 enum class PPCLegacyInsn : uint32_t {
67   NOINSN = 0,
68   // Loads.
69   LBZ = 0x88000000,
70   LHZ = 0xa0000000,
71   LWZ = 0x80000000,
72   LHA = 0xa8000000,
73   LWA = 0xe8000002,
74   LD = 0xe8000000,
75   LFS = 0xC0000000,
76   LXSSP = 0xe4000003,
77   LFD = 0xc8000000,
78   LXSD = 0xe4000002,
79   LXV = 0xf4000001,
80   LXVP = 0x18000000,
81 
82   // Stores.
83   STB = 0x98000000,
84   STH = 0xb0000000,
85   STW = 0x90000000,
86   STD = 0xf8000000,
87   STFS = 0xd0000000,
88   STXSSP = 0xf4000003,
89   STFD = 0xd8000000,
90   STXSD = 0xf4000002,
91   STXV = 0xf4000005,
92   STXVP = 0x18000001
93 };
94 enum class PPCPrefixedInsn : uint64_t {
95   NOINSN = 0,
96   PREFIX_MLS = 0x0610000000000000,
97   PREFIX_8LS = 0x0410000000000000,
98 
99   // Loads.
100   PLBZ = PREFIX_MLS,
101   PLHZ = PREFIX_MLS,
102   PLWZ = PREFIX_MLS,
103   PLHA = PREFIX_MLS,
104   PLWA = PREFIX_8LS | 0xa4000000,
105   PLD = PREFIX_8LS | 0xe4000000,
106   PLFS = PREFIX_MLS,
107   PLXSSP = PREFIX_8LS | 0xac000000,
108   PLFD = PREFIX_MLS,
109   PLXSD = PREFIX_8LS | 0xa8000000,
110   PLXV = PREFIX_8LS | 0xc8000000,
111   PLXVP = PREFIX_8LS | 0xe8000000,
112 
113   // Stores.
114   PSTB = PREFIX_MLS,
115   PSTH = PREFIX_MLS,
116   PSTW = PREFIX_MLS,
117   PSTD = PREFIX_8LS | 0xf4000000,
118   PSTFS = PREFIX_MLS,
119   PSTXSSP = PREFIX_8LS | 0xbc000000,
120   PSTFD = PREFIX_MLS,
121   PSTXSD = PREFIX_8LS | 0xb8000000,
122   PSTXV = PREFIX_8LS | 0xd8000000,
123   PSTXVP = PREFIX_8LS | 0xf8000000
124 };
125 static bool checkPPCLegacyInsn(uint32_t encoding) {
126   PPCLegacyInsn insn = static_cast<PPCLegacyInsn>(encoding);
127   if (insn == PPCLegacyInsn::NOINSN)
128     return false;
129 #define PCREL_OPT(Legacy, PCRel, InsnMask)                                     \
130   if (insn == PPCLegacyInsn::Legacy)                                           \
131     return true;
132 #include "PPCInsns.def"
133 #undef PCREL_OPT
134   return false;
135 }
136 
137 // Masks to apply to legacy instructions when converting them to prefixed,
138 // pc-relative versions. For the most part, the primary opcode is shared
139 // between the legacy instruction and the suffix of its prefixed version.
140 // However, there are some instances where that isn't the case (DS-Form and
141 // DQ-form instructions).
142 enum class LegacyToPrefixMask : uint64_t {
143   NOMASK = 0x0,
144   OPC_AND_RST = 0xffe00000, // Primary opc (0-5) and R[ST] (6-10).
145   ONLY_RST = 0x3e00000,     // [RS]T (6-10).
146   ST_STX28_TO5 =
147       0x8000000003e00000, // S/T (6-10) - The [S/T]X bit moves from 28 to 5.
148 };
149 
150 uint64_t elf::getPPC64TocBase() {
151   // The TOC consists of sections .got, .toc, .tocbss, .plt in that order. The
152   // TOC starts where the first of these sections starts. We always create a
153   // .got when we see a relocation that uses it, so for us the start is always
154   // the .got.
155   uint64_t tocVA = in.got->getVA();
156 
157   // Per the ppc64-elf-linux ABI, The TOC base is TOC value plus 0x8000
158   // thus permitting a full 64 Kbytes segment. Note that the glibc startup
159   // code (crt1.o) assumes that you can get from the TOC base to the
160   // start of the .toc section with only a single (signed) 16-bit relocation.
161   return tocVA + ppc64TocOffset;
162 }
163 
164 unsigned elf::getPPC64GlobalEntryToLocalEntryOffset(uint8_t stOther) {
165   // The offset is encoded into the 3 most significant bits of the st_other
166   // field, with some special values described in section 3.4.1 of the ABI:
167   // 0   --> Zero offset between the GEP and LEP, and the function does NOT use
168   //         the TOC pointer (r2). r2 will hold the same value on returning from
169   //         the function as it did on entering the function.
170   // 1   --> Zero offset between the GEP and LEP, and r2 should be treated as a
171   //         caller-saved register for all callers.
172   // 2-6 --> The  binary logarithm of the offset eg:
173   //         2 --> 2^2 = 4 bytes -->  1 instruction.
174   //         6 --> 2^6 = 64 bytes --> 16 instructions.
175   // 7   --> Reserved.
176   uint8_t gepToLep = (stOther >> 5) & 7;
177   if (gepToLep < 2)
178     return 0;
179 
180   // The value encoded in the st_other bits is the
181   // log-base-2(offset).
182   if (gepToLep < 7)
183     return 1 << gepToLep;
184 
185   error("reserved value of 7 in the 3 most-significant-bits of st_other");
186   return 0;
187 }
188 
189 void elf::writePrefixedInstruction(uint8_t *loc, uint64_t insn) {
190   insn = config->isLE ? insn << 32 | insn >> 32 : insn;
191   write64(loc, insn);
192 }
193 
194 static bool addOptional(StringRef name, uint64_t value,
195                         std::vector<Defined *> &defined) {
196   Symbol *sym = symtab->find(name);
197   if (!sym || sym->isDefined())
198     return false;
199   sym->resolve(Defined{/*file=*/nullptr, saver().save(name), STB_GLOBAL,
200                        STV_HIDDEN, STT_FUNC, value,
201                        /*size=*/0, /*section=*/nullptr});
202   defined.push_back(cast<Defined>(sym));
203   return true;
204 }
205 
206 // If from is 14, write ${prefix}14: firstInsn; ${prefix}15:
207 // firstInsn+0x200008; ...; ${prefix}31: firstInsn+(31-14)*0x200008; $tail
208 // The labels are defined only if they exist in the symbol table.
209 static void writeSequence(MutableArrayRef<uint32_t> buf, const char *prefix,
210                           int from, uint32_t firstInsn,
211                           ArrayRef<uint32_t> tail) {
212   std::vector<Defined *> defined;
213   char name[16];
214   int first;
215   uint32_t *ptr = buf.data();
216   for (int r = from; r < 32; ++r) {
217     format("%s%d", prefix, r).snprint(name, sizeof(name));
218     if (addOptional(name, 4 * (r - from), defined) && defined.size() == 1)
219       first = r - from;
220     write32(ptr++, firstInsn + 0x200008 * (r - from));
221   }
222   for (uint32_t insn : tail)
223     write32(ptr++, insn);
224   assert(ptr == &*buf.end());
225 
226   if (defined.empty())
227     return;
228   // The full section content has the extent of [begin, end). We drop unused
229   // instructions and write [first,end).
230   auto *sec = make<InputSection>(
231       nullptr, SHF_ALLOC, SHT_PROGBITS, 4,
232       makeArrayRef(reinterpret_cast<uint8_t *>(buf.data() + first),
233                    4 * (buf.size() - first)),
234       ".text");
235   inputSections.push_back(sec);
236   for (Defined *sym : defined) {
237     sym->section = sec;
238     sym->value -= 4 * first;
239   }
240 }
241 
242 // Implements some save and restore functions as described by ELF V2 ABI to be
243 // compatible with GCC. With GCC -Os, when the number of call-saved registers
244 // exceeds a certain threshold, GCC generates _savegpr0_* _restgpr0_* calls and
245 // expects the linker to define them. See
246 // https://sourceware.org/pipermail/binutils/2002-February/017444.html and
247 // https://sourceware.org/pipermail/binutils/2004-August/036765.html . This is
248 // weird because libgcc.a would be the natural place. The linker generation
249 // approach has the advantage that the linker can generate multiple copies to
250 // avoid long branch thunks. However, we don't consider the advantage
251 // significant enough to complicate our trunk implementation, so we take the
252 // simple approach and synthesize .text sections providing the implementation.
253 void elf::addPPC64SaveRestore() {
254   static uint32_t savegpr0[20], restgpr0[21], savegpr1[19], restgpr1[19];
255   constexpr uint32_t blr = 0x4e800020, mtlr_0 = 0x7c0803a6;
256 
257   // _restgpr0_14: ld 14, -144(1); _restgpr0_15: ld 15, -136(1); ...
258   // Tail: ld 0, 16(1); mtlr 0; blr
259   writeSequence(restgpr0, "_restgpr0_", 14, 0xe9c1ff70,
260                 {0xe8010010, mtlr_0, blr});
261   // _restgpr1_14: ld 14, -144(12); _restgpr1_15: ld 15, -136(12); ...
262   // Tail: blr
263   writeSequence(restgpr1, "_restgpr1_", 14, 0xe9ccff70, {blr});
264   // _savegpr0_14: std 14, -144(1); _savegpr0_15: std 15, -136(1); ...
265   // Tail: std 0, 16(1); blr
266   writeSequence(savegpr0, "_savegpr0_", 14, 0xf9c1ff70, {0xf8010010, blr});
267   // _savegpr1_14: std 14, -144(12); _savegpr1_15: std 15, -136(12); ...
268   // Tail: blr
269   writeSequence(savegpr1, "_savegpr1_", 14, 0xf9ccff70, {blr});
270 }
271 
272 // Find the R_PPC64_ADDR64 in .rela.toc with matching offset.
273 template <typename ELFT>
274 static std::pair<Defined *, int64_t>
275 getRelaTocSymAndAddend(InputSectionBase *tocSec, uint64_t offset) {
276   // .rela.toc contains exclusively R_PPC64_ADDR64 relocations sorted by
277   // r_offset: 0, 8, 16, etc. For a given Offset, Offset / 8 gives us the
278   // relocation index in most cases.
279   //
280   // In rare cases a TOC entry may store a constant that doesn't need an
281   // R_PPC64_ADDR64, the corresponding r_offset is therefore missing. Offset / 8
282   // points to a relocation with larger r_offset. Do a linear probe then.
283   // Constants are extremely uncommon in .toc and the extra number of array
284   // accesses can be seen as a small constant.
285   ArrayRef<typename ELFT::Rela> relas =
286       tocSec->template relsOrRelas<ELFT>().relas;
287   if (relas.empty())
288     return {};
289   uint64_t index = std::min<uint64_t>(offset / 8, relas.size() - 1);
290   for (;;) {
291     if (relas[index].r_offset == offset) {
292       Symbol &sym = tocSec->getFile<ELFT>()->getRelocTargetSym(relas[index]);
293       return {dyn_cast<Defined>(&sym), getAddend<ELFT>(relas[index])};
294     }
295     if (relas[index].r_offset < offset || index == 0)
296       break;
297     --index;
298   }
299   return {};
300 }
301 
302 // When accessing a symbol defined in another translation unit, compilers
303 // reserve a .toc entry, allocate a local label and generate toc-indirect
304 // instructions:
305 //
306 //   addis 3, 2, .LC0@toc@ha  # R_PPC64_TOC16_HA
307 //   ld    3, .LC0@toc@l(3)   # R_PPC64_TOC16_LO_DS, load the address from a .toc entry
308 //   ld/lwa 3, 0(3)           # load the value from the address
309 //
310 //   .section .toc,"aw",@progbits
311 //   .LC0: .tc var[TC],var
312 //
313 // If var is defined, non-preemptable and addressable with a 32-bit signed
314 // offset from the toc base, the address of var can be computed by adding an
315 // offset to the toc base, saving a load.
316 //
317 //   addis 3,2,var@toc@ha     # this may be relaxed to a nop,
318 //   addi  3,3,var@toc@l      # then this becomes addi 3,2,var@toc
319 //   ld/lwa 3, 0(3)           # load the value from the address
320 //
321 // Returns true if the relaxation is performed.
322 bool elf::tryRelaxPPC64TocIndirection(const Relocation &rel, uint8_t *bufLoc) {
323   assert(config->tocOptimize);
324   if (rel.addend < 0)
325     return false;
326 
327   // If the symbol is not the .toc section, this isn't a toc-indirection.
328   Defined *defSym = dyn_cast<Defined>(rel.sym);
329   if (!defSym || !defSym->isSection() || defSym->section->name != ".toc")
330     return false;
331 
332   Defined *d;
333   int64_t addend;
334   auto *tocISB = cast<InputSectionBase>(defSym->section);
335   std::tie(d, addend) =
336       config->isLE ? getRelaTocSymAndAddend<ELF64LE>(tocISB, rel.addend)
337                    : getRelaTocSymAndAddend<ELF64BE>(tocISB, rel.addend);
338 
339   // Only non-preemptable defined symbols can be relaxed.
340   if (!d || d->isPreemptible)
341     return false;
342 
343   // R_PPC64_ADDR64 should have created a canonical PLT for the non-preemptable
344   // ifunc and changed its type to STT_FUNC.
345   assert(!d->isGnuIFunc());
346 
347   // Two instructions can materialize a 32-bit signed offset from the toc base.
348   uint64_t tocRelative = d->getVA(addend) - getPPC64TocBase();
349   if (!isInt<32>(tocRelative))
350     return false;
351 
352   // Add PPC64TocOffset that will be subtracted by PPC64::relocate().
353   target->relaxGot(bufLoc, rel, tocRelative + ppc64TocOffset);
354   return true;
355 }
356 
357 namespace {
358 class PPC64 final : public TargetInfo {
359 public:
360   PPC64();
361   int getTlsGdRelaxSkip(RelType type) const override;
362   uint32_t calcEFlags() const override;
363   RelExpr getRelExpr(RelType type, const Symbol &s,
364                      const uint8_t *loc) const override;
365   RelType getDynRel(RelType type) const override;
366   int64_t getImplicitAddend(const uint8_t *buf, RelType type) const override;
367   void writePltHeader(uint8_t *buf) const override;
368   void writePlt(uint8_t *buf, const Symbol &sym,
369                 uint64_t pltEntryAddr) const override;
370   void writeIplt(uint8_t *buf, const Symbol &sym,
371                  uint64_t pltEntryAddr) const override;
372   void relocate(uint8_t *loc, const Relocation &rel,
373                 uint64_t val) const override;
374   void writeGotHeader(uint8_t *buf) const override;
375   bool needsThunk(RelExpr expr, RelType type, const InputFile *file,
376                   uint64_t branchAddr, const Symbol &s,
377                   int64_t a) const override;
378   uint32_t getThunkSectionSpacing() const override;
379   bool inBranchRange(RelType type, uint64_t src, uint64_t dst) const override;
380   RelExpr adjustTlsExpr(RelType type, RelExpr expr) const override;
381   RelExpr adjustGotPcExpr(RelType type, int64_t addend,
382                           const uint8_t *loc) const override;
383   void relaxGot(uint8_t *loc, const Relocation &rel,
384                 uint64_t val) const override;
385   void relaxTlsGdToIe(uint8_t *loc, const Relocation &rel,
386                       uint64_t val) const override;
387   void relaxTlsGdToLe(uint8_t *loc, const Relocation &rel,
388                       uint64_t val) const override;
389   void relaxTlsLdToLe(uint8_t *loc, const Relocation &rel,
390                       uint64_t val) const override;
391   void relaxTlsIeToLe(uint8_t *loc, const Relocation &rel,
392                       uint64_t val) const override;
393 
394   bool adjustPrologueForCrossSplitStack(uint8_t *loc, uint8_t *end,
395                                         uint8_t stOther) const override;
396 };
397 } // namespace
398 
399 // Relocation masks following the #lo(value), #hi(value), #ha(value),
400 // #higher(value), #highera(value), #highest(value), and #highesta(value)
401 // macros defined in section 4.5.1. Relocation Types of the PPC-elf64abi
402 // document.
403 static uint16_t lo(uint64_t v) { return v; }
404 static uint16_t hi(uint64_t v) { return v >> 16; }
405 static uint64_t ha(uint64_t v) { return (v + 0x8000) >> 16; }
406 static uint16_t higher(uint64_t v) { return v >> 32; }
407 static uint16_t highera(uint64_t v) { return (v + 0x8000) >> 32; }
408 static uint16_t highest(uint64_t v) { return v >> 48; }
409 static uint16_t highesta(uint64_t v) { return (v + 0x8000) >> 48; }
410 
411 // Extracts the 'PO' field of an instruction encoding.
412 static uint8_t getPrimaryOpCode(uint32_t encoding) { return (encoding >> 26); }
413 
414 static bool isDQFormInstruction(uint32_t encoding) {
415   switch (getPrimaryOpCode(encoding)) {
416   default:
417     return false;
418   case 6: // Power10 paired loads/stores (lxvp, stxvp).
419   case 56:
420     // The only instruction with a primary opcode of 56 is `lq`.
421     return true;
422   case 61:
423     // There are both DS and DQ instruction forms with this primary opcode.
424     // Namely `lxv` and `stxv` are the DQ-forms that use it.
425     // The DS 'XO' bits being set to 01 is restricted to DQ form.
426     return (encoding & 3) == 0x1;
427   }
428 }
429 
430 static bool isDSFormInstruction(PPCLegacyInsn insn) {
431   switch (insn) {
432   default:
433     return false;
434   case PPCLegacyInsn::LWA:
435   case PPCLegacyInsn::LD:
436   case PPCLegacyInsn::LXSD:
437   case PPCLegacyInsn::LXSSP:
438   case PPCLegacyInsn::STD:
439   case PPCLegacyInsn::STXSD:
440   case PPCLegacyInsn::STXSSP:
441     return true;
442   }
443 }
444 
445 static PPCLegacyInsn getPPCLegacyInsn(uint32_t encoding) {
446   uint32_t opc = encoding & 0xfc000000;
447 
448   // If the primary opcode is shared between multiple instructions, we need to
449   // fix it up to match the actual instruction we are after.
450   if ((opc == 0xe4000000 || opc == 0xe8000000 || opc == 0xf4000000 ||
451        opc == 0xf8000000) &&
452       !isDQFormInstruction(encoding))
453     opc = encoding & 0xfc000003;
454   else if (opc == 0xf4000000)
455     opc = encoding & 0xfc000007;
456   else if (opc == 0x18000000)
457     opc = encoding & 0xfc00000f;
458 
459   // If the value is not one of the enumerators in PPCLegacyInsn, we want to
460   // return PPCLegacyInsn::NOINSN.
461   if (!checkPPCLegacyInsn(opc))
462     return PPCLegacyInsn::NOINSN;
463   return static_cast<PPCLegacyInsn>(opc);
464 }
465 
466 static PPCPrefixedInsn getPCRelativeForm(PPCLegacyInsn insn) {
467   switch (insn) {
468 #define PCREL_OPT(Legacy, PCRel, InsnMask)                                     \
469   case PPCLegacyInsn::Legacy:                                                  \
470     return PPCPrefixedInsn::PCRel
471 #include "PPCInsns.def"
472 #undef PCREL_OPT
473   }
474   return PPCPrefixedInsn::NOINSN;
475 }
476 
477 static LegacyToPrefixMask getInsnMask(PPCLegacyInsn insn) {
478   switch (insn) {
479 #define PCREL_OPT(Legacy, PCRel, InsnMask)                                     \
480   case PPCLegacyInsn::Legacy:                                                  \
481     return LegacyToPrefixMask::InsnMask
482 #include "PPCInsns.def"
483 #undef PCREL_OPT
484   }
485   return LegacyToPrefixMask::NOMASK;
486 }
487 static uint64_t getPCRelativeForm(uint32_t encoding) {
488   PPCLegacyInsn origInsn = getPPCLegacyInsn(encoding);
489   PPCPrefixedInsn pcrelInsn = getPCRelativeForm(origInsn);
490   if (pcrelInsn == PPCPrefixedInsn::NOINSN)
491     return UINT64_C(-1);
492   LegacyToPrefixMask origInsnMask = getInsnMask(origInsn);
493   uint64_t pcrelEncoding =
494       (uint64_t)pcrelInsn | (encoding & (uint64_t)origInsnMask);
495 
496   // If the mask requires moving bit 28 to bit 5, do that now.
497   if (origInsnMask == LegacyToPrefixMask::ST_STX28_TO5)
498     pcrelEncoding |= (encoding & 0x8) << 23;
499   return pcrelEncoding;
500 }
501 
502 static bool isInstructionUpdateForm(uint32_t encoding) {
503   switch (getPrimaryOpCode(encoding)) {
504   default:
505     return false;
506   case LBZU:
507   case LHAU:
508   case LHZU:
509   case LWZU:
510   case LFSU:
511   case LFDU:
512   case STBU:
513   case STHU:
514   case STWU:
515   case STFSU:
516   case STFDU:
517     return true;
518     // LWA has the same opcode as LD, and the DS bits is what differentiates
519     // between LD/LDU/LWA
520   case LD:
521   case STD:
522     return (encoding & 3) == 1;
523   }
524 }
525 
526 // Compute the total displacement between the prefixed instruction that gets
527 // to the start of the data and the load/store instruction that has the offset
528 // into the data structure.
529 // For example:
530 // paddi 3, 0, 1000, 1
531 // lwz 3, 20(3)
532 // Should add up to 1020 for total displacement.
533 static int64_t getTotalDisp(uint64_t prefixedInsn, uint32_t accessInsn) {
534   int64_t disp34 = llvm::SignExtend64(
535       ((prefixedInsn & 0x3ffff00000000) >> 16) | (prefixedInsn & 0xffff), 34);
536   int32_t disp16 = llvm::SignExtend32(accessInsn & 0xffff, 16);
537   // For DS and DQ form instructions, we need to mask out the XO bits.
538   if (isDQFormInstruction(accessInsn))
539     disp16 &= ~0xf;
540   else if (isDSFormInstruction(getPPCLegacyInsn(accessInsn)))
541     disp16 &= ~0x3;
542   return disp34 + disp16;
543 }
544 
545 // There are a number of places when we either want to read or write an
546 // instruction when handling a half16 relocation type. On big-endian the buffer
547 // pointer is pointing into the middle of the word we want to extract, and on
548 // little-endian it is pointing to the start of the word. These 2 helpers are to
549 // simplify reading and writing in that context.
550 static void writeFromHalf16(uint8_t *loc, uint32_t insn) {
551   write32(config->isLE ? loc : loc - 2, insn);
552 }
553 
554 static uint32_t readFromHalf16(const uint8_t *loc) {
555   return read32(config->isLE ? loc : loc - 2);
556 }
557 
558 static uint64_t readPrefixedInstruction(const uint8_t *loc) {
559   uint64_t fullInstr = read64(loc);
560   return config->isLE ? (fullInstr << 32 | fullInstr >> 32) : fullInstr;
561 }
562 
563 PPC64::PPC64() {
564   copyRel = R_PPC64_COPY;
565   gotRel = R_PPC64_GLOB_DAT;
566   pltRel = R_PPC64_JMP_SLOT;
567   relativeRel = R_PPC64_RELATIVE;
568   iRelativeRel = R_PPC64_IRELATIVE;
569   symbolicRel = R_PPC64_ADDR64;
570   pltHeaderSize = 60;
571   pltEntrySize = 4;
572   ipltEntrySize = 16; // PPC64PltCallStub::size
573   gotHeaderEntriesNum = 1;
574   gotPltHeaderEntriesNum = 2;
575   needsThunks = true;
576 
577   tlsModuleIndexRel = R_PPC64_DTPMOD64;
578   tlsOffsetRel = R_PPC64_DTPREL64;
579 
580   tlsGotRel = R_PPC64_TPREL64;
581 
582   needsMoreStackNonSplit = false;
583 
584   // We need 64K pages (at least under glibc/Linux, the loader won't
585   // set different permissions on a finer granularity than that).
586   defaultMaxPageSize = 65536;
587 
588   // The PPC64 ELF ABI v1 spec, says:
589   //
590   //   It is normally desirable to put segments with different characteristics
591   //   in separate 256 Mbyte portions of the address space, to give the
592   //   operating system full paging flexibility in the 64-bit address space.
593   //
594   // And because the lowest non-zero 256M boundary is 0x10000000, PPC64 linkers
595   // use 0x10000000 as the starting address.
596   defaultImageBase = 0x10000000;
597 
598   write32(trapInstr.data(), 0x7fe00008);
599 }
600 
601 int PPC64::getTlsGdRelaxSkip(RelType type) const {
602   // A __tls_get_addr call instruction is marked with 2 relocations:
603   //
604   //   R_PPC64_TLSGD / R_PPC64_TLSLD: marker relocation
605   //   R_PPC64_REL24: __tls_get_addr
606   //
607   // After the relaxation we no longer call __tls_get_addr and should skip both
608   // relocations to not create a false dependence on __tls_get_addr being
609   // defined.
610   if (type == R_PPC64_TLSGD || type == R_PPC64_TLSLD)
611     return 2;
612   return 1;
613 }
614 
615 static uint32_t getEFlags(InputFile *file) {
616   if (config->ekind == ELF64BEKind)
617     return cast<ObjFile<ELF64BE>>(file)->getObj().getHeader().e_flags;
618   return cast<ObjFile<ELF64LE>>(file)->getObj().getHeader().e_flags;
619 }
620 
621 // This file implements v2 ABI. This function makes sure that all
622 // object files have v2 or an unspecified version as an ABI version.
623 uint32_t PPC64::calcEFlags() const {
624   for (InputFile *f : objectFiles) {
625     uint32_t flag = getEFlags(f);
626     if (flag == 1)
627       error(toString(f) + ": ABI version 1 is not supported");
628     else if (flag > 2)
629       error(toString(f) + ": unrecognized e_flags: " + Twine(flag));
630   }
631   return 2;
632 }
633 
634 void PPC64::relaxGot(uint8_t *loc, const Relocation &rel, uint64_t val) const {
635   switch (rel.type) {
636   case R_PPC64_TOC16_HA:
637     // Convert "addis reg, 2, .LC0@toc@h" to "addis reg, 2, var@toc@h" or "nop".
638     relocate(loc, rel, val);
639     break;
640   case R_PPC64_TOC16_LO_DS: {
641     // Convert "ld reg, .LC0@toc@l(reg)" to "addi reg, reg, var@toc@l" or
642     // "addi reg, 2, var@toc".
643     uint32_t insn = readFromHalf16(loc);
644     if (getPrimaryOpCode(insn) != LD)
645       error("expected a 'ld' for got-indirect to toc-relative relaxing");
646     writeFromHalf16(loc, (insn & 0x03ffffff) | 0x38000000);
647     relocateNoSym(loc, R_PPC64_TOC16_LO, val);
648     break;
649   }
650   case R_PPC64_GOT_PCREL34: {
651     // Clear the first 8 bits of the prefix and the first 6 bits of the
652     // instruction (the primary opcode).
653     uint64_t insn = readPrefixedInstruction(loc);
654     if ((insn & 0xfc000000) != 0xe4000000)
655       error("expected a 'pld' for got-indirect to pc-relative relaxing");
656     insn &= ~0xff000000fc000000;
657 
658     // Replace the cleared bits with the values for PADDI (0x600000038000000);
659     insn |= 0x600000038000000;
660     writePrefixedInstruction(loc, insn);
661     relocate(loc, rel, val);
662     break;
663   }
664   case R_PPC64_PCREL_OPT: {
665     // We can only relax this if the R_PPC64_GOT_PCREL34 at this offset can
666     // be relaxed. The eligibility for the relaxation needs to be determined
667     // on that relocation since this one does not relocate a symbol.
668     uint64_t insn = readPrefixedInstruction(loc);
669     uint32_t accessInsn = read32(loc + rel.addend);
670     uint64_t pcRelInsn = getPCRelativeForm(accessInsn);
671 
672     // This error is not necessary for correctness but is emitted for now
673     // to ensure we don't miss these opportunities in real code. It can be
674     // removed at a later date.
675     if (pcRelInsn == UINT64_C(-1)) {
676       errorOrWarn(
677           "unrecognized instruction for R_PPC64_PCREL_OPT relaxation: 0x" +
678           Twine::utohexstr(accessInsn));
679       break;
680     }
681 
682     int64_t totalDisp = getTotalDisp(insn, accessInsn);
683     if (!isInt<34>(totalDisp))
684       break; // Displacement doesn't fit.
685     // Convert the PADDI to the prefixed version of accessInsn and convert
686     // accessInsn to a nop.
687     writePrefixedInstruction(loc, pcRelInsn |
688                                       ((totalDisp & 0x3ffff0000) << 16) |
689                                       (totalDisp & 0xffff));
690     write32(loc + rel.addend, NOP); // nop accessInsn.
691     break;
692   }
693   default:
694     llvm_unreachable("unexpected relocation type");
695   }
696 }
697 
698 void PPC64::relaxTlsGdToLe(uint8_t *loc, const Relocation &rel,
699                            uint64_t val) const {
700   // Reference: 3.7.4.2 of the 64-bit ELF V2 abi supplement.
701   // The general dynamic code sequence for a global `x` will look like:
702   // Instruction                    Relocation                Symbol
703   // addis r3, r2, x@got@tlsgd@ha   R_PPC64_GOT_TLSGD16_HA      x
704   // addi  r3, r3, x@got@tlsgd@l    R_PPC64_GOT_TLSGD16_LO      x
705   // bl __tls_get_addr(x@tlsgd)     R_PPC64_TLSGD               x
706   //                                R_PPC64_REL24               __tls_get_addr
707   // nop                            None                       None
708 
709   // Relaxing to local exec entails converting:
710   // addis r3, r2, x@got@tlsgd@ha    into      nop
711   // addi  r3, r3, x@got@tlsgd@l     into      addis r3, r13, x@tprel@ha
712   // bl __tls_get_addr(x@tlsgd)      into      nop
713   // nop                             into      addi r3, r3, x@tprel@l
714 
715   switch (rel.type) {
716   case R_PPC64_GOT_TLSGD16_HA:
717     writeFromHalf16(loc, NOP);
718     break;
719   case R_PPC64_GOT_TLSGD16:
720   case R_PPC64_GOT_TLSGD16_LO:
721     writeFromHalf16(loc, 0x3c6d0000); // addis r3, r13
722     relocateNoSym(loc, R_PPC64_TPREL16_HA, val);
723     break;
724   case R_PPC64_GOT_TLSGD_PCREL34:
725     // Relax from paddi r3, 0, x@got@tlsgd@pcrel, 1 to
726     //            paddi r3, r13, x@tprel, 0
727     writePrefixedInstruction(loc, 0x06000000386d0000);
728     relocateNoSym(loc, R_PPC64_TPREL34, val);
729     break;
730   case R_PPC64_TLSGD: {
731     // PC Relative Relaxation:
732     // Relax from bl __tls_get_addr@notoc(x@tlsgd) to
733     //            nop
734     // TOC Relaxation:
735     // Relax from bl __tls_get_addr(x@tlsgd)
736     //            nop
737     // to
738     //            nop
739     //            addi r3, r3, x@tprel@l
740     const uintptr_t locAsInt = reinterpret_cast<uintptr_t>(loc);
741     if (locAsInt % 4 == 0) {
742       write32(loc, NOP);            // nop
743       write32(loc + 4, 0x38630000); // addi r3, r3
744       // Since we are relocating a half16 type relocation and Loc + 4 points to
745       // the start of an instruction we need to advance the buffer by an extra
746       // 2 bytes on BE.
747       relocateNoSym(loc + 4 + (config->ekind == ELF64BEKind ? 2 : 0),
748                     R_PPC64_TPREL16_LO, val);
749     } else if (locAsInt % 4 == 1) {
750       write32(loc - 1, NOP);
751     } else {
752       errorOrWarn("R_PPC64_TLSGD has unexpected byte alignment");
753     }
754     break;
755   }
756   default:
757     llvm_unreachable("unsupported relocation for TLS GD to LE relaxation");
758   }
759 }
760 
761 void PPC64::relaxTlsLdToLe(uint8_t *loc, const Relocation &rel,
762                            uint64_t val) const {
763   // Reference: 3.7.4.3 of the 64-bit ELF V2 abi supplement.
764   // The local dynamic code sequence for a global `x` will look like:
765   // Instruction                    Relocation                Symbol
766   // addis r3, r2, x@got@tlsld@ha   R_PPC64_GOT_TLSLD16_HA      x
767   // addi  r3, r3, x@got@tlsld@l    R_PPC64_GOT_TLSLD16_LO      x
768   // bl __tls_get_addr(x@tlsgd)     R_PPC64_TLSLD               x
769   //                                R_PPC64_REL24               __tls_get_addr
770   // nop                            None                       None
771 
772   // Relaxing to local exec entails converting:
773   // addis r3, r2, x@got@tlsld@ha   into      nop
774   // addi  r3, r3, x@got@tlsld@l    into      addis r3, r13, 0
775   // bl __tls_get_addr(x@tlsgd)     into      nop
776   // nop                            into      addi r3, r3, 4096
777 
778   switch (rel.type) {
779   case R_PPC64_GOT_TLSLD16_HA:
780     writeFromHalf16(loc, NOP);
781     break;
782   case R_PPC64_GOT_TLSLD16_LO:
783     writeFromHalf16(loc, 0x3c6d0000); // addis r3, r13, 0
784     break;
785   case R_PPC64_GOT_TLSLD_PCREL34:
786     // Relax from paddi r3, 0, x1@got@tlsld@pcrel, 1 to
787     //            paddi r3, r13, 0x1000, 0
788     writePrefixedInstruction(loc, 0x06000000386d1000);
789     break;
790   case R_PPC64_TLSLD: {
791     // PC Relative Relaxation:
792     // Relax from bl __tls_get_addr@notoc(x@tlsld)
793     // to
794     //            nop
795     // TOC Relaxation:
796     // Relax from bl __tls_get_addr(x@tlsld)
797     //            nop
798     // to
799     //            nop
800     //            addi r3, r3, 4096
801     const uintptr_t locAsInt = reinterpret_cast<uintptr_t>(loc);
802     if (locAsInt % 4 == 0) {
803       write32(loc, NOP);
804       write32(loc + 4, 0x38631000); // addi r3, r3, 4096
805     } else if (locAsInt % 4 == 1) {
806       write32(loc - 1, NOP);
807     } else {
808       errorOrWarn("R_PPC64_TLSLD has unexpected byte alignment");
809     }
810     break;
811   }
812   case R_PPC64_DTPREL16:
813   case R_PPC64_DTPREL16_HA:
814   case R_PPC64_DTPREL16_HI:
815   case R_PPC64_DTPREL16_DS:
816   case R_PPC64_DTPREL16_LO:
817   case R_PPC64_DTPREL16_LO_DS:
818   case R_PPC64_DTPREL34:
819     relocate(loc, rel, val);
820     break;
821   default:
822     llvm_unreachable("unsupported relocation for TLS LD to LE relaxation");
823   }
824 }
825 
826 unsigned elf::getPPCDFormOp(unsigned secondaryOp) {
827   switch (secondaryOp) {
828   case LBZX:
829     return LBZ;
830   case LHZX:
831     return LHZ;
832   case LWZX:
833     return LWZ;
834   case LDX:
835     return LD;
836   case STBX:
837     return STB;
838   case STHX:
839     return STH;
840   case STWX:
841     return STW;
842   case STDX:
843     return STD;
844   case ADD:
845     return ADDI;
846   default:
847     return 0;
848   }
849 }
850 
851 void PPC64::relaxTlsIeToLe(uint8_t *loc, const Relocation &rel,
852                            uint64_t val) const {
853   // The initial exec code sequence for a global `x` will look like:
854   // Instruction                    Relocation                Symbol
855   // addis r9, r2, x@got@tprel@ha   R_PPC64_GOT_TPREL16_HA      x
856   // ld    r9, x@got@tprel@l(r9)    R_PPC64_GOT_TPREL16_LO_DS   x
857   // add r9, r9, x@tls              R_PPC64_TLS                 x
858 
859   // Relaxing to local exec entails converting:
860   // addis r9, r2, x@got@tprel@ha       into        nop
861   // ld r9, x@got@tprel@l(r9)           into        addis r9, r13, x@tprel@ha
862   // add r9, r9, x@tls                  into        addi r9, r9, x@tprel@l
863 
864   // x@tls R_PPC64_TLS is a relocation which does not compute anything,
865   // it is replaced with r13 (thread pointer).
866 
867   // The add instruction in the initial exec sequence has multiple variations
868   // that need to be handled. If we are building an address it will use an add
869   // instruction, if we are accessing memory it will use any of the X-form
870   // indexed load or store instructions.
871 
872   unsigned offset = (config->ekind == ELF64BEKind) ? 2 : 0;
873   switch (rel.type) {
874   case R_PPC64_GOT_TPREL16_HA:
875     write32(loc - offset, NOP);
876     break;
877   case R_PPC64_GOT_TPREL16_LO_DS:
878   case R_PPC64_GOT_TPREL16_DS: {
879     uint32_t regNo = read32(loc - offset) & 0x03E00000; // bits 6-10
880     write32(loc - offset, 0x3C0D0000 | regNo);          // addis RegNo, r13
881     relocateNoSym(loc, R_PPC64_TPREL16_HA, val);
882     break;
883   }
884   case R_PPC64_GOT_TPREL_PCREL34: {
885     const uint64_t pldRT = readPrefixedInstruction(loc) & 0x0000000003e00000;
886     // paddi RT(from pld), r13, symbol@tprel, 0
887     writePrefixedInstruction(loc, 0x06000000380d0000 | pldRT);
888     relocateNoSym(loc, R_PPC64_TPREL34, val);
889     break;
890   }
891   case R_PPC64_TLS: {
892     const uintptr_t locAsInt = reinterpret_cast<uintptr_t>(loc);
893     if (locAsInt % 4 == 0) {
894       uint32_t primaryOp = getPrimaryOpCode(read32(loc));
895       if (primaryOp != 31)
896         error("unrecognized instruction for IE to LE R_PPC64_TLS");
897       uint32_t secondaryOp = (read32(loc) & 0x000007FE) >> 1; // bits 21-30
898       uint32_t dFormOp = getPPCDFormOp(secondaryOp);
899       if (dFormOp == 0)
900         error("unrecognized instruction for IE to LE R_PPC64_TLS");
901       write32(loc, ((dFormOp << 26) | (read32(loc) & 0x03FFFFFF)));
902       relocateNoSym(loc + offset, R_PPC64_TPREL16_LO, val);
903     } else if (locAsInt % 4 == 1) {
904       // If the offset is not 4 byte aligned then we have a PCRel type reloc.
905       // This version of the relocation is offset by one byte from the
906       // instruction it references.
907       uint32_t tlsInstr = read32(loc - 1);
908       uint32_t primaryOp = getPrimaryOpCode(tlsInstr);
909       if (primaryOp != 31)
910         errorOrWarn("unrecognized instruction for IE to LE R_PPC64_TLS");
911       uint32_t secondaryOp = (tlsInstr & 0x000007FE) >> 1; // bits 21-30
912       // The add is a special case and should be turned into a nop. The paddi
913       // that comes before it will already have computed the address of the
914       // symbol.
915       if (secondaryOp == 266) {
916         // Check if the add uses the same result register as the input register.
917         uint32_t rt = (tlsInstr & 0x03E00000) >> 21; // bits 6-10
918         uint32_t ra = (tlsInstr & 0x001F0000) >> 16; // bits 11-15
919         if (ra == rt) {
920           write32(loc - 1, NOP);
921         } else {
922           // mr rt, ra
923           write32(loc - 1, 0x7C000378 | (rt << 16) | (ra << 21) | (ra << 11));
924         }
925       } else {
926         uint32_t dFormOp = getPPCDFormOp(secondaryOp);
927         if (dFormOp == 0)
928           errorOrWarn("unrecognized instruction for IE to LE R_PPC64_TLS");
929         write32(loc - 1, ((dFormOp << 26) | (tlsInstr & 0x03FF0000)));
930       }
931     } else {
932       errorOrWarn("R_PPC64_TLS must be either 4 byte aligned or one byte "
933                   "offset from 4 byte aligned");
934     }
935     break;
936   }
937   default:
938     llvm_unreachable("unknown relocation for IE to LE");
939     break;
940   }
941 }
942 
943 RelExpr PPC64::getRelExpr(RelType type, const Symbol &s,
944                           const uint8_t *loc) const {
945   switch (type) {
946   case R_PPC64_NONE:
947     return R_NONE;
948   case R_PPC64_ADDR16:
949   case R_PPC64_ADDR16_DS:
950   case R_PPC64_ADDR16_HA:
951   case R_PPC64_ADDR16_HI:
952   case R_PPC64_ADDR16_HIGH:
953   case R_PPC64_ADDR16_HIGHER:
954   case R_PPC64_ADDR16_HIGHERA:
955   case R_PPC64_ADDR16_HIGHEST:
956   case R_PPC64_ADDR16_HIGHESTA:
957   case R_PPC64_ADDR16_LO:
958   case R_PPC64_ADDR16_LO_DS:
959   case R_PPC64_ADDR32:
960   case R_PPC64_ADDR64:
961     return R_ABS;
962   case R_PPC64_GOT16:
963   case R_PPC64_GOT16_DS:
964   case R_PPC64_GOT16_HA:
965   case R_PPC64_GOT16_HI:
966   case R_PPC64_GOT16_LO:
967   case R_PPC64_GOT16_LO_DS:
968     return R_GOT_OFF;
969   case R_PPC64_TOC16:
970   case R_PPC64_TOC16_DS:
971   case R_PPC64_TOC16_HI:
972   case R_PPC64_TOC16_LO:
973     return R_GOTREL;
974   case R_PPC64_GOT_PCREL34:
975   case R_PPC64_GOT_TPREL_PCREL34:
976   case R_PPC64_PCREL_OPT:
977     return R_GOT_PC;
978   case R_PPC64_TOC16_HA:
979   case R_PPC64_TOC16_LO_DS:
980     return config->tocOptimize ? R_PPC64_RELAX_TOC : R_GOTREL;
981   case R_PPC64_TOC:
982     return R_PPC64_TOCBASE;
983   case R_PPC64_REL14:
984   case R_PPC64_REL24:
985     return R_PPC64_CALL_PLT;
986   case R_PPC64_REL24_NOTOC:
987     return R_PLT_PC;
988   case R_PPC64_REL16_LO:
989   case R_PPC64_REL16_HA:
990   case R_PPC64_REL16_HI:
991   case R_PPC64_REL32:
992   case R_PPC64_REL64:
993   case R_PPC64_PCREL34:
994     return R_PC;
995   case R_PPC64_GOT_TLSGD16:
996   case R_PPC64_GOT_TLSGD16_HA:
997   case R_PPC64_GOT_TLSGD16_HI:
998   case R_PPC64_GOT_TLSGD16_LO:
999     return R_TLSGD_GOT;
1000   case R_PPC64_GOT_TLSGD_PCREL34:
1001     return R_TLSGD_PC;
1002   case R_PPC64_GOT_TLSLD16:
1003   case R_PPC64_GOT_TLSLD16_HA:
1004   case R_PPC64_GOT_TLSLD16_HI:
1005   case R_PPC64_GOT_TLSLD16_LO:
1006     return R_TLSLD_GOT;
1007   case R_PPC64_GOT_TLSLD_PCREL34:
1008     return R_TLSLD_PC;
1009   case R_PPC64_GOT_TPREL16_HA:
1010   case R_PPC64_GOT_TPREL16_LO_DS:
1011   case R_PPC64_GOT_TPREL16_DS:
1012   case R_PPC64_GOT_TPREL16_HI:
1013     return R_GOT_OFF;
1014   case R_PPC64_GOT_DTPREL16_HA:
1015   case R_PPC64_GOT_DTPREL16_LO_DS:
1016   case R_PPC64_GOT_DTPREL16_DS:
1017   case R_PPC64_GOT_DTPREL16_HI:
1018     return R_TLSLD_GOT_OFF;
1019   case R_PPC64_TPREL16:
1020   case R_PPC64_TPREL16_HA:
1021   case R_PPC64_TPREL16_LO:
1022   case R_PPC64_TPREL16_HI:
1023   case R_PPC64_TPREL16_DS:
1024   case R_PPC64_TPREL16_LO_DS:
1025   case R_PPC64_TPREL16_HIGHER:
1026   case R_PPC64_TPREL16_HIGHERA:
1027   case R_PPC64_TPREL16_HIGHEST:
1028   case R_PPC64_TPREL16_HIGHESTA:
1029   case R_PPC64_TPREL34:
1030     return R_TPREL;
1031   case R_PPC64_DTPREL16:
1032   case R_PPC64_DTPREL16_DS:
1033   case R_PPC64_DTPREL16_HA:
1034   case R_PPC64_DTPREL16_HI:
1035   case R_PPC64_DTPREL16_HIGHER:
1036   case R_PPC64_DTPREL16_HIGHERA:
1037   case R_PPC64_DTPREL16_HIGHEST:
1038   case R_PPC64_DTPREL16_HIGHESTA:
1039   case R_PPC64_DTPREL16_LO:
1040   case R_PPC64_DTPREL16_LO_DS:
1041   case R_PPC64_DTPREL64:
1042   case R_PPC64_DTPREL34:
1043     return R_DTPREL;
1044   case R_PPC64_TLSGD:
1045     return R_TLSDESC_CALL;
1046   case R_PPC64_TLSLD:
1047     return R_TLSLD_HINT;
1048   case R_PPC64_TLS:
1049     return R_TLSIE_HINT;
1050   default:
1051     error(getErrorLocation(loc) + "unknown relocation (" + Twine(type) +
1052           ") against symbol " + toString(s));
1053     return R_NONE;
1054   }
1055 }
1056 
1057 RelType PPC64::getDynRel(RelType type) const {
1058   if (type == R_PPC64_ADDR64 || type == R_PPC64_TOC)
1059     return R_PPC64_ADDR64;
1060   return R_PPC64_NONE;
1061 }
1062 
1063 int64_t PPC64::getImplicitAddend(const uint8_t *buf, RelType type) const {
1064   switch (type) {
1065   case R_PPC64_NONE:
1066     return 0;
1067   case R_PPC64_REL32:
1068     return SignExtend64<32>(read32(buf));
1069   case R_PPC64_ADDR64:
1070   case R_PPC64_REL64:
1071     return read64(buf);
1072   default:
1073     internalLinkerError(getErrorLocation(buf),
1074                         "cannot read addend for relocation " + toString(type));
1075     return 0;
1076   }
1077 }
1078 
1079 void PPC64::writeGotHeader(uint8_t *buf) const {
1080   write64(buf, getPPC64TocBase());
1081 }
1082 
1083 void PPC64::writePltHeader(uint8_t *buf) const {
1084   // The generic resolver stub goes first.
1085   write32(buf +  0, 0x7c0802a6); // mflr r0
1086   write32(buf +  4, 0x429f0005); // bcl  20,4*cr7+so,8 <_glink+0x8>
1087   write32(buf +  8, 0x7d6802a6); // mflr r11
1088   write32(buf + 12, 0x7c0803a6); // mtlr r0
1089   write32(buf + 16, 0x7d8b6050); // subf r12, r11, r12
1090   write32(buf + 20, 0x380cffcc); // subi r0,r12,52
1091   write32(buf + 24, 0x7800f082); // srdi r0,r0,62,2
1092   write32(buf + 28, 0xe98b002c); // ld   r12,44(r11)
1093   write32(buf + 32, 0x7d6c5a14); // add  r11,r12,r11
1094   write32(buf + 36, 0xe98b0000); // ld   r12,0(r11)
1095   write32(buf + 40, 0xe96b0008); // ld   r11,8(r11)
1096   write32(buf + 44, 0x7d8903a6); // mtctr   r12
1097   write32(buf + 48, 0x4e800420); // bctr
1098 
1099   // The 'bcl' instruction will set the link register to the address of the
1100   // following instruction ('mflr r11'). Here we store the offset from that
1101   // instruction  to the first entry in the GotPlt section.
1102   int64_t gotPltOffset = in.gotPlt->getVA() - (in.plt->getVA() + 8);
1103   write64(buf + 52, gotPltOffset);
1104 }
1105 
1106 void PPC64::writePlt(uint8_t *buf, const Symbol &sym,
1107                      uint64_t /*pltEntryAddr*/) const {
1108   int32_t offset = pltHeaderSize + sym.getPltIdx() * pltEntrySize;
1109   // bl __glink_PLTresolve
1110   write32(buf, 0x48000000 | ((-offset) & 0x03FFFFFc));
1111 }
1112 
1113 void PPC64::writeIplt(uint8_t *buf, const Symbol &sym,
1114                       uint64_t /*pltEntryAddr*/) const {
1115   writePPC64LoadAndBranch(buf, sym.getGotPltVA() - getPPC64TocBase());
1116 }
1117 
1118 static std::pair<RelType, uint64_t> toAddr16Rel(RelType type, uint64_t val) {
1119   // Relocations relative to the toc-base need to be adjusted by the Toc offset.
1120   uint64_t tocBiasedVal = val - ppc64TocOffset;
1121   // Relocations relative to dtv[dtpmod] need to be adjusted by the DTP offset.
1122   uint64_t dtpBiasedVal = val - dynamicThreadPointerOffset;
1123 
1124   switch (type) {
1125   // TOC biased relocation.
1126   case R_PPC64_GOT16:
1127   case R_PPC64_GOT_TLSGD16:
1128   case R_PPC64_GOT_TLSLD16:
1129   case R_PPC64_TOC16:
1130     return {R_PPC64_ADDR16, tocBiasedVal};
1131   case R_PPC64_GOT16_DS:
1132   case R_PPC64_TOC16_DS:
1133   case R_PPC64_GOT_TPREL16_DS:
1134   case R_PPC64_GOT_DTPREL16_DS:
1135     return {R_PPC64_ADDR16_DS, tocBiasedVal};
1136   case R_PPC64_GOT16_HA:
1137   case R_PPC64_GOT_TLSGD16_HA:
1138   case R_PPC64_GOT_TLSLD16_HA:
1139   case R_PPC64_GOT_TPREL16_HA:
1140   case R_PPC64_GOT_DTPREL16_HA:
1141   case R_PPC64_TOC16_HA:
1142     return {R_PPC64_ADDR16_HA, tocBiasedVal};
1143   case R_PPC64_GOT16_HI:
1144   case R_PPC64_GOT_TLSGD16_HI:
1145   case R_PPC64_GOT_TLSLD16_HI:
1146   case R_PPC64_GOT_TPREL16_HI:
1147   case R_PPC64_GOT_DTPREL16_HI:
1148   case R_PPC64_TOC16_HI:
1149     return {R_PPC64_ADDR16_HI, tocBiasedVal};
1150   case R_PPC64_GOT16_LO:
1151   case R_PPC64_GOT_TLSGD16_LO:
1152   case R_PPC64_GOT_TLSLD16_LO:
1153   case R_PPC64_TOC16_LO:
1154     return {R_PPC64_ADDR16_LO, tocBiasedVal};
1155   case R_PPC64_GOT16_LO_DS:
1156   case R_PPC64_TOC16_LO_DS:
1157   case R_PPC64_GOT_TPREL16_LO_DS:
1158   case R_PPC64_GOT_DTPREL16_LO_DS:
1159     return {R_PPC64_ADDR16_LO_DS, tocBiasedVal};
1160 
1161   // Dynamic Thread pointer biased relocation types.
1162   case R_PPC64_DTPREL16:
1163     return {R_PPC64_ADDR16, dtpBiasedVal};
1164   case R_PPC64_DTPREL16_DS:
1165     return {R_PPC64_ADDR16_DS, dtpBiasedVal};
1166   case R_PPC64_DTPREL16_HA:
1167     return {R_PPC64_ADDR16_HA, dtpBiasedVal};
1168   case R_PPC64_DTPREL16_HI:
1169     return {R_PPC64_ADDR16_HI, dtpBiasedVal};
1170   case R_PPC64_DTPREL16_HIGHER:
1171     return {R_PPC64_ADDR16_HIGHER, dtpBiasedVal};
1172   case R_PPC64_DTPREL16_HIGHERA:
1173     return {R_PPC64_ADDR16_HIGHERA, dtpBiasedVal};
1174   case R_PPC64_DTPREL16_HIGHEST:
1175     return {R_PPC64_ADDR16_HIGHEST, dtpBiasedVal};
1176   case R_PPC64_DTPREL16_HIGHESTA:
1177     return {R_PPC64_ADDR16_HIGHESTA, dtpBiasedVal};
1178   case R_PPC64_DTPREL16_LO:
1179     return {R_PPC64_ADDR16_LO, dtpBiasedVal};
1180   case R_PPC64_DTPREL16_LO_DS:
1181     return {R_PPC64_ADDR16_LO_DS, dtpBiasedVal};
1182   case R_PPC64_DTPREL64:
1183     return {R_PPC64_ADDR64, dtpBiasedVal};
1184 
1185   default:
1186     return {type, val};
1187   }
1188 }
1189 
1190 static bool isTocOptType(RelType type) {
1191   switch (type) {
1192   case R_PPC64_GOT16_HA:
1193   case R_PPC64_GOT16_LO_DS:
1194   case R_PPC64_TOC16_HA:
1195   case R_PPC64_TOC16_LO_DS:
1196   case R_PPC64_TOC16_LO:
1197     return true;
1198   default:
1199     return false;
1200   }
1201 }
1202 
1203 void PPC64::relocate(uint8_t *loc, const Relocation &rel, uint64_t val) const {
1204   RelType type = rel.type;
1205   bool shouldTocOptimize =  isTocOptType(type);
1206   // For dynamic thread pointer relative, toc-relative, and got-indirect
1207   // relocations, proceed in terms of the corresponding ADDR16 relocation type.
1208   std::tie(type, val) = toAddr16Rel(type, val);
1209 
1210   switch (type) {
1211   case R_PPC64_ADDR14: {
1212     checkAlignment(loc, val, 4, rel);
1213     // Preserve the AA/LK bits in the branch instruction
1214     uint8_t aalk = loc[3];
1215     write16(loc + 2, (aalk & 3) | (val & 0xfffc));
1216     break;
1217   }
1218   case R_PPC64_ADDR16:
1219     checkIntUInt(loc, val, 16, rel);
1220     write16(loc, val);
1221     break;
1222   case R_PPC64_ADDR32:
1223     checkIntUInt(loc, val, 32, rel);
1224     write32(loc, val);
1225     break;
1226   case R_PPC64_ADDR16_DS:
1227   case R_PPC64_TPREL16_DS: {
1228     checkInt(loc, val, 16, rel);
1229     // DQ-form instructions use bits 28-31 as part of the instruction encoding
1230     // DS-form instructions only use bits 30-31.
1231     uint16_t mask = isDQFormInstruction(readFromHalf16(loc)) ? 0xf : 0x3;
1232     checkAlignment(loc, lo(val), mask + 1, rel);
1233     write16(loc, (read16(loc) & mask) | lo(val));
1234   } break;
1235   case R_PPC64_ADDR16_HA:
1236   case R_PPC64_REL16_HA:
1237   case R_PPC64_TPREL16_HA:
1238     if (config->tocOptimize && shouldTocOptimize && ha(val) == 0)
1239       writeFromHalf16(loc, NOP);
1240     else {
1241       checkInt(loc, val + 0x8000, 32, rel);
1242       write16(loc, ha(val));
1243     }
1244     break;
1245   case R_PPC64_ADDR16_HI:
1246   case R_PPC64_REL16_HI:
1247   case R_PPC64_TPREL16_HI:
1248     checkInt(loc, val, 32, rel);
1249     write16(loc, hi(val));
1250     break;
1251   case R_PPC64_ADDR16_HIGH:
1252     write16(loc, hi(val));
1253     break;
1254   case R_PPC64_ADDR16_HIGHER:
1255   case R_PPC64_TPREL16_HIGHER:
1256     write16(loc, higher(val));
1257     break;
1258   case R_PPC64_ADDR16_HIGHERA:
1259   case R_PPC64_TPREL16_HIGHERA:
1260     write16(loc, highera(val));
1261     break;
1262   case R_PPC64_ADDR16_HIGHEST:
1263   case R_PPC64_TPREL16_HIGHEST:
1264     write16(loc, highest(val));
1265     break;
1266   case R_PPC64_ADDR16_HIGHESTA:
1267   case R_PPC64_TPREL16_HIGHESTA:
1268     write16(loc, highesta(val));
1269     break;
1270   case R_PPC64_ADDR16_LO:
1271   case R_PPC64_REL16_LO:
1272   case R_PPC64_TPREL16_LO:
1273     // When the high-adjusted part of a toc relocation evaluates to 0, it is
1274     // changed into a nop. The lo part then needs to be updated to use the
1275     // toc-pointer register r2, as the base register.
1276     if (config->tocOptimize && shouldTocOptimize && ha(val) == 0) {
1277       uint32_t insn = readFromHalf16(loc);
1278       if (isInstructionUpdateForm(insn))
1279         error(getErrorLocation(loc) +
1280               "can't toc-optimize an update instruction: 0x" +
1281               utohexstr(insn));
1282       writeFromHalf16(loc, (insn & 0xffe00000) | 0x00020000 | lo(val));
1283     } else {
1284       write16(loc, lo(val));
1285     }
1286     break;
1287   case R_PPC64_ADDR16_LO_DS:
1288   case R_PPC64_TPREL16_LO_DS: {
1289     // DQ-form instructions use bits 28-31 as part of the instruction encoding
1290     // DS-form instructions only use bits 30-31.
1291     uint32_t insn = readFromHalf16(loc);
1292     uint16_t mask = isDQFormInstruction(insn) ? 0xf : 0x3;
1293     checkAlignment(loc, lo(val), mask + 1, rel);
1294     if (config->tocOptimize && shouldTocOptimize && ha(val) == 0) {
1295       // When the high-adjusted part of a toc relocation evaluates to 0, it is
1296       // changed into a nop. The lo part then needs to be updated to use the toc
1297       // pointer register r2, as the base register.
1298       if (isInstructionUpdateForm(insn))
1299         error(getErrorLocation(loc) +
1300               "Can't toc-optimize an update instruction: 0x" +
1301               Twine::utohexstr(insn));
1302       insn &= 0xffe00000 | mask;
1303       writeFromHalf16(loc, insn | 0x00020000 | lo(val));
1304     } else {
1305       write16(loc, (read16(loc) & mask) | lo(val));
1306     }
1307   } break;
1308   case R_PPC64_TPREL16:
1309     checkInt(loc, val, 16, rel);
1310     write16(loc, val);
1311     break;
1312   case R_PPC64_REL32:
1313     checkInt(loc, val, 32, rel);
1314     write32(loc, val);
1315     break;
1316   case R_PPC64_ADDR64:
1317   case R_PPC64_REL64:
1318   case R_PPC64_TOC:
1319     write64(loc, val);
1320     break;
1321   case R_PPC64_REL14: {
1322     uint32_t mask = 0x0000FFFC;
1323     checkInt(loc, val, 16, rel);
1324     checkAlignment(loc, val, 4, rel);
1325     write32(loc, (read32(loc) & ~mask) | (val & mask));
1326     break;
1327   }
1328   case R_PPC64_REL24:
1329   case R_PPC64_REL24_NOTOC: {
1330     uint32_t mask = 0x03FFFFFC;
1331     checkInt(loc, val, 26, rel);
1332     checkAlignment(loc, val, 4, rel);
1333     write32(loc, (read32(loc) & ~mask) | (val & mask));
1334     break;
1335   }
1336   case R_PPC64_DTPREL64:
1337     write64(loc, val - dynamicThreadPointerOffset);
1338     break;
1339   case R_PPC64_DTPREL34:
1340     // The Dynamic Thread Vector actually points 0x8000 bytes past the start
1341     // of the TLS block. Therefore, in the case of R_PPC64_DTPREL34 we first
1342     // need to subtract that value then fallthrough to the general case.
1343     val -= dynamicThreadPointerOffset;
1344     LLVM_FALLTHROUGH;
1345   case R_PPC64_PCREL34:
1346   case R_PPC64_GOT_PCREL34:
1347   case R_PPC64_GOT_TLSGD_PCREL34:
1348   case R_PPC64_GOT_TLSLD_PCREL34:
1349   case R_PPC64_GOT_TPREL_PCREL34:
1350   case R_PPC64_TPREL34: {
1351     const uint64_t si0Mask = 0x00000003ffff0000;
1352     const uint64_t si1Mask = 0x000000000000ffff;
1353     const uint64_t fullMask = 0x0003ffff0000ffff;
1354     checkInt(loc, val, 34, rel);
1355 
1356     uint64_t instr = readPrefixedInstruction(loc) & ~fullMask;
1357     writePrefixedInstruction(loc, instr | ((val & si0Mask) << 16) |
1358                              (val & si1Mask));
1359     break;
1360   }
1361   // If we encounter a PCREL_OPT relocation that we won't optimize.
1362   case R_PPC64_PCREL_OPT:
1363     break;
1364   default:
1365     llvm_unreachable("unknown relocation");
1366   }
1367 }
1368 
1369 bool PPC64::needsThunk(RelExpr expr, RelType type, const InputFile *file,
1370                        uint64_t branchAddr, const Symbol &s, int64_t a) const {
1371   if (type != R_PPC64_REL14 && type != R_PPC64_REL24 &&
1372       type != R_PPC64_REL24_NOTOC)
1373     return false;
1374 
1375   // If a function is in the Plt it needs to be called with a call-stub.
1376   if (s.isInPlt())
1377     return true;
1378 
1379   // This check looks at the st_other bits of the callee with relocation
1380   // R_PPC64_REL14 or R_PPC64_REL24. If the value is 1, then the callee
1381   // clobbers the TOC and we need an R2 save stub.
1382   if (type != R_PPC64_REL24_NOTOC && (s.stOther >> 5) == 1)
1383     return true;
1384 
1385   if (type == R_PPC64_REL24_NOTOC && (s.stOther >> 5) > 1)
1386     return true;
1387 
1388   // An undefined weak symbol not in a PLT does not need a thunk. If it is
1389   // hidden, its binding has been converted to local, so we just check
1390   // isUndefined() here. A undefined non-weak symbol has been errored.
1391   if (s.isUndefined())
1392     return false;
1393 
1394   // If the offset exceeds the range of the branch type then it will need
1395   // a range-extending thunk.
1396   // See the comment in getRelocTargetVA() about R_PPC64_CALL.
1397   return !inBranchRange(type, branchAddr,
1398                         s.getVA(a) +
1399                             getPPC64GlobalEntryToLocalEntryOffset(s.stOther));
1400 }
1401 
1402 uint32_t PPC64::getThunkSectionSpacing() const {
1403   // See comment in Arch/ARM.cpp for a more detailed explanation of
1404   // getThunkSectionSpacing(). For PPC64 we pick the constant here based on
1405   // R_PPC64_REL24, which is used by unconditional branch instructions.
1406   // 0x2000000 = (1 << 24-1) * 4
1407   return 0x2000000;
1408 }
1409 
1410 bool PPC64::inBranchRange(RelType type, uint64_t src, uint64_t dst) const {
1411   int64_t offset = dst - src;
1412   if (type == R_PPC64_REL14)
1413     return isInt<16>(offset);
1414   if (type == R_PPC64_REL24 || type == R_PPC64_REL24_NOTOC)
1415     return isInt<26>(offset);
1416   llvm_unreachable("unsupported relocation type used in branch");
1417 }
1418 
1419 RelExpr PPC64::adjustTlsExpr(RelType type, RelExpr expr) const {
1420   if (type != R_PPC64_GOT_TLSGD_PCREL34 && expr == R_RELAX_TLS_GD_TO_IE)
1421     return R_RELAX_TLS_GD_TO_IE_GOT_OFF;
1422   if (expr == R_RELAX_TLS_LD_TO_LE)
1423     return R_RELAX_TLS_LD_TO_LE_ABS;
1424   return expr;
1425 }
1426 
1427 RelExpr PPC64::adjustGotPcExpr(RelType type, int64_t addend,
1428                                const uint8_t *loc) const {
1429   if ((type == R_PPC64_GOT_PCREL34 || type == R_PPC64_PCREL_OPT) &&
1430       config->pcRelOptimize) {
1431     // It only makes sense to optimize pld since paddi means that the address
1432     // of the object in the GOT is required rather than the object itself.
1433     if ((readPrefixedInstruction(loc) & 0xfc000000) == 0xe4000000)
1434       return R_PPC64_RELAX_GOT_PC;
1435   }
1436   return R_GOT_PC;
1437 }
1438 
1439 // Reference: 3.7.4.1 of the 64-bit ELF V2 abi supplement.
1440 // The general dynamic code sequence for a global `x` uses 4 instructions.
1441 // Instruction                    Relocation                Symbol
1442 // addis r3, r2, x@got@tlsgd@ha   R_PPC64_GOT_TLSGD16_HA      x
1443 // addi  r3, r3, x@got@tlsgd@l    R_PPC64_GOT_TLSGD16_LO      x
1444 // bl __tls_get_addr(x@tlsgd)     R_PPC64_TLSGD               x
1445 //                                R_PPC64_REL24               __tls_get_addr
1446 // nop                            None                       None
1447 //
1448 // Relaxing to initial-exec entails:
1449 // 1) Convert the addis/addi pair that builds the address of the tls_index
1450 //    struct for 'x' to an addis/ld pair that loads an offset from a got-entry.
1451 // 2) Convert the call to __tls_get_addr to a nop.
1452 // 3) Convert the nop following the call to an add of the loaded offset to the
1453 //    thread pointer.
1454 // Since the nop must directly follow the call, the R_PPC64_TLSGD relocation is
1455 // used as the relaxation hint for both steps 2 and 3.
1456 void PPC64::relaxTlsGdToIe(uint8_t *loc, const Relocation &rel,
1457                            uint64_t val) const {
1458   switch (rel.type) {
1459   case R_PPC64_GOT_TLSGD16_HA:
1460     // This is relaxed from addis rT, r2, sym@got@tlsgd@ha to
1461     //                      addis rT, r2, sym@got@tprel@ha.
1462     relocateNoSym(loc, R_PPC64_GOT_TPREL16_HA, val);
1463     return;
1464   case R_PPC64_GOT_TLSGD16:
1465   case R_PPC64_GOT_TLSGD16_LO: {
1466     // Relax from addi  r3, rA, sym@got@tlsgd@l to
1467     //            ld r3, sym@got@tprel@l(rA)
1468     uint32_t ra = (readFromHalf16(loc) & (0x1f << 16));
1469     writeFromHalf16(loc, 0xe8600000 | ra);
1470     relocateNoSym(loc, R_PPC64_GOT_TPREL16_LO_DS, val);
1471     return;
1472   }
1473   case R_PPC64_GOT_TLSGD_PCREL34: {
1474     // Relax from paddi r3, 0, sym@got@tlsgd@pcrel, 1 to
1475     //            pld r3, sym@got@tprel@pcrel
1476     writePrefixedInstruction(loc, 0x04100000e4600000);
1477     relocateNoSym(loc, R_PPC64_GOT_TPREL_PCREL34, val);
1478     return;
1479   }
1480   case R_PPC64_TLSGD: {
1481     // PC Relative Relaxation:
1482     // Relax from bl __tls_get_addr@notoc(x@tlsgd) to
1483     //            nop
1484     // TOC Relaxation:
1485     // Relax from bl __tls_get_addr(x@tlsgd)
1486     //            nop
1487     // to
1488     //            nop
1489     //            add r3, r3, r13
1490     const uintptr_t locAsInt = reinterpret_cast<uintptr_t>(loc);
1491     if (locAsInt % 4 == 0) {
1492       write32(loc, NOP);            // bl __tls_get_addr(sym@tlsgd) --> nop
1493       write32(loc + 4, 0x7c636A14); // nop --> add r3, r3, r13
1494     } else if (locAsInt % 4 == 1) {
1495       // bl __tls_get_addr(sym@tlsgd) --> add r3, r3, r13
1496       write32(loc - 1, 0x7c636a14);
1497     } else {
1498       errorOrWarn("R_PPC64_TLSGD has unexpected byte alignment");
1499     }
1500     return;
1501   }
1502   default:
1503     llvm_unreachable("unsupported relocation for TLS GD to IE relaxation");
1504   }
1505 }
1506 
1507 // The prologue for a split-stack function is expected to look roughly
1508 // like this:
1509 //    .Lglobal_entry_point:
1510 //      # TOC pointer initialization.
1511 //      ...
1512 //    .Llocal_entry_point:
1513 //      # load the __private_ss member of the threads tcbhead.
1514 //      ld r0,-0x7000-64(r13)
1515 //      # subtract the functions stack size from the stack pointer.
1516 //      addis r12, r1, ha(-stack-frame size)
1517 //      addi  r12, r12, l(-stack-frame size)
1518 //      # compare needed to actual and branch to allocate_more_stack if more
1519 //      # space is needed, otherwise fallthrough to 'normal' function body.
1520 //      cmpld cr7,r12,r0
1521 //      blt- cr7, .Lallocate_more_stack
1522 //
1523 // -) The allocate_more_stack block might be placed after the split-stack
1524 //    prologue and the `blt-` replaced with a `bge+ .Lnormal_func_body`
1525 //    instead.
1526 // -) If either the addis or addi is not needed due to the stack size being
1527 //    smaller then 32K or a multiple of 64K they will be replaced with a nop,
1528 //    but there will always be 2 instructions the linker can overwrite for the
1529 //    adjusted stack size.
1530 //
1531 // The linkers job here is to increase the stack size used in the addis/addi
1532 // pair by split-stack-size-adjust.
1533 // addis r12, r1, ha(-stack-frame size - split-stack-adjust-size)
1534 // addi  r12, r12, l(-stack-frame size - split-stack-adjust-size)
1535 bool PPC64::adjustPrologueForCrossSplitStack(uint8_t *loc, uint8_t *end,
1536                                              uint8_t stOther) const {
1537   // If the caller has a global entry point adjust the buffer past it. The start
1538   // of the split-stack prologue will be at the local entry point.
1539   loc += getPPC64GlobalEntryToLocalEntryOffset(stOther);
1540 
1541   // At the very least we expect to see a load of some split-stack data from the
1542   // tcb, and 2 instructions that calculate the ending stack address this
1543   // function will require. If there is not enough room for at least 3
1544   // instructions it can't be a split-stack prologue.
1545   if (loc + 12 >= end)
1546     return false;
1547 
1548   // First instruction must be `ld r0, -0x7000-64(r13)`
1549   if (read32(loc) != 0xe80d8fc0)
1550     return false;
1551 
1552   int16_t hiImm = 0;
1553   int16_t loImm = 0;
1554   // First instruction can be either an addis if the frame size is larger then
1555   // 32K, or an addi if the size is less then 32K.
1556   int32_t firstInstr = read32(loc + 4);
1557   if (getPrimaryOpCode(firstInstr) == 15) {
1558     hiImm = firstInstr & 0xFFFF;
1559   } else if (getPrimaryOpCode(firstInstr) == 14) {
1560     loImm = firstInstr & 0xFFFF;
1561   } else {
1562     return false;
1563   }
1564 
1565   // Second instruction is either an addi or a nop. If the first instruction was
1566   // an addi then LoImm is set and the second instruction must be a nop.
1567   uint32_t secondInstr = read32(loc + 8);
1568   if (!loImm && getPrimaryOpCode(secondInstr) == 14) {
1569     loImm = secondInstr & 0xFFFF;
1570   } else if (secondInstr != NOP) {
1571     return false;
1572   }
1573 
1574   // The register operands of the first instruction should be the stack-pointer
1575   // (r1) as the input (RA) and r12 as the output (RT). If the second
1576   // instruction is not a nop, then it should use r12 as both input and output.
1577   auto checkRegOperands = [](uint32_t instr, uint8_t expectedRT,
1578                              uint8_t expectedRA) {
1579     return ((instr & 0x3E00000) >> 21 == expectedRT) &&
1580            ((instr & 0x1F0000) >> 16 == expectedRA);
1581   };
1582   if (!checkRegOperands(firstInstr, 12, 1))
1583     return false;
1584   if (secondInstr != NOP && !checkRegOperands(secondInstr, 12, 12))
1585     return false;
1586 
1587   int32_t stackFrameSize = (hiImm * 65536) + loImm;
1588   // Check that the adjusted size doesn't overflow what we can represent with 2
1589   // instructions.
1590   if (stackFrameSize < config->splitStackAdjustSize + INT32_MIN) {
1591     error(getErrorLocation(loc) + "split-stack prologue adjustment overflows");
1592     return false;
1593   }
1594 
1595   int32_t adjustedStackFrameSize =
1596       stackFrameSize - config->splitStackAdjustSize;
1597 
1598   loImm = adjustedStackFrameSize & 0xFFFF;
1599   hiImm = (adjustedStackFrameSize + 0x8000) >> 16;
1600   if (hiImm) {
1601     write32(loc + 4, 0x3D810000 | (uint16_t)hiImm);
1602     // If the low immediate is zero the second instruction will be a nop.
1603     secondInstr = loImm ? 0x398C0000 | (uint16_t)loImm : NOP;
1604     write32(loc + 8, secondInstr);
1605   } else {
1606     // addi r12, r1, imm
1607     write32(loc + 4, (0x39810000) | (uint16_t)loImm);
1608     write32(loc + 8, NOP);
1609   }
1610 
1611   return true;
1612 }
1613 
1614 TargetInfo *elf::getPPC64TargetInfo() {
1615   static PPC64 target;
1616   return &target;
1617 }
1618