xref: /llvm-project-15.0.7/lld/ELF/Arch/PPC64.cpp (revision 2ea3c8a5)
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/ErrorHandler.h"
15 #include "lld/Common/Memory.h"
16 #include "llvm/Support/Endian.h"
17 
18 using namespace llvm;
19 using namespace llvm::object;
20 using namespace llvm::support::endian;
21 using namespace llvm::ELF;
22 using namespace lld;
23 using namespace lld::elf;
24 
25 constexpr uint64_t ppc64TocOffset = 0x8000;
26 constexpr uint64_t dynamicThreadPointerOffset = 0x8000;
27 
28 // The instruction encoding of bits 21-30 from the ISA for the Xform and Dform
29 // instructions that can be used as part of the initial exec TLS sequence.
30 enum XFormOpcd {
31   LBZX = 87,
32   LHZX = 279,
33   LWZX = 23,
34   LDX = 21,
35   STBX = 215,
36   STHX = 407,
37   STWX = 151,
38   STDX = 149,
39   ADD = 266,
40 };
41 
42 enum DFormOpcd {
43   LBZ = 34,
44   LBZU = 35,
45   LHZ = 40,
46   LHZU = 41,
47   LHAU = 43,
48   LWZ = 32,
49   LWZU = 33,
50   LFSU = 49,
51   LD = 58,
52   LFDU = 51,
53   STB = 38,
54   STBU = 39,
55   STH = 44,
56   STHU = 45,
57   STW = 36,
58   STWU = 37,
59   STFSU = 53,
60   STFDU = 55,
61   STD = 62,
62   ADDI = 14
63 };
64 
65 constexpr uint32_t NOP = 0x60000000;
66 
67 enum class PPCLegacyInsn : uint32_t {
68   NOINSN = 0,
69   // Loads.
70   LBZ = 0x88000000,
71   LHZ = 0xa0000000,
72   LWZ = 0x80000000,
73   LHA = 0xa8000000,
74   LWA = 0xe8000002,
75   LD = 0xe8000000,
76   LFS = 0xC0000000,
77   LXSSP = 0xe4000003,
78   LFD = 0xc8000000,
79   LXSD = 0xe4000002,
80   LXV = 0xf4000001,
81   LXVP = 0x18000000,
82 
83   // Stores.
84   STB = 0x98000000,
85   STH = 0xb0000000,
86   STW = 0x90000000,
87   STD = 0xf8000000,
88   STFS = 0xd0000000,
89   STXSSP = 0xf4000003,
90   STFD = 0xd8000000,
91   STXSD = 0xf4000002,
92   STXV = 0xf4000005,
93   STXVP = 0x18000001
94 };
95 enum class PPCPrefixedInsn : uint64_t {
96   NOINSN = 0,
97   PREFIX_MLS = 0x0610000000000000,
98   PREFIX_8LS = 0x0410000000000000,
99 
100   // Loads.
101   PLBZ = PREFIX_MLS,
102   PLHZ = PREFIX_MLS,
103   PLWZ = PREFIX_MLS,
104   PLHA = PREFIX_MLS,
105   PLWA = PREFIX_8LS | 0xa4000000,
106   PLD = PREFIX_8LS | 0xe4000000,
107   PLFS = PREFIX_MLS,
108   PLXSSP = PREFIX_8LS | 0xac000000,
109   PLFD = PREFIX_MLS,
110   PLXSD = PREFIX_8LS | 0xa8000000,
111   PLXV = PREFIX_8LS | 0xc8000000,
112   PLXVP = PREFIX_8LS | 0xe8000000,
113 
114   // Stores.
115   PSTB = PREFIX_MLS,
116   PSTH = PREFIX_MLS,
117   PSTW = PREFIX_MLS,
118   PSTD = PREFIX_8LS | 0xf4000000,
119   PSTFS = PREFIX_MLS,
120   PSTXSSP = PREFIX_8LS | 0xbc000000,
121   PSTFD = PREFIX_MLS,
122   PSTXSD = PREFIX_8LS | 0xb8000000,
123   PSTXV = PREFIX_8LS | 0xd8000000,
124   PSTXVP = PREFIX_8LS | 0xf8000000
125 };
126 static bool checkPPCLegacyInsn(uint32_t encoding) {
127   PPCLegacyInsn insn = static_cast<PPCLegacyInsn>(encoding);
128   if (insn == PPCLegacyInsn::NOINSN)
129     return false;
130 #define PCREL_OPT(Legacy, PCRel, InsnMask)                                     \
131   if (insn == PPCLegacyInsn::Legacy)                                           \
132     return true;
133 #include "PPCInsns.def"
134 #undef PCREL_OPT
135   return false;
136 }
137 
138 // Masks to apply to legacy instructions when converting them to prefixed,
139 // pc-relative versions. For the most part, the primary opcode is shared
140 // between the legacy instruction and the suffix of its prefixed version.
141 // However, there are some instances where that isn't the case (DS-Form and
142 // DQ-form instructions).
143 enum class LegacyToPrefixMask : uint64_t {
144   NOMASK = 0x0,
145   OPC_AND_RST = 0xffe00000, // Primary opc (0-5) and R[ST] (6-10).
146   ONLY_RST = 0x3e00000,     // [RS]T (6-10).
147   ST_STX28_TO5 =
148       0x8000000003e00000, // S/T (6-10) - The [S/T]X bit moves from 28 to 5.
149 };
150 
151 uint64_t elf::getPPC64TocBase() {
152   // The TOC consists of sections .got, .toc, .tocbss, .plt in that order. The
153   // TOC starts where the first of these sections starts. We always create a
154   // .got when we see a relocation that uses it, so for us the start is always
155   // the .got.
156   uint64_t tocVA = in.got->getVA();
157 
158   // Per the ppc64-elf-linux ABI, The TOC base is TOC value plus 0x8000
159   // thus permitting a full 64 Kbytes segment. Note that the glibc startup
160   // code (crt1.o) assumes that you can get from the TOC base to the
161   // start of the .toc section with only a single (signed) 16-bit relocation.
162   return tocVA + ppc64TocOffset;
163 }
164 
165 unsigned elf::getPPC64GlobalEntryToLocalEntryOffset(uint8_t stOther) {
166   // The offset is encoded into the 3 most significant bits of the st_other
167   // field, with some special values described in section 3.4.1 of the ABI:
168   // 0   --> Zero offset between the GEP and LEP, and the function does NOT use
169   //         the TOC pointer (r2). r2 will hold the same value on returning from
170   //         the function as it did on entering the function.
171   // 1   --> Zero offset between the GEP and LEP, and r2 should be treated as a
172   //         caller-saved register for all callers.
173   // 2-6 --> The  binary logarithm of the offset eg:
174   //         2 --> 2^2 = 4 bytes -->  1 instruction.
175   //         6 --> 2^6 = 64 bytes --> 16 instructions.
176   // 7   --> Reserved.
177   uint8_t gepToLep = (stOther >> 5) & 7;
178   if (gepToLep < 2)
179     return 0;
180 
181   // The value encoded in the st_other bits is the
182   // log-base-2(offset).
183   if (gepToLep < 7)
184     return 1 << gepToLep;
185 
186   error("reserved value of 7 in the 3 most-significant-bits of st_other");
187   return 0;
188 }
189 
190 void elf::writePrefixedInstruction(uint8_t *loc, uint64_t insn) {
191   insn = config->isLE ? insn << 32 | insn >> 32 : insn;
192   write64(loc, insn);
193 }
194 
195 static bool addOptional(StringRef name, uint64_t value,
196                         std::vector<Defined *> &defined) {
197   Symbol *sym = symtab->find(name);
198   if (!sym || sym->isDefined())
199     return false;
200   sym->resolve(Defined{/*file=*/nullptr, saver.save(name), STB_GLOBAL,
201                        STV_HIDDEN, STT_FUNC, value,
202                        /*size=*/0, /*section=*/nullptr});
203   defined.push_back(cast<Defined>(sym));
204   return true;
205 }
206 
207 // If from is 14, write ${prefix}14: firstInsn; ${prefix}15:
208 // firstInsn+0x200008; ...; ${prefix}31: firstInsn+(31-14)*0x200008; $tail
209 // The labels are defined only if they exist in the symbol table.
210 static void writeSequence(MutableArrayRef<uint32_t> buf, const char *prefix,
211                           int from, uint32_t firstInsn,
212                           ArrayRef<uint32_t> tail) {
213   std::vector<Defined *> defined;
214   char name[16];
215   int first;
216   uint32_t *ptr = buf.data();
217   for (int r = from; r < 32; ++r) {
218     format("%s%d", prefix, r).snprint(name, sizeof(name));
219     if (addOptional(name, 4 * (r - from), defined) && defined.size() == 1)
220       first = r - from;
221     write32(ptr++, firstInsn + 0x200008 * (r - from));
222   }
223   for (uint32_t insn : tail)
224     write32(ptr++, insn);
225   assert(ptr == &*buf.end());
226 
227   if (defined.empty())
228     return;
229   // The full section content has the extent of [begin, end). We drop unused
230   // instructions and write [first,end).
231   auto *sec = make<InputSection>(
232       nullptr, SHF_ALLOC, SHT_PROGBITS, 4,
233       makeArrayRef(reinterpret_cast<uint8_t *>(buf.data() + first),
234                    4 * (buf.size() - first)),
235       ".text");
236   inputSections.push_back(sec);
237   for (Defined *sym : defined) {
238     sym->section = sec;
239     sym->value -= 4 * first;
240   }
241 }
242 
243 // Implements some save and restore functions as described by ELF V2 ABI to be
244 // compatible with GCC. With GCC -Os, when the number of call-saved registers
245 // exceeds a certain threshold, GCC generates _savegpr0_* _restgpr0_* calls and
246 // expects the linker to define them. See
247 // https://sourceware.org/pipermail/binutils/2002-February/017444.html and
248 // https://sourceware.org/pipermail/binutils/2004-August/036765.html . This is
249 // weird because libgcc.a would be the natural place. The linker generation
250 // approach has the advantage that the linker can generate multiple copies to
251 // avoid long branch thunks. However, we don't consider the advantage
252 // significant enough to complicate our trunk implementation, so we take the
253 // simple approach and synthesize .text sections providing the implementation.
254 void elf::addPPC64SaveRestore() {
255   static uint32_t savegpr0[20], restgpr0[21], savegpr1[19], restgpr1[19];
256   constexpr uint32_t blr = 0x4e800020, mtlr_0 = 0x7c0803a6;
257 
258   // _restgpr0_14: ld 14, -144(1); _restgpr0_15: ld 15, -136(1); ...
259   // Tail: ld 0, 16(1); mtlr 0; blr
260   writeSequence(restgpr0, "_restgpr0_", 14, 0xe9c1ff70,
261                 {0xe8010010, mtlr_0, blr});
262   // _restgpr1_14: ld 14, -144(12); _restgpr1_15: ld 15, -136(12); ...
263   // Tail: blr
264   writeSequence(restgpr1, "_restgpr1_", 14, 0xe9ccff70, {blr});
265   // _savegpr0_14: std 14, -144(1); _savegpr0_15: std 15, -136(1); ...
266   // Tail: std 0, 16(1); blr
267   writeSequence(savegpr0, "_savegpr0_", 14, 0xf9c1ff70, {0xf8010010, blr});
268   // _savegpr1_14: std 14, -144(12); _savegpr1_15: std 15, -136(12); ...
269   // Tail: blr
270   writeSequence(savegpr1, "_savegpr1_", 14, 0xf9ccff70, {blr});
271 }
272 
273 // Find the R_PPC64_ADDR64 in .rela.toc with matching offset.
274 template <typename ELFT>
275 static std::pair<Defined *, int64_t>
276 getRelaTocSymAndAddend(InputSectionBase *tocSec, uint64_t offset) {
277   // .rela.toc contains exclusively R_PPC64_ADDR64 relocations sorted by
278   // r_offset: 0, 8, 16, etc. For a given Offset, Offset / 8 gives us the
279   // relocation index in most cases.
280   //
281   // In rare cases a TOC entry may store a constant that doesn't need an
282   // R_PPC64_ADDR64, the corresponding r_offset is therefore missing. Offset / 8
283   // points to a relocation with larger r_offset. Do a linear probe then.
284   // Constants are extremely uncommon in .toc and the extra number of array
285   // accesses can be seen as a small constant.
286   ArrayRef<typename ELFT::Rela> relas =
287       tocSec->template relsOrRelas<ELFT>().relas;
288   if (relas.empty())
289     return {};
290   uint64_t index = std::min<uint64_t>(offset / 8, relas.size() - 1);
291   for (;;) {
292     if (relas[index].r_offset == offset) {
293       Symbol &sym = tocSec->getFile<ELFT>()->getRelocTargetSym(relas[index]);
294       return {dyn_cast<Defined>(&sym), getAddend<ELFT>(relas[index])};
295     }
296     if (relas[index].r_offset < offset || index == 0)
297       break;
298     --index;
299   }
300   return {};
301 }
302 
303 // When accessing a symbol defined in another translation unit, compilers
304 // reserve a .toc entry, allocate a local label and generate toc-indirect
305 // instructions:
306 //
307 //   addis 3, 2, .LC0@toc@ha  # R_PPC64_TOC16_HA
308 //   ld    3, .LC0@toc@l(3)   # R_PPC64_TOC16_LO_DS, load the address from a .toc entry
309 //   ld/lwa 3, 0(3)           # load the value from the address
310 //
311 //   .section .toc,"aw",@progbits
312 //   .LC0: .tc var[TC],var
313 //
314 // If var is defined, non-preemptable and addressable with a 32-bit signed
315 // offset from the toc base, the address of var can be computed by adding an
316 // offset to the toc base, saving a load.
317 //
318 //   addis 3,2,var@toc@ha     # this may be relaxed to a nop,
319 //   addi  3,3,var@toc@l      # then this becomes addi 3,2,var@toc
320 //   ld/lwa 3, 0(3)           # load the value from the address
321 //
322 // Returns true if the relaxation is performed.
323 bool elf::tryRelaxPPC64TocIndirection(const Relocation &rel, uint8_t *bufLoc) {
324   assert(config->tocOptimize);
325   if (rel.addend < 0)
326     return false;
327 
328   // If the symbol is not the .toc section, this isn't a toc-indirection.
329   Defined *defSym = dyn_cast<Defined>(rel.sym);
330   if (!defSym || !defSym->isSection() || defSym->section->name != ".toc")
331     return false;
332 
333   Defined *d;
334   int64_t addend;
335   auto *tocISB = cast<InputSectionBase>(defSym->section);
336   std::tie(d, addend) =
337       config->isLE ? getRelaTocSymAndAddend<ELF64LE>(tocISB, rel.addend)
338                    : getRelaTocSymAndAddend<ELF64BE>(tocISB, rel.addend);
339 
340   // Only non-preemptable defined symbols can be relaxed.
341   if (!d || d->isPreemptible)
342     return false;
343 
344   // R_PPC64_ADDR64 should have created a canonical PLT for the non-preemptable
345   // ifunc and changed its type to STT_FUNC.
346   assert(!d->isGnuIFunc());
347 
348   // Two instructions can materialize a 32-bit signed offset from the toc base.
349   uint64_t tocRelative = d->getVA(addend) - getPPC64TocBase();
350   if (!isInt<32>(tocRelative))
351     return false;
352 
353   // Add PPC64TocOffset that will be subtracted by PPC64::relocate().
354   target->relaxGot(bufLoc, rel, tocRelative + ppc64TocOffset);
355   return true;
356 }
357 
358 namespace {
359 class PPC64 final : public TargetInfo {
360 public:
361   PPC64();
362   int getTlsGdRelaxSkip(RelType type) const override;
363   uint32_t calcEFlags() const override;
364   RelExpr getRelExpr(RelType type, const Symbol &s,
365                      const uint8_t *loc) const override;
366   RelType getDynRel(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 void PPC64::writeGotHeader(uint8_t *buf) const {
1064   write64(buf, getPPC64TocBase());
1065 }
1066 
1067 void PPC64::writePltHeader(uint8_t *buf) const {
1068   // The generic resolver stub goes first.
1069   write32(buf +  0, 0x7c0802a6); // mflr r0
1070   write32(buf +  4, 0x429f0005); // bcl  20,4*cr7+so,8 <_glink+0x8>
1071   write32(buf +  8, 0x7d6802a6); // mflr r11
1072   write32(buf + 12, 0x7c0803a6); // mtlr r0
1073   write32(buf + 16, 0x7d8b6050); // subf r12, r11, r12
1074   write32(buf + 20, 0x380cffcc); // subi r0,r12,52
1075   write32(buf + 24, 0x7800f082); // srdi r0,r0,62,2
1076   write32(buf + 28, 0xe98b002c); // ld   r12,44(r11)
1077   write32(buf + 32, 0x7d6c5a14); // add  r11,r12,r11
1078   write32(buf + 36, 0xe98b0000); // ld   r12,0(r11)
1079   write32(buf + 40, 0xe96b0008); // ld   r11,8(r11)
1080   write32(buf + 44, 0x7d8903a6); // mtctr   r12
1081   write32(buf + 48, 0x4e800420); // bctr
1082 
1083   // The 'bcl' instruction will set the link register to the address of the
1084   // following instruction ('mflr r11'). Here we store the offset from that
1085   // instruction  to the first entry in the GotPlt section.
1086   int64_t gotPltOffset = in.gotPlt->getVA() - (in.plt->getVA() + 8);
1087   write64(buf + 52, gotPltOffset);
1088 }
1089 
1090 void PPC64::writePlt(uint8_t *buf, const Symbol &sym,
1091                      uint64_t /*pltEntryAddr*/) const {
1092   int32_t offset = pltHeaderSize + sym.pltIndex * pltEntrySize;
1093   // bl __glink_PLTresolve
1094   write32(buf, 0x48000000 | ((-offset) & 0x03FFFFFc));
1095 }
1096 
1097 void PPC64::writeIplt(uint8_t *buf, const Symbol &sym,
1098                       uint64_t /*pltEntryAddr*/) const {
1099   writePPC64LoadAndBranch(buf, sym.getGotPltVA() - getPPC64TocBase());
1100 }
1101 
1102 static std::pair<RelType, uint64_t> toAddr16Rel(RelType type, uint64_t val) {
1103   // Relocations relative to the toc-base need to be adjusted by the Toc offset.
1104   uint64_t tocBiasedVal = val - ppc64TocOffset;
1105   // Relocations relative to dtv[dtpmod] need to be adjusted by the DTP offset.
1106   uint64_t dtpBiasedVal = val - dynamicThreadPointerOffset;
1107 
1108   switch (type) {
1109   // TOC biased relocation.
1110   case R_PPC64_GOT16:
1111   case R_PPC64_GOT_TLSGD16:
1112   case R_PPC64_GOT_TLSLD16:
1113   case R_PPC64_TOC16:
1114     return {R_PPC64_ADDR16, tocBiasedVal};
1115   case R_PPC64_GOT16_DS:
1116   case R_PPC64_TOC16_DS:
1117   case R_PPC64_GOT_TPREL16_DS:
1118   case R_PPC64_GOT_DTPREL16_DS:
1119     return {R_PPC64_ADDR16_DS, tocBiasedVal};
1120   case R_PPC64_GOT16_HA:
1121   case R_PPC64_GOT_TLSGD16_HA:
1122   case R_PPC64_GOT_TLSLD16_HA:
1123   case R_PPC64_GOT_TPREL16_HA:
1124   case R_PPC64_GOT_DTPREL16_HA:
1125   case R_PPC64_TOC16_HA:
1126     return {R_PPC64_ADDR16_HA, tocBiasedVal};
1127   case R_PPC64_GOT16_HI:
1128   case R_PPC64_GOT_TLSGD16_HI:
1129   case R_PPC64_GOT_TLSLD16_HI:
1130   case R_PPC64_GOT_TPREL16_HI:
1131   case R_PPC64_GOT_DTPREL16_HI:
1132   case R_PPC64_TOC16_HI:
1133     return {R_PPC64_ADDR16_HI, tocBiasedVal};
1134   case R_PPC64_GOT16_LO:
1135   case R_PPC64_GOT_TLSGD16_LO:
1136   case R_PPC64_GOT_TLSLD16_LO:
1137   case R_PPC64_TOC16_LO:
1138     return {R_PPC64_ADDR16_LO, tocBiasedVal};
1139   case R_PPC64_GOT16_LO_DS:
1140   case R_PPC64_TOC16_LO_DS:
1141   case R_PPC64_GOT_TPREL16_LO_DS:
1142   case R_PPC64_GOT_DTPREL16_LO_DS:
1143     return {R_PPC64_ADDR16_LO_DS, tocBiasedVal};
1144 
1145   // Dynamic Thread pointer biased relocation types.
1146   case R_PPC64_DTPREL16:
1147     return {R_PPC64_ADDR16, dtpBiasedVal};
1148   case R_PPC64_DTPREL16_DS:
1149     return {R_PPC64_ADDR16_DS, dtpBiasedVal};
1150   case R_PPC64_DTPREL16_HA:
1151     return {R_PPC64_ADDR16_HA, dtpBiasedVal};
1152   case R_PPC64_DTPREL16_HI:
1153     return {R_PPC64_ADDR16_HI, dtpBiasedVal};
1154   case R_PPC64_DTPREL16_HIGHER:
1155     return {R_PPC64_ADDR16_HIGHER, dtpBiasedVal};
1156   case R_PPC64_DTPREL16_HIGHERA:
1157     return {R_PPC64_ADDR16_HIGHERA, dtpBiasedVal};
1158   case R_PPC64_DTPREL16_HIGHEST:
1159     return {R_PPC64_ADDR16_HIGHEST, dtpBiasedVal};
1160   case R_PPC64_DTPREL16_HIGHESTA:
1161     return {R_PPC64_ADDR16_HIGHESTA, dtpBiasedVal};
1162   case R_PPC64_DTPREL16_LO:
1163     return {R_PPC64_ADDR16_LO, dtpBiasedVal};
1164   case R_PPC64_DTPREL16_LO_DS:
1165     return {R_PPC64_ADDR16_LO_DS, dtpBiasedVal};
1166   case R_PPC64_DTPREL64:
1167     return {R_PPC64_ADDR64, dtpBiasedVal};
1168 
1169   default:
1170     return {type, val};
1171   }
1172 }
1173 
1174 static bool isTocOptType(RelType type) {
1175   switch (type) {
1176   case R_PPC64_GOT16_HA:
1177   case R_PPC64_GOT16_LO_DS:
1178   case R_PPC64_TOC16_HA:
1179   case R_PPC64_TOC16_LO_DS:
1180   case R_PPC64_TOC16_LO:
1181     return true;
1182   default:
1183     return false;
1184   }
1185 }
1186 
1187 void PPC64::relocate(uint8_t *loc, const Relocation &rel, uint64_t val) const {
1188   RelType type = rel.type;
1189   bool shouldTocOptimize =  isTocOptType(type);
1190   // For dynamic thread pointer relative, toc-relative, and got-indirect
1191   // relocations, proceed in terms of the corresponding ADDR16 relocation type.
1192   std::tie(type, val) = toAddr16Rel(type, val);
1193 
1194   switch (type) {
1195   case R_PPC64_ADDR14: {
1196     checkAlignment(loc, val, 4, rel);
1197     // Preserve the AA/LK bits in the branch instruction
1198     uint8_t aalk = loc[3];
1199     write16(loc + 2, (aalk & 3) | (val & 0xfffc));
1200     break;
1201   }
1202   case R_PPC64_ADDR16:
1203     checkIntUInt(loc, val, 16, rel);
1204     write16(loc, val);
1205     break;
1206   case R_PPC64_ADDR32:
1207     checkIntUInt(loc, val, 32, rel);
1208     write32(loc, val);
1209     break;
1210   case R_PPC64_ADDR16_DS:
1211   case R_PPC64_TPREL16_DS: {
1212     checkInt(loc, val, 16, rel);
1213     // DQ-form instructions use bits 28-31 as part of the instruction encoding
1214     // DS-form instructions only use bits 30-31.
1215     uint16_t mask = isDQFormInstruction(readFromHalf16(loc)) ? 0xf : 0x3;
1216     checkAlignment(loc, lo(val), mask + 1, rel);
1217     write16(loc, (read16(loc) & mask) | lo(val));
1218   } break;
1219   case R_PPC64_ADDR16_HA:
1220   case R_PPC64_REL16_HA:
1221   case R_PPC64_TPREL16_HA:
1222     if (config->tocOptimize && shouldTocOptimize && ha(val) == 0)
1223       writeFromHalf16(loc, NOP);
1224     else {
1225       checkInt(loc, val + 0x8000, 32, rel);
1226       write16(loc, ha(val));
1227     }
1228     break;
1229   case R_PPC64_ADDR16_HI:
1230   case R_PPC64_REL16_HI:
1231   case R_PPC64_TPREL16_HI:
1232     checkInt(loc, val, 32, rel);
1233     write16(loc, hi(val));
1234     break;
1235   case R_PPC64_ADDR16_HIGH:
1236     write16(loc, hi(val));
1237     break;
1238   case R_PPC64_ADDR16_HIGHER:
1239   case R_PPC64_TPREL16_HIGHER:
1240     write16(loc, higher(val));
1241     break;
1242   case R_PPC64_ADDR16_HIGHERA:
1243   case R_PPC64_TPREL16_HIGHERA:
1244     write16(loc, highera(val));
1245     break;
1246   case R_PPC64_ADDR16_HIGHEST:
1247   case R_PPC64_TPREL16_HIGHEST:
1248     write16(loc, highest(val));
1249     break;
1250   case R_PPC64_ADDR16_HIGHESTA:
1251   case R_PPC64_TPREL16_HIGHESTA:
1252     write16(loc, highesta(val));
1253     break;
1254   case R_PPC64_ADDR16_LO:
1255   case R_PPC64_REL16_LO:
1256   case R_PPC64_TPREL16_LO:
1257     // When the high-adjusted part of a toc relocation evaluates to 0, it is
1258     // changed into a nop. The lo part then needs to be updated to use the
1259     // toc-pointer register r2, as the base register.
1260     if (config->tocOptimize && shouldTocOptimize && ha(val) == 0) {
1261       uint32_t insn = readFromHalf16(loc);
1262       if (isInstructionUpdateForm(insn))
1263         error(getErrorLocation(loc) +
1264               "can't toc-optimize an update instruction: 0x" +
1265               utohexstr(insn));
1266       writeFromHalf16(loc, (insn & 0xffe00000) | 0x00020000 | lo(val));
1267     } else {
1268       write16(loc, lo(val));
1269     }
1270     break;
1271   case R_PPC64_ADDR16_LO_DS:
1272   case R_PPC64_TPREL16_LO_DS: {
1273     // DQ-form instructions use bits 28-31 as part of the instruction encoding
1274     // DS-form instructions only use bits 30-31.
1275     uint32_t insn = readFromHalf16(loc);
1276     uint16_t mask = isDQFormInstruction(insn) ? 0xf : 0x3;
1277     checkAlignment(loc, lo(val), mask + 1, rel);
1278     if (config->tocOptimize && shouldTocOptimize && ha(val) == 0) {
1279       // When the high-adjusted part of a toc relocation evaluates to 0, it is
1280       // changed into a nop. The lo part then needs to be updated to use the toc
1281       // pointer register r2, as the base register.
1282       if (isInstructionUpdateForm(insn))
1283         error(getErrorLocation(loc) +
1284               "Can't toc-optimize an update instruction: 0x" +
1285               Twine::utohexstr(insn));
1286       insn &= 0xffe00000 | mask;
1287       writeFromHalf16(loc, insn | 0x00020000 | lo(val));
1288     } else {
1289       write16(loc, (read16(loc) & mask) | lo(val));
1290     }
1291   } break;
1292   case R_PPC64_TPREL16:
1293     checkInt(loc, val, 16, rel);
1294     write16(loc, val);
1295     break;
1296   case R_PPC64_REL32:
1297     checkInt(loc, val, 32, rel);
1298     write32(loc, val);
1299     break;
1300   case R_PPC64_ADDR64:
1301   case R_PPC64_REL64:
1302   case R_PPC64_TOC:
1303     write64(loc, val);
1304     break;
1305   case R_PPC64_REL14: {
1306     uint32_t mask = 0x0000FFFC;
1307     checkInt(loc, val, 16, rel);
1308     checkAlignment(loc, val, 4, rel);
1309     write32(loc, (read32(loc) & ~mask) | (val & mask));
1310     break;
1311   }
1312   case R_PPC64_REL24:
1313   case R_PPC64_REL24_NOTOC: {
1314     uint32_t mask = 0x03FFFFFC;
1315     checkInt(loc, val, 26, rel);
1316     checkAlignment(loc, val, 4, rel);
1317     write32(loc, (read32(loc) & ~mask) | (val & mask));
1318     break;
1319   }
1320   case R_PPC64_DTPREL64:
1321     write64(loc, val - dynamicThreadPointerOffset);
1322     break;
1323   case R_PPC64_DTPREL34:
1324     // The Dynamic Thread Vector actually points 0x8000 bytes past the start
1325     // of the TLS block. Therefore, in the case of R_PPC64_DTPREL34 we first
1326     // need to subtract that value then fallthrough to the general case.
1327     val -= dynamicThreadPointerOffset;
1328     LLVM_FALLTHROUGH;
1329   case R_PPC64_PCREL34:
1330   case R_PPC64_GOT_PCREL34:
1331   case R_PPC64_GOT_TLSGD_PCREL34:
1332   case R_PPC64_GOT_TLSLD_PCREL34:
1333   case R_PPC64_GOT_TPREL_PCREL34:
1334   case R_PPC64_TPREL34: {
1335     const uint64_t si0Mask = 0x00000003ffff0000;
1336     const uint64_t si1Mask = 0x000000000000ffff;
1337     const uint64_t fullMask = 0x0003ffff0000ffff;
1338     checkInt(loc, val, 34, rel);
1339 
1340     uint64_t instr = readPrefixedInstruction(loc) & ~fullMask;
1341     writePrefixedInstruction(loc, instr | ((val & si0Mask) << 16) |
1342                              (val & si1Mask));
1343     break;
1344   }
1345   // If we encounter a PCREL_OPT relocation that we won't optimize.
1346   case R_PPC64_PCREL_OPT:
1347     break;
1348   default:
1349     llvm_unreachable("unknown relocation");
1350   }
1351 }
1352 
1353 bool PPC64::needsThunk(RelExpr expr, RelType type, const InputFile *file,
1354                        uint64_t branchAddr, const Symbol &s, int64_t a) const {
1355   if (type != R_PPC64_REL14 && type != R_PPC64_REL24 &&
1356       type != R_PPC64_REL24_NOTOC)
1357     return false;
1358 
1359   // If a function is in the Plt it needs to be called with a call-stub.
1360   if (s.isInPlt())
1361     return true;
1362 
1363   // This check looks at the st_other bits of the callee with relocation
1364   // R_PPC64_REL14 or R_PPC64_REL24. If the value is 1, then the callee
1365   // clobbers the TOC and we need an R2 save stub.
1366   if (type != R_PPC64_REL24_NOTOC && (s.stOther >> 5) == 1)
1367     return true;
1368 
1369   if (type == R_PPC64_REL24_NOTOC && (s.stOther >> 5) > 1)
1370     return true;
1371 
1372   // If a symbol is a weak undefined and we are compiling an executable
1373   // it doesn't need a range-extending thunk since it can't be called.
1374   if (s.isUndefWeak() && !config->shared)
1375     return false;
1376 
1377   // If the offset exceeds the range of the branch type then it will need
1378   // a range-extending thunk.
1379   // See the comment in getRelocTargetVA() about R_PPC64_CALL.
1380   return !inBranchRange(type, branchAddr,
1381                         s.getVA(a) +
1382                             getPPC64GlobalEntryToLocalEntryOffset(s.stOther));
1383 }
1384 
1385 uint32_t PPC64::getThunkSectionSpacing() const {
1386   // See comment in Arch/ARM.cpp for a more detailed explanation of
1387   // getThunkSectionSpacing(). For PPC64 we pick the constant here based on
1388   // R_PPC64_REL24, which is used by unconditional branch instructions.
1389   // 0x2000000 = (1 << 24-1) * 4
1390   return 0x2000000;
1391 }
1392 
1393 bool PPC64::inBranchRange(RelType type, uint64_t src, uint64_t dst) const {
1394   int64_t offset = dst - src;
1395   if (type == R_PPC64_REL14)
1396     return isInt<16>(offset);
1397   if (type == R_PPC64_REL24 || type == R_PPC64_REL24_NOTOC)
1398     return isInt<26>(offset);
1399   llvm_unreachable("unsupported relocation type used in branch");
1400 }
1401 
1402 RelExpr PPC64::adjustTlsExpr(RelType type, RelExpr expr) const {
1403   if (type != R_PPC64_GOT_TLSGD_PCREL34 && expr == R_RELAX_TLS_GD_TO_IE)
1404     return R_RELAX_TLS_GD_TO_IE_GOT_OFF;
1405   if (expr == R_RELAX_TLS_LD_TO_LE)
1406     return R_RELAX_TLS_LD_TO_LE_ABS;
1407   return expr;
1408 }
1409 
1410 RelExpr PPC64::adjustGotPcExpr(RelType type, int64_t addend,
1411                                const uint8_t *loc) const {
1412   if ((type == R_PPC64_GOT_PCREL34 || type == R_PPC64_PCREL_OPT) &&
1413       config->pcRelOptimize) {
1414     // It only makes sense to optimize pld since paddi means that the address
1415     // of the object in the GOT is required rather than the object itself.
1416     if ((readPrefixedInstruction(loc) & 0xfc000000) == 0xe4000000)
1417       return R_PPC64_RELAX_GOT_PC;
1418   }
1419   return R_GOT_PC;
1420 }
1421 
1422 // Reference: 3.7.4.1 of the 64-bit ELF V2 abi supplement.
1423 // The general dynamic code sequence for a global `x` uses 4 instructions.
1424 // Instruction                    Relocation                Symbol
1425 // addis r3, r2, x@got@tlsgd@ha   R_PPC64_GOT_TLSGD16_HA      x
1426 // addi  r3, r3, x@got@tlsgd@l    R_PPC64_GOT_TLSGD16_LO      x
1427 // bl __tls_get_addr(x@tlsgd)     R_PPC64_TLSGD               x
1428 //                                R_PPC64_REL24               __tls_get_addr
1429 // nop                            None                       None
1430 //
1431 // Relaxing to initial-exec entails:
1432 // 1) Convert the addis/addi pair that builds the address of the tls_index
1433 //    struct for 'x' to an addis/ld pair that loads an offset from a got-entry.
1434 // 2) Convert the call to __tls_get_addr to a nop.
1435 // 3) Convert the nop following the call to an add of the loaded offset to the
1436 //    thread pointer.
1437 // Since the nop must directly follow the call, the R_PPC64_TLSGD relocation is
1438 // used as the relaxation hint for both steps 2 and 3.
1439 void PPC64::relaxTlsGdToIe(uint8_t *loc, const Relocation &rel,
1440                            uint64_t val) const {
1441   switch (rel.type) {
1442   case R_PPC64_GOT_TLSGD16_HA:
1443     // This is relaxed from addis rT, r2, sym@got@tlsgd@ha to
1444     //                      addis rT, r2, sym@got@tprel@ha.
1445     relocateNoSym(loc, R_PPC64_GOT_TPREL16_HA, val);
1446     return;
1447   case R_PPC64_GOT_TLSGD16:
1448   case R_PPC64_GOT_TLSGD16_LO: {
1449     // Relax from addi  r3, rA, sym@got@tlsgd@l to
1450     //            ld r3, sym@got@tprel@l(rA)
1451     uint32_t ra = (readFromHalf16(loc) & (0x1f << 16));
1452     writeFromHalf16(loc, 0xe8600000 | ra);
1453     relocateNoSym(loc, R_PPC64_GOT_TPREL16_LO_DS, val);
1454     return;
1455   }
1456   case R_PPC64_GOT_TLSGD_PCREL34: {
1457     // Relax from paddi r3, 0, sym@got@tlsgd@pcrel, 1 to
1458     //            pld r3, sym@got@tprel@pcrel
1459     writePrefixedInstruction(loc, 0x04100000e4600000);
1460     relocateNoSym(loc, R_PPC64_GOT_TPREL_PCREL34, val);
1461     return;
1462   }
1463   case R_PPC64_TLSGD: {
1464     // PC Relative Relaxation:
1465     // Relax from bl __tls_get_addr@notoc(x@tlsgd) to
1466     //            nop
1467     // TOC Relaxation:
1468     // Relax from bl __tls_get_addr(x@tlsgd)
1469     //            nop
1470     // to
1471     //            nop
1472     //            add r3, r3, r13
1473     const uintptr_t locAsInt = reinterpret_cast<uintptr_t>(loc);
1474     if (locAsInt % 4 == 0) {
1475       write32(loc, NOP);            // bl __tls_get_addr(sym@tlsgd) --> nop
1476       write32(loc + 4, 0x7c636A14); // nop --> add r3, r3, r13
1477     } else if (locAsInt % 4 == 1) {
1478       // bl __tls_get_addr(sym@tlsgd) --> add r3, r3, r13
1479       write32(loc - 1, 0x7c636a14);
1480     } else {
1481       errorOrWarn("R_PPC64_TLSGD has unexpected byte alignment");
1482     }
1483     return;
1484   }
1485   default:
1486     llvm_unreachable("unsupported relocation for TLS GD to IE relaxation");
1487   }
1488 }
1489 
1490 // The prologue for a split-stack function is expected to look roughly
1491 // like this:
1492 //    .Lglobal_entry_point:
1493 //      # TOC pointer initialization.
1494 //      ...
1495 //    .Llocal_entry_point:
1496 //      # load the __private_ss member of the threads tcbhead.
1497 //      ld r0,-0x7000-64(r13)
1498 //      # subtract the functions stack size from the stack pointer.
1499 //      addis r12, r1, ha(-stack-frame size)
1500 //      addi  r12, r12, l(-stack-frame size)
1501 //      # compare needed to actual and branch to allocate_more_stack if more
1502 //      # space is needed, otherwise fallthrough to 'normal' function body.
1503 //      cmpld cr7,r12,r0
1504 //      blt- cr7, .Lallocate_more_stack
1505 //
1506 // -) The allocate_more_stack block might be placed after the split-stack
1507 //    prologue and the `blt-` replaced with a `bge+ .Lnormal_func_body`
1508 //    instead.
1509 // -) If either the addis or addi is not needed due to the stack size being
1510 //    smaller then 32K or a multiple of 64K they will be replaced with a nop,
1511 //    but there will always be 2 instructions the linker can overwrite for the
1512 //    adjusted stack size.
1513 //
1514 // The linkers job here is to increase the stack size used in the addis/addi
1515 // pair by split-stack-size-adjust.
1516 // addis r12, r1, ha(-stack-frame size - split-stack-adjust-size)
1517 // addi  r12, r12, l(-stack-frame size - split-stack-adjust-size)
1518 bool PPC64::adjustPrologueForCrossSplitStack(uint8_t *loc, uint8_t *end,
1519                                              uint8_t stOther) const {
1520   // If the caller has a global entry point adjust the buffer past it. The start
1521   // of the split-stack prologue will be at the local entry point.
1522   loc += getPPC64GlobalEntryToLocalEntryOffset(stOther);
1523 
1524   // At the very least we expect to see a load of some split-stack data from the
1525   // tcb, and 2 instructions that calculate the ending stack address this
1526   // function will require. If there is not enough room for at least 3
1527   // instructions it can't be a split-stack prologue.
1528   if (loc + 12 >= end)
1529     return false;
1530 
1531   // First instruction must be `ld r0, -0x7000-64(r13)`
1532   if (read32(loc) != 0xe80d8fc0)
1533     return false;
1534 
1535   int16_t hiImm = 0;
1536   int16_t loImm = 0;
1537   // First instruction can be either an addis if the frame size is larger then
1538   // 32K, or an addi if the size is less then 32K.
1539   int32_t firstInstr = read32(loc + 4);
1540   if (getPrimaryOpCode(firstInstr) == 15) {
1541     hiImm = firstInstr & 0xFFFF;
1542   } else if (getPrimaryOpCode(firstInstr) == 14) {
1543     loImm = firstInstr & 0xFFFF;
1544   } else {
1545     return false;
1546   }
1547 
1548   // Second instruction is either an addi or a nop. If the first instruction was
1549   // an addi then LoImm is set and the second instruction must be a nop.
1550   uint32_t secondInstr = read32(loc + 8);
1551   if (!loImm && getPrimaryOpCode(secondInstr) == 14) {
1552     loImm = secondInstr & 0xFFFF;
1553   } else if (secondInstr != NOP) {
1554     return false;
1555   }
1556 
1557   // The register operands of the first instruction should be the stack-pointer
1558   // (r1) as the input (RA) and r12 as the output (RT). If the second
1559   // instruction is not a nop, then it should use r12 as both input and output.
1560   auto checkRegOperands = [](uint32_t instr, uint8_t expectedRT,
1561                              uint8_t expectedRA) {
1562     return ((instr & 0x3E00000) >> 21 == expectedRT) &&
1563            ((instr & 0x1F0000) >> 16 == expectedRA);
1564   };
1565   if (!checkRegOperands(firstInstr, 12, 1))
1566     return false;
1567   if (secondInstr != NOP && !checkRegOperands(secondInstr, 12, 12))
1568     return false;
1569 
1570   int32_t stackFrameSize = (hiImm * 65536) + loImm;
1571   // Check that the adjusted size doesn't overflow what we can represent with 2
1572   // instructions.
1573   if (stackFrameSize < config->splitStackAdjustSize + INT32_MIN) {
1574     error(getErrorLocation(loc) + "split-stack prologue adjustment overflows");
1575     return false;
1576   }
1577 
1578   int32_t adjustedStackFrameSize =
1579       stackFrameSize - config->splitStackAdjustSize;
1580 
1581   loImm = adjustedStackFrameSize & 0xFFFF;
1582   hiImm = (adjustedStackFrameSize + 0x8000) >> 16;
1583   if (hiImm) {
1584     write32(loc + 4, 0x3D810000 | (uint16_t)hiImm);
1585     // If the low immediate is zero the second instruction will be a nop.
1586     secondInstr = loImm ? 0x398C0000 | (uint16_t)loImm : NOP;
1587     write32(loc + 8, secondInstr);
1588   } else {
1589     // addi r12, r1, imm
1590     write32(loc + 4, (0x39810000) | (uint16_t)loImm);
1591     write32(loc + 8, NOP);
1592   }
1593 
1594   return true;
1595 }
1596 
1597 TargetInfo *elf::getPPC64TargetInfo() {
1598   static PPC64 target;
1599   return &target;
1600 }
1601