xref: /freebsd/contrib/llvm-project/lld/ELF/Arch/PPC64.cpp (revision 85868e8a1daeaae7a0e48effb2ea2310ae3b02c6)
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 "Symbols.h"
10 #include "SyntheticSections.h"
11 #include "Target.h"
12 #include "lld/Common/ErrorHandler.h"
13 #include "llvm/Support/Endian.h"
14 
15 using namespace llvm;
16 using namespace llvm::object;
17 using namespace llvm::support::endian;
18 using namespace llvm::ELF;
19 
20 namespace lld {
21 namespace elf {
22 
23 static uint64_t ppc64TocOffset = 0x8000;
24 static uint64_t dynamicThreadPointerOffset = 0x8000;
25 
26 // The instruction encoding of bits 21-30 from the ISA for the Xform and Dform
27 // instructions that can be used as part of the initial exec TLS sequence.
28 enum XFormOpcd {
29   LBZX = 87,
30   LHZX = 279,
31   LWZX = 23,
32   LDX = 21,
33   STBX = 215,
34   STHX = 407,
35   STWX = 151,
36   STDX = 149,
37   ADD = 266,
38 };
39 
40 enum DFormOpcd {
41   LBZ = 34,
42   LBZU = 35,
43   LHZ = 40,
44   LHZU = 41,
45   LHAU = 43,
46   LWZ = 32,
47   LWZU = 33,
48   LFSU = 49,
49   LD = 58,
50   LFDU = 51,
51   STB = 38,
52   STBU = 39,
53   STH = 44,
54   STHU = 45,
55   STW = 36,
56   STWU = 37,
57   STFSU = 53,
58   STFDU = 55,
59   STD = 62,
60   ADDI = 14
61 };
62 
63 uint64_t getPPC64TocBase() {
64   // The TOC consists of sections .got, .toc, .tocbss, .plt in that order. The
65   // TOC starts where the first of these sections starts. We always create a
66   // .got when we see a relocation that uses it, so for us the start is always
67   // the .got.
68   uint64_t tocVA = in.got->getVA();
69 
70   // Per the ppc64-elf-linux ABI, The TOC base is TOC value plus 0x8000
71   // thus permitting a full 64 Kbytes segment. Note that the glibc startup
72   // code (crt1.o) assumes that you can get from the TOC base to the
73   // start of the .toc section with only a single (signed) 16-bit relocation.
74   return tocVA + ppc64TocOffset;
75 }
76 
77 unsigned getPPC64GlobalEntryToLocalEntryOffset(uint8_t stOther) {
78   // The offset is encoded into the 3 most significant bits of the st_other
79   // field, with some special values described in section 3.4.1 of the ABI:
80   // 0   --> Zero offset between the GEP and LEP, and the function does NOT use
81   //         the TOC pointer (r2). r2 will hold the same value on returning from
82   //         the function as it did on entering the function.
83   // 1   --> Zero offset between the GEP and LEP, and r2 should be treated as a
84   //         caller-saved register for all callers.
85   // 2-6 --> The  binary logarithm of the offset eg:
86   //         2 --> 2^2 = 4 bytes -->  1 instruction.
87   //         6 --> 2^6 = 64 bytes --> 16 instructions.
88   // 7   --> Reserved.
89   uint8_t gepToLep = (stOther >> 5) & 7;
90   if (gepToLep < 2)
91     return 0;
92 
93   // The value encoded in the st_other bits is the
94   // log-base-2(offset).
95   if (gepToLep < 7)
96     return 1 << gepToLep;
97 
98   error("reserved value of 7 in the 3 most-significant-bits of st_other");
99   return 0;
100 }
101 
102 bool isPPC64SmallCodeModelTocReloc(RelType type) {
103   // The only small code model relocations that access the .toc section.
104   return type == R_PPC64_TOC16 || type == R_PPC64_TOC16_DS;
105 }
106 
107 // Find the R_PPC64_ADDR64 in .rela.toc with matching offset.
108 template <typename ELFT>
109 static std::pair<Defined *, int64_t>
110 getRelaTocSymAndAddend(InputSectionBase *tocSec, uint64_t offset) {
111   if (tocSec->numRelocations == 0)
112     return {};
113 
114   // .rela.toc contains exclusively R_PPC64_ADDR64 relocations sorted by
115   // r_offset: 0, 8, 16, etc. For a given Offset, Offset / 8 gives us the
116   // relocation index in most cases.
117   //
118   // In rare cases a TOC entry may store a constant that doesn't need an
119   // R_PPC64_ADDR64, the corresponding r_offset is therefore missing. Offset / 8
120   // points to a relocation with larger r_offset. Do a linear probe then.
121   // Constants are extremely uncommon in .toc and the extra number of array
122   // accesses can be seen as a small constant.
123   ArrayRef<typename ELFT::Rela> relas = tocSec->template relas<ELFT>();
124   uint64_t index = std::min<uint64_t>(offset / 8, relas.size() - 1);
125   for (;;) {
126     if (relas[index].r_offset == offset) {
127       Symbol &sym = tocSec->getFile<ELFT>()->getRelocTargetSym(relas[index]);
128       return {dyn_cast<Defined>(&sym), getAddend<ELFT>(relas[index])};
129     }
130     if (relas[index].r_offset < offset || index == 0)
131       break;
132     --index;
133   }
134   return {};
135 }
136 
137 // When accessing a symbol defined in another translation unit, compilers
138 // reserve a .toc entry, allocate a local label and generate toc-indirect
139 // instuctions:
140 //
141 //   addis 3, 2, .LC0@toc@ha  # R_PPC64_TOC16_HA
142 //   ld    3, .LC0@toc@l(3)   # R_PPC64_TOC16_LO_DS, load the address from a .toc entry
143 //   ld/lwa 3, 0(3)           # load the value from the address
144 //
145 //   .section .toc,"aw",@progbits
146 //   .LC0: .tc var[TC],var
147 //
148 // If var is defined, non-preemptable and addressable with a 32-bit signed
149 // offset from the toc base, the address of var can be computed by adding an
150 // offset to the toc base, saving a load.
151 //
152 //   addis 3,2,var@toc@ha     # this may be relaxed to a nop,
153 //   addi  3,3,var@toc@l      # then this becomes addi 3,2,var@toc
154 //   ld/lwa 3, 0(3)           # load the value from the address
155 //
156 // Returns true if the relaxation is performed.
157 bool tryRelaxPPC64TocIndirection(RelType type, const Relocation &rel,
158                                  uint8_t *bufLoc) {
159   assert(config->tocOptimize);
160   if (rel.addend < 0)
161     return false;
162 
163   // If the symbol is not the .toc section, this isn't a toc-indirection.
164   Defined *defSym = dyn_cast<Defined>(rel.sym);
165   if (!defSym || !defSym->isSection() || defSym->section->name != ".toc")
166     return false;
167 
168   Defined *d;
169   int64_t addend;
170   auto *tocISB = cast<InputSectionBase>(defSym->section);
171   std::tie(d, addend) =
172       config->isLE ? getRelaTocSymAndAddend<ELF64LE>(tocISB, rel.addend)
173                    : getRelaTocSymAndAddend<ELF64BE>(tocISB, rel.addend);
174 
175   // Only non-preemptable defined symbols can be relaxed.
176   if (!d || d->isPreemptible)
177     return false;
178 
179   // R_PPC64_ADDR64 should have created a canonical PLT for the non-preemptable
180   // ifunc and changed its type to STT_FUNC.
181   assert(!d->isGnuIFunc());
182 
183   // Two instructions can materialize a 32-bit signed offset from the toc base.
184   uint64_t tocRelative = d->getVA(addend) - getPPC64TocBase();
185   if (!isInt<32>(tocRelative))
186     return false;
187 
188   // Add PPC64TocOffset that will be subtracted by relocateOne().
189   target->relaxGot(bufLoc, type, tocRelative + ppc64TocOffset);
190   return true;
191 }
192 
193 namespace {
194 class PPC64 final : public TargetInfo {
195 public:
196   PPC64();
197   int getTlsGdRelaxSkip(RelType type) const override;
198   uint32_t calcEFlags() const override;
199   RelExpr getRelExpr(RelType type, const Symbol &s,
200                      const uint8_t *loc) const override;
201   RelType getDynRel(RelType type) const override;
202   void writePltHeader(uint8_t *buf) const override;
203   void writePlt(uint8_t *buf, uint64_t gotPltEntryAddr, uint64_t pltEntryAddr,
204                 int32_t index, unsigned relOff) const override;
205   void relocateOne(uint8_t *loc, RelType type, uint64_t val) const override;
206   void writeGotHeader(uint8_t *buf) const override;
207   bool needsThunk(RelExpr expr, RelType type, const InputFile *file,
208                   uint64_t branchAddr, const Symbol &s) const override;
209   uint32_t getThunkSectionSpacing() const override;
210   bool inBranchRange(RelType type, uint64_t src, uint64_t dst) const override;
211   RelExpr adjustRelaxExpr(RelType type, const uint8_t *data,
212                           RelExpr expr) const override;
213   void relaxGot(uint8_t *loc, RelType type, uint64_t val) const override;
214   void relaxTlsGdToIe(uint8_t *loc, RelType type, uint64_t val) const override;
215   void relaxTlsGdToLe(uint8_t *loc, RelType type, uint64_t val) const override;
216   void relaxTlsLdToLe(uint8_t *loc, RelType type, uint64_t val) const override;
217   void relaxTlsIeToLe(uint8_t *loc, RelType type, uint64_t val) const override;
218 
219   bool adjustPrologueForCrossSplitStack(uint8_t *loc, uint8_t *end,
220                                         uint8_t stOther) const override;
221 };
222 } // namespace
223 
224 // Relocation masks following the #lo(value), #hi(value), #ha(value),
225 // #higher(value), #highera(value), #highest(value), and #highesta(value)
226 // macros defined in section 4.5.1. Relocation Types of the PPC-elf64abi
227 // document.
228 static uint16_t lo(uint64_t v) { return v; }
229 static uint16_t hi(uint64_t v) { return v >> 16; }
230 static uint16_t ha(uint64_t v) { return (v + 0x8000) >> 16; }
231 static uint16_t higher(uint64_t v) { return v >> 32; }
232 static uint16_t highera(uint64_t v) { return (v + 0x8000) >> 32; }
233 static uint16_t highest(uint64_t v) { return v >> 48; }
234 static uint16_t highesta(uint64_t v) { return (v + 0x8000) >> 48; }
235 
236 // Extracts the 'PO' field of an instruction encoding.
237 static uint8_t getPrimaryOpCode(uint32_t encoding) { return (encoding >> 26); }
238 
239 static bool isDQFormInstruction(uint32_t encoding) {
240   switch (getPrimaryOpCode(encoding)) {
241   default:
242     return false;
243   case 56:
244     // The only instruction with a primary opcode of 56 is `lq`.
245     return true;
246   case 61:
247     // There are both DS and DQ instruction forms with this primary opcode.
248     // Namely `lxv` and `stxv` are the DQ-forms that use it.
249     // The DS 'XO' bits being set to 01 is restricted to DQ form.
250     return (encoding & 3) == 0x1;
251   }
252 }
253 
254 static bool isInstructionUpdateForm(uint32_t encoding) {
255   switch (getPrimaryOpCode(encoding)) {
256   default:
257     return false;
258   case LBZU:
259   case LHAU:
260   case LHZU:
261   case LWZU:
262   case LFSU:
263   case LFDU:
264   case STBU:
265   case STHU:
266   case STWU:
267   case STFSU:
268   case STFDU:
269     return true;
270     // LWA has the same opcode as LD, and the DS bits is what differentiates
271     // between LD/LDU/LWA
272   case LD:
273   case STD:
274     return (encoding & 3) == 1;
275   }
276 }
277 
278 // There are a number of places when we either want to read or write an
279 // instruction when handling a half16 relocation type. On big-endian the buffer
280 // pointer is pointing into the middle of the word we want to extract, and on
281 // little-endian it is pointing to the start of the word. These 2 helpers are to
282 // simplify reading and writing in that context.
283 static void writeFromHalf16(uint8_t *loc, uint32_t insn) {
284   write32(config->isLE ? loc : loc - 2, insn);
285 }
286 
287 static uint32_t readFromHalf16(const uint8_t *loc) {
288   return read32(config->isLE ? loc : loc - 2);
289 }
290 
291 PPC64::PPC64() {
292   gotRel = R_PPC64_GLOB_DAT;
293   noneRel = R_PPC64_NONE;
294   pltRel = R_PPC64_JMP_SLOT;
295   relativeRel = R_PPC64_RELATIVE;
296   iRelativeRel = R_PPC64_IRELATIVE;
297   symbolicRel = R_PPC64_ADDR64;
298   pltEntrySize = 4;
299   gotBaseSymInGotPlt = false;
300   gotHeaderEntriesNum = 1;
301   gotPltHeaderEntriesNum = 2;
302   pltHeaderSize = 60;
303   needsThunks = true;
304 
305   tlsModuleIndexRel = R_PPC64_DTPMOD64;
306   tlsOffsetRel = R_PPC64_DTPREL64;
307 
308   tlsGotRel = R_PPC64_TPREL64;
309 
310   needsMoreStackNonSplit = false;
311 
312   // We need 64K pages (at least under glibc/Linux, the loader won't
313   // set different permissions on a finer granularity than that).
314   defaultMaxPageSize = 65536;
315 
316   // The PPC64 ELF ABI v1 spec, says:
317   //
318   //   It is normally desirable to put segments with different characteristics
319   //   in separate 256 Mbyte portions of the address space, to give the
320   //   operating system full paging flexibility in the 64-bit address space.
321   //
322   // And because the lowest non-zero 256M boundary is 0x10000000, PPC64 linkers
323   // use 0x10000000 as the starting address.
324   defaultImageBase = 0x10000000;
325 
326   write32(trapInstr.data(), 0x7fe00008);
327 }
328 
329 int PPC64::getTlsGdRelaxSkip(RelType type) const {
330   // A __tls_get_addr call instruction is marked with 2 relocations:
331   //
332   //   R_PPC64_TLSGD / R_PPC64_TLSLD: marker relocation
333   //   R_PPC64_REL24: __tls_get_addr
334   //
335   // After the relaxation we no longer call __tls_get_addr and should skip both
336   // relocations to not create a false dependence on __tls_get_addr being
337   // defined.
338   if (type == R_PPC64_TLSGD || type == R_PPC64_TLSLD)
339     return 2;
340   return 1;
341 }
342 
343 static uint32_t getEFlags(InputFile *file) {
344   if (config->ekind == ELF64BEKind)
345     return cast<ObjFile<ELF64BE>>(file)->getObj().getHeader()->e_flags;
346   return cast<ObjFile<ELF64LE>>(file)->getObj().getHeader()->e_flags;
347 }
348 
349 // This file implements v2 ABI. This function makes sure that all
350 // object files have v2 or an unspecified version as an ABI version.
351 uint32_t PPC64::calcEFlags() const {
352   for (InputFile *f : objectFiles) {
353     uint32_t flag = getEFlags(f);
354     if (flag == 1)
355       error(toString(f) + ": ABI version 1 is not supported");
356     else if (flag > 2)
357       error(toString(f) + ": unrecognized e_flags: " + Twine(flag));
358   }
359   return 2;
360 }
361 
362 void PPC64::relaxGot(uint8_t *loc, RelType type, uint64_t val) const {
363   switch (type) {
364   case R_PPC64_TOC16_HA:
365     // Convert "addis reg, 2, .LC0@toc@h" to "addis reg, 2, var@toc@h" or "nop".
366     relocateOne(loc, type, val);
367     break;
368   case R_PPC64_TOC16_LO_DS: {
369     // Convert "ld reg, .LC0@toc@l(reg)" to "addi reg, reg, var@toc@l" or
370     // "addi reg, 2, var@toc".
371     uint32_t insn = readFromHalf16(loc);
372     if (getPrimaryOpCode(insn) != LD)
373       error("expected a 'ld' for got-indirect to toc-relative relaxing");
374     writeFromHalf16(loc, (insn & 0x03ffffff) | 0x38000000);
375     relocateOne(loc, R_PPC64_TOC16_LO, val);
376     break;
377   }
378   default:
379     llvm_unreachable("unexpected relocation type");
380   }
381 }
382 
383 void PPC64::relaxTlsGdToLe(uint8_t *loc, RelType type, uint64_t val) const {
384   // Reference: 3.7.4.2 of the 64-bit ELF V2 abi supplement.
385   // The general dynamic code sequence for a global `x` will look like:
386   // Instruction                    Relocation                Symbol
387   // addis r3, r2, x@got@tlsgd@ha   R_PPC64_GOT_TLSGD16_HA      x
388   // addi  r3, r3, x@got@tlsgd@l    R_PPC64_GOT_TLSGD16_LO      x
389   // bl __tls_get_addr(x@tlsgd)     R_PPC64_TLSGD               x
390   //                                R_PPC64_REL24               __tls_get_addr
391   // nop                            None                       None
392 
393   // Relaxing to local exec entails converting:
394   // addis r3, r2, x@got@tlsgd@ha    into      nop
395   // addi  r3, r3, x@got@tlsgd@l     into      addis r3, r13, x@tprel@ha
396   // bl __tls_get_addr(x@tlsgd)      into      nop
397   // nop                             into      addi r3, r3, x@tprel@l
398 
399   switch (type) {
400   case R_PPC64_GOT_TLSGD16_HA:
401     writeFromHalf16(loc, 0x60000000); // nop
402     break;
403   case R_PPC64_GOT_TLSGD16:
404   case R_PPC64_GOT_TLSGD16_LO:
405     writeFromHalf16(loc, 0x3c6d0000); // addis r3, r13
406     relocateOne(loc, R_PPC64_TPREL16_HA, val);
407     break;
408   case R_PPC64_TLSGD:
409     write32(loc, 0x60000000);     // nop
410     write32(loc + 4, 0x38630000); // addi r3, r3
411     // Since we are relocating a half16 type relocation and Loc + 4 points to
412     // the start of an instruction we need to advance the buffer by an extra
413     // 2 bytes on BE.
414     relocateOne(loc + 4 + (config->ekind == ELF64BEKind ? 2 : 0),
415                 R_PPC64_TPREL16_LO, val);
416     break;
417   default:
418     llvm_unreachable("unsupported relocation for TLS GD to LE relaxation");
419   }
420 }
421 
422 void PPC64::relaxTlsLdToLe(uint8_t *loc, RelType type, uint64_t val) const {
423   // Reference: 3.7.4.3 of the 64-bit ELF V2 abi supplement.
424   // The local dynamic code sequence for a global `x` will look like:
425   // Instruction                    Relocation                Symbol
426   // addis r3, r2, x@got@tlsld@ha   R_PPC64_GOT_TLSLD16_HA      x
427   // addi  r3, r3, x@got@tlsld@l    R_PPC64_GOT_TLSLD16_LO      x
428   // bl __tls_get_addr(x@tlsgd)     R_PPC64_TLSLD               x
429   //                                R_PPC64_REL24               __tls_get_addr
430   // nop                            None                       None
431 
432   // Relaxing to local exec entails converting:
433   // addis r3, r2, x@got@tlsld@ha   into      nop
434   // addi  r3, r3, x@got@tlsld@l    into      addis r3, r13, 0
435   // bl __tls_get_addr(x@tlsgd)     into      nop
436   // nop                            into      addi r3, r3, 4096
437 
438   switch (type) {
439   case R_PPC64_GOT_TLSLD16_HA:
440     writeFromHalf16(loc, 0x60000000); // nop
441     break;
442   case R_PPC64_GOT_TLSLD16_LO:
443     writeFromHalf16(loc, 0x3c6d0000); // addis r3, r13, 0
444     break;
445   case R_PPC64_TLSLD:
446     write32(loc, 0x60000000);     // nop
447     write32(loc + 4, 0x38631000); // addi r3, r3, 4096
448     break;
449   case R_PPC64_DTPREL16:
450   case R_PPC64_DTPREL16_HA:
451   case R_PPC64_DTPREL16_HI:
452   case R_PPC64_DTPREL16_DS:
453   case R_PPC64_DTPREL16_LO:
454   case R_PPC64_DTPREL16_LO_DS:
455     relocateOne(loc, type, val);
456     break;
457   default:
458     llvm_unreachable("unsupported relocation for TLS LD to LE relaxation");
459   }
460 }
461 
462 unsigned getPPCDFormOp(unsigned secondaryOp) {
463   switch (secondaryOp) {
464   case LBZX:
465     return LBZ;
466   case LHZX:
467     return LHZ;
468   case LWZX:
469     return LWZ;
470   case LDX:
471     return LD;
472   case STBX:
473     return STB;
474   case STHX:
475     return STH;
476   case STWX:
477     return STW;
478   case STDX:
479     return STD;
480   case ADD:
481     return ADDI;
482   default:
483     return 0;
484   }
485 }
486 
487 void PPC64::relaxTlsIeToLe(uint8_t *loc, RelType type, uint64_t val) const {
488   // The initial exec code sequence for a global `x` will look like:
489   // Instruction                    Relocation                Symbol
490   // addis r9, r2, x@got@tprel@ha   R_PPC64_GOT_TPREL16_HA      x
491   // ld    r9, x@got@tprel@l(r9)    R_PPC64_GOT_TPREL16_LO_DS   x
492   // add r9, r9, x@tls              R_PPC64_TLS                 x
493 
494   // Relaxing to local exec entails converting:
495   // addis r9, r2, x@got@tprel@ha       into        nop
496   // ld r9, x@got@tprel@l(r9)           into        addis r9, r13, x@tprel@ha
497   // add r9, r9, x@tls                  into        addi r9, r9, x@tprel@l
498 
499   // x@tls R_PPC64_TLS is a relocation which does not compute anything,
500   // it is replaced with r13 (thread pointer).
501 
502   // The add instruction in the initial exec sequence has multiple variations
503   // that need to be handled. If we are building an address it will use an add
504   // instruction, if we are accessing memory it will use any of the X-form
505   // indexed load or store instructions.
506 
507   unsigned offset = (config->ekind == ELF64BEKind) ? 2 : 0;
508   switch (type) {
509   case R_PPC64_GOT_TPREL16_HA:
510     write32(loc - offset, 0x60000000); // nop
511     break;
512   case R_PPC64_GOT_TPREL16_LO_DS:
513   case R_PPC64_GOT_TPREL16_DS: {
514     uint32_t regNo = read32(loc - offset) & 0x03E00000; // bits 6-10
515     write32(loc - offset, 0x3C0D0000 | regNo);          // addis RegNo, r13
516     relocateOne(loc, R_PPC64_TPREL16_HA, val);
517     break;
518   }
519   case R_PPC64_TLS: {
520     uint32_t primaryOp = getPrimaryOpCode(read32(loc));
521     if (primaryOp != 31)
522       error("unrecognized instruction for IE to LE R_PPC64_TLS");
523     uint32_t secondaryOp = (read32(loc) & 0x000007FE) >> 1; // bits 21-30
524     uint32_t dFormOp = getPPCDFormOp(secondaryOp);
525     if (dFormOp == 0)
526       error("unrecognized instruction for IE to LE R_PPC64_TLS");
527     write32(loc, ((dFormOp << 26) | (read32(loc) & 0x03FFFFFF)));
528     relocateOne(loc + offset, R_PPC64_TPREL16_LO, val);
529     break;
530   }
531   default:
532     llvm_unreachable("unknown relocation for IE to LE");
533     break;
534   }
535 }
536 
537 RelExpr PPC64::getRelExpr(RelType type, const Symbol &s,
538                           const uint8_t *loc) const {
539   switch (type) {
540   case R_PPC64_NONE:
541     return R_NONE;
542   case R_PPC64_ADDR16:
543   case R_PPC64_ADDR16_DS:
544   case R_PPC64_ADDR16_HA:
545   case R_PPC64_ADDR16_HI:
546   case R_PPC64_ADDR16_HIGHER:
547   case R_PPC64_ADDR16_HIGHERA:
548   case R_PPC64_ADDR16_HIGHEST:
549   case R_PPC64_ADDR16_HIGHESTA:
550   case R_PPC64_ADDR16_LO:
551   case R_PPC64_ADDR16_LO_DS:
552   case R_PPC64_ADDR32:
553   case R_PPC64_ADDR64:
554     return R_ABS;
555   case R_PPC64_GOT16:
556   case R_PPC64_GOT16_DS:
557   case R_PPC64_GOT16_HA:
558   case R_PPC64_GOT16_HI:
559   case R_PPC64_GOT16_LO:
560   case R_PPC64_GOT16_LO_DS:
561     return R_GOT_OFF;
562   case R_PPC64_TOC16:
563   case R_PPC64_TOC16_DS:
564   case R_PPC64_TOC16_HI:
565   case R_PPC64_TOC16_LO:
566     return R_GOTREL;
567   case R_PPC64_TOC16_HA:
568   case R_PPC64_TOC16_LO_DS:
569     return config->tocOptimize ? R_PPC64_RELAX_TOC : R_GOTREL;
570   case R_PPC64_TOC:
571     return R_PPC64_TOCBASE;
572   case R_PPC64_REL14:
573   case R_PPC64_REL24:
574     return R_PPC64_CALL_PLT;
575   case R_PPC64_REL16_LO:
576   case R_PPC64_REL16_HA:
577   case R_PPC64_REL16_HI:
578   case R_PPC64_REL32:
579   case R_PPC64_REL64:
580     return R_PC;
581   case R_PPC64_GOT_TLSGD16:
582   case R_PPC64_GOT_TLSGD16_HA:
583   case R_PPC64_GOT_TLSGD16_HI:
584   case R_PPC64_GOT_TLSGD16_LO:
585     return R_TLSGD_GOT;
586   case R_PPC64_GOT_TLSLD16:
587   case R_PPC64_GOT_TLSLD16_HA:
588   case R_PPC64_GOT_TLSLD16_HI:
589   case R_PPC64_GOT_TLSLD16_LO:
590     return R_TLSLD_GOT;
591   case R_PPC64_GOT_TPREL16_HA:
592   case R_PPC64_GOT_TPREL16_LO_DS:
593   case R_PPC64_GOT_TPREL16_DS:
594   case R_PPC64_GOT_TPREL16_HI:
595     return R_GOT_OFF;
596   case R_PPC64_GOT_DTPREL16_HA:
597   case R_PPC64_GOT_DTPREL16_LO_DS:
598   case R_PPC64_GOT_DTPREL16_DS:
599   case R_PPC64_GOT_DTPREL16_HI:
600     return R_TLSLD_GOT_OFF;
601   case R_PPC64_TPREL16:
602   case R_PPC64_TPREL16_HA:
603   case R_PPC64_TPREL16_LO:
604   case R_PPC64_TPREL16_HI:
605   case R_PPC64_TPREL16_DS:
606   case R_PPC64_TPREL16_LO_DS:
607   case R_PPC64_TPREL16_HIGHER:
608   case R_PPC64_TPREL16_HIGHERA:
609   case R_PPC64_TPREL16_HIGHEST:
610   case R_PPC64_TPREL16_HIGHESTA:
611     return R_TLS;
612   case R_PPC64_DTPREL16:
613   case R_PPC64_DTPREL16_DS:
614   case R_PPC64_DTPREL16_HA:
615   case R_PPC64_DTPREL16_HI:
616   case R_PPC64_DTPREL16_HIGHER:
617   case R_PPC64_DTPREL16_HIGHERA:
618   case R_PPC64_DTPREL16_HIGHEST:
619   case R_PPC64_DTPREL16_HIGHESTA:
620   case R_PPC64_DTPREL16_LO:
621   case R_PPC64_DTPREL16_LO_DS:
622   case R_PPC64_DTPREL64:
623     return R_DTPREL;
624   case R_PPC64_TLSGD:
625     return R_TLSDESC_CALL;
626   case R_PPC64_TLSLD:
627     return R_TLSLD_HINT;
628   case R_PPC64_TLS:
629     return R_TLSIE_HINT;
630   default:
631     error(getErrorLocation(loc) + "unknown relocation (" + Twine(type) +
632           ") against symbol " + toString(s));
633     return R_NONE;
634   }
635 }
636 
637 RelType PPC64::getDynRel(RelType type) const {
638   if (type == R_PPC64_ADDR64 || type == R_PPC64_TOC)
639     return R_PPC64_ADDR64;
640   return R_PPC64_NONE;
641 }
642 
643 void PPC64::writeGotHeader(uint8_t *buf) const {
644   write64(buf, getPPC64TocBase());
645 }
646 
647 void PPC64::writePltHeader(uint8_t *buf) const {
648   // The generic resolver stub goes first.
649   write32(buf +  0, 0x7c0802a6); // mflr r0
650   write32(buf +  4, 0x429f0005); // bcl  20,4*cr7+so,8 <_glink+0x8>
651   write32(buf +  8, 0x7d6802a6); // mflr r11
652   write32(buf + 12, 0x7c0803a6); // mtlr r0
653   write32(buf + 16, 0x7d8b6050); // subf r12, r11, r12
654   write32(buf + 20, 0x380cffcc); // subi r0,r12,52
655   write32(buf + 24, 0x7800f082); // srdi r0,r0,62,2
656   write32(buf + 28, 0xe98b002c); // ld   r12,44(r11)
657   write32(buf + 32, 0x7d6c5a14); // add  r11,r12,r11
658   write32(buf + 36, 0xe98b0000); // ld   r12,0(r11)
659   write32(buf + 40, 0xe96b0008); // ld   r11,8(r11)
660   write32(buf + 44, 0x7d8903a6); // mtctr   r12
661   write32(buf + 48, 0x4e800420); // bctr
662 
663   // The 'bcl' instruction will set the link register to the address of the
664   // following instruction ('mflr r11'). Here we store the offset from that
665   // instruction  to the first entry in the GotPlt section.
666   int64_t gotPltOffset = in.gotPlt->getVA() - (in.plt->getVA() + 8);
667   write64(buf + 52, gotPltOffset);
668 }
669 
670 void PPC64::writePlt(uint8_t *buf, uint64_t gotPltEntryAddr,
671                      uint64_t pltEntryAddr, int32_t index,
672                      unsigned relOff) const {
673   int32_t offset = pltHeaderSize + index * pltEntrySize;
674   // bl __glink_PLTresolve
675   write32(buf, 0x48000000 | ((-offset) & 0x03FFFFFc));
676 }
677 
678 static std::pair<RelType, uint64_t> toAddr16Rel(RelType type, uint64_t val) {
679   // Relocations relative to the toc-base need to be adjusted by the Toc offset.
680   uint64_t tocBiasedVal = val - ppc64TocOffset;
681   // Relocations relative to dtv[dtpmod] need to be adjusted by the DTP offset.
682   uint64_t dtpBiasedVal = val - dynamicThreadPointerOffset;
683 
684   switch (type) {
685   // TOC biased relocation.
686   case R_PPC64_GOT16:
687   case R_PPC64_GOT_TLSGD16:
688   case R_PPC64_GOT_TLSLD16:
689   case R_PPC64_TOC16:
690     return {R_PPC64_ADDR16, tocBiasedVal};
691   case R_PPC64_GOT16_DS:
692   case R_PPC64_TOC16_DS:
693   case R_PPC64_GOT_TPREL16_DS:
694   case R_PPC64_GOT_DTPREL16_DS:
695     return {R_PPC64_ADDR16_DS, tocBiasedVal};
696   case R_PPC64_GOT16_HA:
697   case R_PPC64_GOT_TLSGD16_HA:
698   case R_PPC64_GOT_TLSLD16_HA:
699   case R_PPC64_GOT_TPREL16_HA:
700   case R_PPC64_GOT_DTPREL16_HA:
701   case R_PPC64_TOC16_HA:
702     return {R_PPC64_ADDR16_HA, tocBiasedVal};
703   case R_PPC64_GOT16_HI:
704   case R_PPC64_GOT_TLSGD16_HI:
705   case R_PPC64_GOT_TLSLD16_HI:
706   case R_PPC64_GOT_TPREL16_HI:
707   case R_PPC64_GOT_DTPREL16_HI:
708   case R_PPC64_TOC16_HI:
709     return {R_PPC64_ADDR16_HI, tocBiasedVal};
710   case R_PPC64_GOT16_LO:
711   case R_PPC64_GOT_TLSGD16_LO:
712   case R_PPC64_GOT_TLSLD16_LO:
713   case R_PPC64_TOC16_LO:
714     return {R_PPC64_ADDR16_LO, tocBiasedVal};
715   case R_PPC64_GOT16_LO_DS:
716   case R_PPC64_TOC16_LO_DS:
717   case R_PPC64_GOT_TPREL16_LO_DS:
718   case R_PPC64_GOT_DTPREL16_LO_DS:
719     return {R_PPC64_ADDR16_LO_DS, tocBiasedVal};
720 
721   // Dynamic Thread pointer biased relocation types.
722   case R_PPC64_DTPREL16:
723     return {R_PPC64_ADDR16, dtpBiasedVal};
724   case R_PPC64_DTPREL16_DS:
725     return {R_PPC64_ADDR16_DS, dtpBiasedVal};
726   case R_PPC64_DTPREL16_HA:
727     return {R_PPC64_ADDR16_HA, dtpBiasedVal};
728   case R_PPC64_DTPREL16_HI:
729     return {R_PPC64_ADDR16_HI, dtpBiasedVal};
730   case R_PPC64_DTPREL16_HIGHER:
731     return {R_PPC64_ADDR16_HIGHER, dtpBiasedVal};
732   case R_PPC64_DTPREL16_HIGHERA:
733     return {R_PPC64_ADDR16_HIGHERA, dtpBiasedVal};
734   case R_PPC64_DTPREL16_HIGHEST:
735     return {R_PPC64_ADDR16_HIGHEST, dtpBiasedVal};
736   case R_PPC64_DTPREL16_HIGHESTA:
737     return {R_PPC64_ADDR16_HIGHESTA, dtpBiasedVal};
738   case R_PPC64_DTPREL16_LO:
739     return {R_PPC64_ADDR16_LO, dtpBiasedVal};
740   case R_PPC64_DTPREL16_LO_DS:
741     return {R_PPC64_ADDR16_LO_DS, dtpBiasedVal};
742   case R_PPC64_DTPREL64:
743     return {R_PPC64_ADDR64, dtpBiasedVal};
744 
745   default:
746     return {type, val};
747   }
748 }
749 
750 static bool isTocOptType(RelType type) {
751   switch (type) {
752   case R_PPC64_GOT16_HA:
753   case R_PPC64_GOT16_LO_DS:
754   case R_PPC64_TOC16_HA:
755   case R_PPC64_TOC16_LO_DS:
756   case R_PPC64_TOC16_LO:
757     return true;
758   default:
759     return false;
760   }
761 }
762 
763 void PPC64::relocateOne(uint8_t *loc, RelType type, uint64_t val) const {
764   // We need to save the original relocation type to use in diagnostics, and
765   // use the original type to determine if we should toc-optimize the
766   // instructions being relocated.
767   RelType originalType = type;
768   bool shouldTocOptimize =  isTocOptType(type);
769   // For dynamic thread pointer relative, toc-relative, and got-indirect
770   // relocations, proceed in terms of the corresponding ADDR16 relocation type.
771   std::tie(type, val) = toAddr16Rel(type, val);
772 
773   switch (type) {
774   case R_PPC64_ADDR14: {
775     checkAlignment(loc, val, 4, type);
776     // Preserve the AA/LK bits in the branch instruction
777     uint8_t aalk = loc[3];
778     write16(loc + 2, (aalk & 3) | (val & 0xfffc));
779     break;
780   }
781   case R_PPC64_ADDR16:
782     checkIntUInt(loc, val, 16, originalType);
783     write16(loc, val);
784     break;
785   case R_PPC64_ADDR32:
786     checkIntUInt(loc, val, 32, originalType);
787     write32(loc, val);
788     break;
789   case R_PPC64_ADDR16_DS:
790   case R_PPC64_TPREL16_DS: {
791     checkInt(loc, val, 16, originalType);
792     // DQ-form instructions use bits 28-31 as part of the instruction encoding
793     // DS-form instructions only use bits 30-31.
794     uint16_t mask = isDQFormInstruction(readFromHalf16(loc)) ? 0xf : 0x3;
795     checkAlignment(loc, lo(val), mask + 1, originalType);
796     write16(loc, (read16(loc) & mask) | lo(val));
797   } break;
798   case R_PPC64_ADDR16_HA:
799   case R_PPC64_REL16_HA:
800   case R_PPC64_TPREL16_HA:
801     if (config->tocOptimize && shouldTocOptimize && ha(val) == 0)
802       writeFromHalf16(loc, 0x60000000);
803     else
804       write16(loc, ha(val));
805     break;
806   case R_PPC64_ADDR16_HI:
807   case R_PPC64_REL16_HI:
808   case R_PPC64_TPREL16_HI:
809     write16(loc, hi(val));
810     break;
811   case R_PPC64_ADDR16_HIGHER:
812   case R_PPC64_TPREL16_HIGHER:
813     write16(loc, higher(val));
814     break;
815   case R_PPC64_ADDR16_HIGHERA:
816   case R_PPC64_TPREL16_HIGHERA:
817     write16(loc, highera(val));
818     break;
819   case R_PPC64_ADDR16_HIGHEST:
820   case R_PPC64_TPREL16_HIGHEST:
821     write16(loc, highest(val));
822     break;
823   case R_PPC64_ADDR16_HIGHESTA:
824   case R_PPC64_TPREL16_HIGHESTA:
825     write16(loc, highesta(val));
826     break;
827   case R_PPC64_ADDR16_LO:
828   case R_PPC64_REL16_LO:
829   case R_PPC64_TPREL16_LO:
830     // When the high-adjusted part of a toc relocation evalutes to 0, it is
831     // changed into a nop. The lo part then needs to be updated to use the
832     // toc-pointer register r2, as the base register.
833     if (config->tocOptimize && shouldTocOptimize && ha(val) == 0) {
834       uint32_t insn = readFromHalf16(loc);
835       if (isInstructionUpdateForm(insn))
836         error(getErrorLocation(loc) +
837               "can't toc-optimize an update instruction: 0x" +
838               utohexstr(insn));
839       writeFromHalf16(loc, (insn & 0xffe00000) | 0x00020000 | lo(val));
840     } else {
841       write16(loc, lo(val));
842     }
843     break;
844   case R_PPC64_ADDR16_LO_DS:
845   case R_PPC64_TPREL16_LO_DS: {
846     // DQ-form instructions use bits 28-31 as part of the instruction encoding
847     // DS-form instructions only use bits 30-31.
848     uint32_t insn = readFromHalf16(loc);
849     uint16_t mask = isDQFormInstruction(insn) ? 0xf : 0x3;
850     checkAlignment(loc, lo(val), mask + 1, originalType);
851     if (config->tocOptimize && shouldTocOptimize && ha(val) == 0) {
852       // When the high-adjusted part of a toc relocation evalutes to 0, it is
853       // changed into a nop. The lo part then needs to be updated to use the toc
854       // pointer register r2, as the base register.
855       if (isInstructionUpdateForm(insn))
856         error(getErrorLocation(loc) +
857               "Can't toc-optimize an update instruction: 0x" +
858               Twine::utohexstr(insn));
859       insn &= 0xffe00000 | mask;
860       writeFromHalf16(loc, insn | 0x00020000 | lo(val));
861     } else {
862       write16(loc, (read16(loc) & mask) | lo(val));
863     }
864   } break;
865   case R_PPC64_TPREL16:
866     checkInt(loc, val, 16, originalType);
867     write16(loc, val);
868     break;
869   case R_PPC64_REL32:
870     checkInt(loc, val, 32, type);
871     write32(loc, val);
872     break;
873   case R_PPC64_ADDR64:
874   case R_PPC64_REL64:
875   case R_PPC64_TOC:
876     write64(loc, val);
877     break;
878   case R_PPC64_REL14: {
879     uint32_t mask = 0x0000FFFC;
880     checkInt(loc, val, 16, type);
881     checkAlignment(loc, val, 4, type);
882     write32(loc, (read32(loc) & ~mask) | (val & mask));
883     break;
884   }
885   case R_PPC64_REL24: {
886     uint32_t mask = 0x03FFFFFC;
887     checkInt(loc, val, 26, type);
888     checkAlignment(loc, val, 4, type);
889     write32(loc, (read32(loc) & ~mask) | (val & mask));
890     break;
891   }
892   case R_PPC64_DTPREL64:
893     write64(loc, val - dynamicThreadPointerOffset);
894     break;
895   default:
896     llvm_unreachable("unknown relocation");
897   }
898 }
899 
900 bool PPC64::needsThunk(RelExpr expr, RelType type, const InputFile *file,
901                        uint64_t branchAddr, const Symbol &s) const {
902   if (type != R_PPC64_REL14 && type != R_PPC64_REL24)
903     return false;
904 
905   // If a function is in the Plt it needs to be called with a call-stub.
906   if (s.isInPlt())
907     return true;
908 
909   // If a symbol is a weak undefined and we are compiling an executable
910   // it doesn't need a range-extending thunk since it can't be called.
911   if (s.isUndefWeak() && !config->shared)
912     return false;
913 
914   // If the offset exceeds the range of the branch type then it will need
915   // a range-extending thunk.
916   // See the comment in getRelocTargetVA() about R_PPC64_CALL.
917   return !inBranchRange(type, branchAddr,
918                         s.getVA() +
919                             getPPC64GlobalEntryToLocalEntryOffset(s.stOther));
920 }
921 
922 uint32_t PPC64::getThunkSectionSpacing() const {
923   // See comment in Arch/ARM.cpp for a more detailed explanation of
924   // getThunkSectionSpacing(). For PPC64 we pick the constant here based on
925   // R_PPC64_REL24, which is used by unconditional branch instructions.
926   // 0x2000000 = (1 << 24-1) * 4
927   return 0x2000000;
928 }
929 
930 bool PPC64::inBranchRange(RelType type, uint64_t src, uint64_t dst) const {
931   int64_t offset = dst - src;
932   if (type == R_PPC64_REL14)
933     return isInt<16>(offset);
934   if (type == R_PPC64_REL24)
935     return isInt<26>(offset);
936   llvm_unreachable("unsupported relocation type used in branch");
937 }
938 
939 RelExpr PPC64::adjustRelaxExpr(RelType type, const uint8_t *data,
940                                RelExpr expr) const {
941   if (expr == R_RELAX_TLS_GD_TO_IE)
942     return R_RELAX_TLS_GD_TO_IE_GOT_OFF;
943   if (expr == R_RELAX_TLS_LD_TO_LE)
944     return R_RELAX_TLS_LD_TO_LE_ABS;
945   return expr;
946 }
947 
948 // Reference: 3.7.4.1 of the 64-bit ELF V2 abi supplement.
949 // The general dynamic code sequence for a global `x` uses 4 instructions.
950 // Instruction                    Relocation                Symbol
951 // addis r3, r2, x@got@tlsgd@ha   R_PPC64_GOT_TLSGD16_HA      x
952 // addi  r3, r3, x@got@tlsgd@l    R_PPC64_GOT_TLSGD16_LO      x
953 // bl __tls_get_addr(x@tlsgd)     R_PPC64_TLSGD               x
954 //                                R_PPC64_REL24               __tls_get_addr
955 // nop                            None                       None
956 //
957 // Relaxing to initial-exec entails:
958 // 1) Convert the addis/addi pair that builds the address of the tls_index
959 //    struct for 'x' to an addis/ld pair that loads an offset from a got-entry.
960 // 2) Convert the call to __tls_get_addr to a nop.
961 // 3) Convert the nop following the call to an add of the loaded offset to the
962 //    thread pointer.
963 // Since the nop must directly follow the call, the R_PPC64_TLSGD relocation is
964 // used as the relaxation hint for both steps 2 and 3.
965 void PPC64::relaxTlsGdToIe(uint8_t *loc, RelType type, uint64_t val) const {
966   switch (type) {
967   case R_PPC64_GOT_TLSGD16_HA:
968     // This is relaxed from addis rT, r2, sym@got@tlsgd@ha to
969     //                      addis rT, r2, sym@got@tprel@ha.
970     relocateOne(loc, R_PPC64_GOT_TPREL16_HA, val);
971     return;
972   case R_PPC64_GOT_TLSGD16:
973   case R_PPC64_GOT_TLSGD16_LO: {
974     // Relax from addi  r3, rA, sym@got@tlsgd@l to
975     //            ld r3, sym@got@tprel@l(rA)
976     uint32_t ra = (readFromHalf16(loc) & (0x1f << 16));
977     writeFromHalf16(loc, 0xe8600000 | ra);
978     relocateOne(loc, R_PPC64_GOT_TPREL16_LO_DS, val);
979     return;
980   }
981   case R_PPC64_TLSGD:
982     write32(loc, 0x60000000);     // bl __tls_get_addr(sym@tlsgd) --> nop
983     write32(loc + 4, 0x7c636A14); // nop --> add r3, r3, r13
984     return;
985   default:
986     llvm_unreachable("unsupported relocation for TLS GD to IE relaxation");
987   }
988 }
989 
990 // The prologue for a split-stack function is expected to look roughly
991 // like this:
992 //    .Lglobal_entry_point:
993 //      # TOC pointer initalization.
994 //      ...
995 //    .Llocal_entry_point:
996 //      # load the __private_ss member of the threads tcbhead.
997 //      ld r0,-0x7000-64(r13)
998 //      # subtract the functions stack size from the stack pointer.
999 //      addis r12, r1, ha(-stack-frame size)
1000 //      addi  r12, r12, l(-stack-frame size)
1001 //      # compare needed to actual and branch to allocate_more_stack if more
1002 //      # space is needed, otherwise fallthrough to 'normal' function body.
1003 //      cmpld cr7,r12,r0
1004 //      blt- cr7, .Lallocate_more_stack
1005 //
1006 // -) The allocate_more_stack block might be placed after the split-stack
1007 //    prologue and the `blt-` replaced with a `bge+ .Lnormal_func_body`
1008 //    instead.
1009 // -) If either the addis or addi is not needed due to the stack size being
1010 //    smaller then 32K or a multiple of 64K they will be replaced with a nop,
1011 //    but there will always be 2 instructions the linker can overwrite for the
1012 //    adjusted stack size.
1013 //
1014 // The linkers job here is to increase the stack size used in the addis/addi
1015 // pair by split-stack-size-adjust.
1016 // addis r12, r1, ha(-stack-frame size - split-stack-adjust-size)
1017 // addi  r12, r12, l(-stack-frame size - split-stack-adjust-size)
1018 bool PPC64::adjustPrologueForCrossSplitStack(uint8_t *loc, uint8_t *end,
1019                                              uint8_t stOther) const {
1020   // If the caller has a global entry point adjust the buffer past it. The start
1021   // of the split-stack prologue will be at the local entry point.
1022   loc += getPPC64GlobalEntryToLocalEntryOffset(stOther);
1023 
1024   // At the very least we expect to see a load of some split-stack data from the
1025   // tcb, and 2 instructions that calculate the ending stack address this
1026   // function will require. If there is not enough room for at least 3
1027   // instructions it can't be a split-stack prologue.
1028   if (loc + 12 >= end)
1029     return false;
1030 
1031   // First instruction must be `ld r0, -0x7000-64(r13)`
1032   if (read32(loc) != 0xe80d8fc0)
1033     return false;
1034 
1035   int16_t hiImm = 0;
1036   int16_t loImm = 0;
1037   // First instruction can be either an addis if the frame size is larger then
1038   // 32K, or an addi if the size is less then 32K.
1039   int32_t firstInstr = read32(loc + 4);
1040   if (getPrimaryOpCode(firstInstr) == 15) {
1041     hiImm = firstInstr & 0xFFFF;
1042   } else if (getPrimaryOpCode(firstInstr) == 14) {
1043     loImm = firstInstr & 0xFFFF;
1044   } else {
1045     return false;
1046   }
1047 
1048   // Second instruction is either an addi or a nop. If the first instruction was
1049   // an addi then LoImm is set and the second instruction must be a nop.
1050   uint32_t secondInstr = read32(loc + 8);
1051   if (!loImm && getPrimaryOpCode(secondInstr) == 14) {
1052     loImm = secondInstr & 0xFFFF;
1053   } else if (secondInstr != 0x60000000) {
1054     return false;
1055   }
1056 
1057   // The register operands of the first instruction should be the stack-pointer
1058   // (r1) as the input (RA) and r12 as the output (RT). If the second
1059   // instruction is not a nop, then it should use r12 as both input and output.
1060   auto checkRegOperands = [](uint32_t instr, uint8_t expectedRT,
1061                              uint8_t expectedRA) {
1062     return ((instr & 0x3E00000) >> 21 == expectedRT) &&
1063            ((instr & 0x1F0000) >> 16 == expectedRA);
1064   };
1065   if (!checkRegOperands(firstInstr, 12, 1))
1066     return false;
1067   if (secondInstr != 0x60000000 && !checkRegOperands(secondInstr, 12, 12))
1068     return false;
1069 
1070   int32_t stackFrameSize = (hiImm * 65536) + loImm;
1071   // Check that the adjusted size doesn't overflow what we can represent with 2
1072   // instructions.
1073   if (stackFrameSize < config->splitStackAdjustSize + INT32_MIN) {
1074     error(getErrorLocation(loc) + "split-stack prologue adjustment overflows");
1075     return false;
1076   }
1077 
1078   int32_t adjustedStackFrameSize =
1079       stackFrameSize - config->splitStackAdjustSize;
1080 
1081   loImm = adjustedStackFrameSize & 0xFFFF;
1082   hiImm = (adjustedStackFrameSize + 0x8000) >> 16;
1083   if (hiImm) {
1084     write32(loc + 4, 0x3D810000 | (uint16_t)hiImm);
1085     // If the low immediate is zero the second instruction will be a nop.
1086     secondInstr = loImm ? 0x398C0000 | (uint16_t)loImm : 0x60000000;
1087     write32(loc + 8, secondInstr);
1088   } else {
1089     // addi r12, r1, imm
1090     write32(loc + 4, (0x39810000) | (uint16_t)loImm);
1091     write32(loc + 8, 0x60000000);
1092   }
1093 
1094   return true;
1095 }
1096 
1097 TargetInfo *getPPC64TargetInfo() {
1098   static PPC64 target;
1099   return &target;
1100 }
1101 
1102 } // namespace elf
1103 } // namespace lld
1104