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