xref: /llvm-project-15.0.7/lld/ELF/Arch/PPC64.cpp (revision 7177e63f)
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_REL16_LO:
685   case R_PPC64_REL16_HA:
686   case R_PPC64_REL16_HI:
687   case R_PPC64_REL32:
688   case R_PPC64_REL64:
689   case R_PPC64_PCREL34:
690     return R_PC;
691   case R_PPC64_GOT_TLSGD16:
692   case R_PPC64_GOT_TLSGD16_HA:
693   case R_PPC64_GOT_TLSGD16_HI:
694   case R_PPC64_GOT_TLSGD16_LO:
695     return R_TLSGD_GOT;
696   case R_PPC64_GOT_TLSLD16:
697   case R_PPC64_GOT_TLSLD16_HA:
698   case R_PPC64_GOT_TLSLD16_HI:
699   case R_PPC64_GOT_TLSLD16_LO:
700     return R_TLSLD_GOT;
701   case R_PPC64_GOT_TPREL16_HA:
702   case R_PPC64_GOT_TPREL16_LO_DS:
703   case R_PPC64_GOT_TPREL16_DS:
704   case R_PPC64_GOT_TPREL16_HI:
705     return R_GOT_OFF;
706   case R_PPC64_GOT_DTPREL16_HA:
707   case R_PPC64_GOT_DTPREL16_LO_DS:
708   case R_PPC64_GOT_DTPREL16_DS:
709   case R_PPC64_GOT_DTPREL16_HI:
710     return R_TLSLD_GOT_OFF;
711   case R_PPC64_TPREL16:
712   case R_PPC64_TPREL16_HA:
713   case R_PPC64_TPREL16_LO:
714   case R_PPC64_TPREL16_HI:
715   case R_PPC64_TPREL16_DS:
716   case R_PPC64_TPREL16_LO_DS:
717   case R_PPC64_TPREL16_HIGHER:
718   case R_PPC64_TPREL16_HIGHERA:
719   case R_PPC64_TPREL16_HIGHEST:
720   case R_PPC64_TPREL16_HIGHESTA:
721     return R_TLS;
722   case R_PPC64_DTPREL16:
723   case R_PPC64_DTPREL16_DS:
724   case R_PPC64_DTPREL16_HA:
725   case R_PPC64_DTPREL16_HI:
726   case R_PPC64_DTPREL16_HIGHER:
727   case R_PPC64_DTPREL16_HIGHERA:
728   case R_PPC64_DTPREL16_HIGHEST:
729   case R_PPC64_DTPREL16_HIGHESTA:
730   case R_PPC64_DTPREL16_LO:
731   case R_PPC64_DTPREL16_LO_DS:
732   case R_PPC64_DTPREL64:
733     return R_DTPREL;
734   case R_PPC64_TLSGD:
735     return R_TLSDESC_CALL;
736   case R_PPC64_TLSLD:
737     return R_TLSLD_HINT;
738   case R_PPC64_TLS:
739     return R_TLSIE_HINT;
740   default:
741     error(getErrorLocation(loc) + "unknown relocation (" + Twine(type) +
742           ") against symbol " + toString(s));
743     return R_NONE;
744   }
745 }
746 
747 RelType PPC64::getDynRel(RelType type) const {
748   if (type == R_PPC64_ADDR64 || type == R_PPC64_TOC)
749     return R_PPC64_ADDR64;
750   return R_PPC64_NONE;
751 }
752 
753 void PPC64::writeGotHeader(uint8_t *buf) const {
754   write64(buf, getPPC64TocBase());
755 }
756 
757 void PPC64::writePltHeader(uint8_t *buf) const {
758   // The generic resolver stub goes first.
759   write32(buf +  0, 0x7c0802a6); // mflr r0
760   write32(buf +  4, 0x429f0005); // bcl  20,4*cr7+so,8 <_glink+0x8>
761   write32(buf +  8, 0x7d6802a6); // mflr r11
762   write32(buf + 12, 0x7c0803a6); // mtlr r0
763   write32(buf + 16, 0x7d8b6050); // subf r12, r11, r12
764   write32(buf + 20, 0x380cffcc); // subi r0,r12,52
765   write32(buf + 24, 0x7800f082); // srdi r0,r0,62,2
766   write32(buf + 28, 0xe98b002c); // ld   r12,44(r11)
767   write32(buf + 32, 0x7d6c5a14); // add  r11,r12,r11
768   write32(buf + 36, 0xe98b0000); // ld   r12,0(r11)
769   write32(buf + 40, 0xe96b0008); // ld   r11,8(r11)
770   write32(buf + 44, 0x7d8903a6); // mtctr   r12
771   write32(buf + 48, 0x4e800420); // bctr
772 
773   // The 'bcl' instruction will set the link register to the address of the
774   // following instruction ('mflr r11'). Here we store the offset from that
775   // instruction  to the first entry in the GotPlt section.
776   int64_t gotPltOffset = in.gotPlt->getVA() - (in.plt->getVA() + 8);
777   write64(buf + 52, gotPltOffset);
778 }
779 
780 void PPC64::writePlt(uint8_t *buf, const Symbol &sym,
781                      uint64_t /*pltEntryAddr*/) const {
782   int32_t offset = pltHeaderSize + sym.pltIndex * pltEntrySize;
783   // bl __glink_PLTresolve
784   write32(buf, 0x48000000 | ((-offset) & 0x03FFFFFc));
785 }
786 
787 void PPC64::writeIplt(uint8_t *buf, const Symbol &sym,
788                       uint64_t /*pltEntryAddr*/) const {
789   writePPC64LoadAndBranch(buf, sym.getGotPltVA() - getPPC64TocBase());
790 }
791 
792 static std::pair<RelType, uint64_t> toAddr16Rel(RelType type, uint64_t val) {
793   // Relocations relative to the toc-base need to be adjusted by the Toc offset.
794   uint64_t tocBiasedVal = val - ppc64TocOffset;
795   // Relocations relative to dtv[dtpmod] need to be adjusted by the DTP offset.
796   uint64_t dtpBiasedVal = val - dynamicThreadPointerOffset;
797 
798   switch (type) {
799   // TOC biased relocation.
800   case R_PPC64_GOT16:
801   case R_PPC64_GOT_TLSGD16:
802   case R_PPC64_GOT_TLSLD16:
803   case R_PPC64_TOC16:
804     return {R_PPC64_ADDR16, tocBiasedVal};
805   case R_PPC64_GOT16_DS:
806   case R_PPC64_TOC16_DS:
807   case R_PPC64_GOT_TPREL16_DS:
808   case R_PPC64_GOT_DTPREL16_DS:
809     return {R_PPC64_ADDR16_DS, tocBiasedVal};
810   case R_PPC64_GOT16_HA:
811   case R_PPC64_GOT_TLSGD16_HA:
812   case R_PPC64_GOT_TLSLD16_HA:
813   case R_PPC64_GOT_TPREL16_HA:
814   case R_PPC64_GOT_DTPREL16_HA:
815   case R_PPC64_TOC16_HA:
816     return {R_PPC64_ADDR16_HA, tocBiasedVal};
817   case R_PPC64_GOT16_HI:
818   case R_PPC64_GOT_TLSGD16_HI:
819   case R_PPC64_GOT_TLSLD16_HI:
820   case R_PPC64_GOT_TPREL16_HI:
821   case R_PPC64_GOT_DTPREL16_HI:
822   case R_PPC64_TOC16_HI:
823     return {R_PPC64_ADDR16_HI, tocBiasedVal};
824   case R_PPC64_GOT16_LO:
825   case R_PPC64_GOT_TLSGD16_LO:
826   case R_PPC64_GOT_TLSLD16_LO:
827   case R_PPC64_TOC16_LO:
828     return {R_PPC64_ADDR16_LO, tocBiasedVal};
829   case R_PPC64_GOT16_LO_DS:
830   case R_PPC64_TOC16_LO_DS:
831   case R_PPC64_GOT_TPREL16_LO_DS:
832   case R_PPC64_GOT_DTPREL16_LO_DS:
833     return {R_PPC64_ADDR16_LO_DS, tocBiasedVal};
834 
835   // Dynamic Thread pointer biased relocation types.
836   case R_PPC64_DTPREL16:
837     return {R_PPC64_ADDR16, dtpBiasedVal};
838   case R_PPC64_DTPREL16_DS:
839     return {R_PPC64_ADDR16_DS, dtpBiasedVal};
840   case R_PPC64_DTPREL16_HA:
841     return {R_PPC64_ADDR16_HA, dtpBiasedVal};
842   case R_PPC64_DTPREL16_HI:
843     return {R_PPC64_ADDR16_HI, dtpBiasedVal};
844   case R_PPC64_DTPREL16_HIGHER:
845     return {R_PPC64_ADDR16_HIGHER, dtpBiasedVal};
846   case R_PPC64_DTPREL16_HIGHERA:
847     return {R_PPC64_ADDR16_HIGHERA, dtpBiasedVal};
848   case R_PPC64_DTPREL16_HIGHEST:
849     return {R_PPC64_ADDR16_HIGHEST, dtpBiasedVal};
850   case R_PPC64_DTPREL16_HIGHESTA:
851     return {R_PPC64_ADDR16_HIGHESTA, dtpBiasedVal};
852   case R_PPC64_DTPREL16_LO:
853     return {R_PPC64_ADDR16_LO, dtpBiasedVal};
854   case R_PPC64_DTPREL16_LO_DS:
855     return {R_PPC64_ADDR16_LO_DS, dtpBiasedVal};
856   case R_PPC64_DTPREL64:
857     return {R_PPC64_ADDR64, dtpBiasedVal};
858 
859   default:
860     return {type, val};
861   }
862 }
863 
864 static bool isTocOptType(RelType type) {
865   switch (type) {
866   case R_PPC64_GOT16_HA:
867   case R_PPC64_GOT16_LO_DS:
868   case R_PPC64_TOC16_HA:
869   case R_PPC64_TOC16_LO_DS:
870   case R_PPC64_TOC16_LO:
871     return true;
872   default:
873     return false;
874   }
875 }
876 
877 void PPC64::relocate(uint8_t *loc, const Relocation &rel, uint64_t val) const {
878   RelType type = rel.type;
879   bool shouldTocOptimize =  isTocOptType(type);
880   // For dynamic thread pointer relative, toc-relative, and got-indirect
881   // relocations, proceed in terms of the corresponding ADDR16 relocation type.
882   std::tie(type, val) = toAddr16Rel(type, val);
883 
884   switch (type) {
885   case R_PPC64_ADDR14: {
886     checkAlignment(loc, val, 4, rel);
887     // Preserve the AA/LK bits in the branch instruction
888     uint8_t aalk = loc[3];
889     write16(loc + 2, (aalk & 3) | (val & 0xfffc));
890     break;
891   }
892   case R_PPC64_ADDR16:
893     checkIntUInt(loc, val, 16, rel);
894     write16(loc, val);
895     break;
896   case R_PPC64_ADDR32:
897     checkIntUInt(loc, val, 32, rel);
898     write32(loc, val);
899     break;
900   case R_PPC64_ADDR16_DS:
901   case R_PPC64_TPREL16_DS: {
902     checkInt(loc, val, 16, rel);
903     // DQ-form instructions use bits 28-31 as part of the instruction encoding
904     // DS-form instructions only use bits 30-31.
905     uint16_t mask = isDQFormInstruction(readFromHalf16(loc)) ? 0xf : 0x3;
906     checkAlignment(loc, lo(val), mask + 1, rel);
907     write16(loc, (read16(loc) & mask) | lo(val));
908   } break;
909   case R_PPC64_ADDR16_HA:
910   case R_PPC64_REL16_HA:
911   case R_PPC64_TPREL16_HA:
912     if (config->tocOptimize && shouldTocOptimize && ha(val) == 0)
913       writeFromHalf16(loc, 0x60000000);
914     else
915       write16(loc, ha(val));
916     break;
917   case R_PPC64_ADDR16_HI:
918   case R_PPC64_REL16_HI:
919   case R_PPC64_TPREL16_HI:
920     write16(loc, hi(val));
921     break;
922   case R_PPC64_ADDR16_HIGHER:
923   case R_PPC64_TPREL16_HIGHER:
924     write16(loc, higher(val));
925     break;
926   case R_PPC64_ADDR16_HIGHERA:
927   case R_PPC64_TPREL16_HIGHERA:
928     write16(loc, highera(val));
929     break;
930   case R_PPC64_ADDR16_HIGHEST:
931   case R_PPC64_TPREL16_HIGHEST:
932     write16(loc, highest(val));
933     break;
934   case R_PPC64_ADDR16_HIGHESTA:
935   case R_PPC64_TPREL16_HIGHESTA:
936     write16(loc, highesta(val));
937     break;
938   case R_PPC64_ADDR16_LO:
939   case R_PPC64_REL16_LO:
940   case R_PPC64_TPREL16_LO:
941     // When the high-adjusted part of a toc relocation evaluates to 0, it is
942     // changed into a nop. The lo part then needs to be updated to use the
943     // toc-pointer register r2, as the base register.
944     if (config->tocOptimize && shouldTocOptimize && ha(val) == 0) {
945       uint32_t insn = readFromHalf16(loc);
946       if (isInstructionUpdateForm(insn))
947         error(getErrorLocation(loc) +
948               "can't toc-optimize an update instruction: 0x" +
949               utohexstr(insn));
950       writeFromHalf16(loc, (insn & 0xffe00000) | 0x00020000 | lo(val));
951     } else {
952       write16(loc, lo(val));
953     }
954     break;
955   case R_PPC64_ADDR16_LO_DS:
956   case R_PPC64_TPREL16_LO_DS: {
957     // DQ-form instructions use bits 28-31 as part of the instruction encoding
958     // DS-form instructions only use bits 30-31.
959     uint32_t insn = readFromHalf16(loc);
960     uint16_t mask = isDQFormInstruction(insn) ? 0xf : 0x3;
961     checkAlignment(loc, lo(val), mask + 1, rel);
962     if (config->tocOptimize && shouldTocOptimize && ha(val) == 0) {
963       // When the high-adjusted part of a toc relocation evaluates to 0, it is
964       // changed into a nop. The lo part then needs to be updated to use the toc
965       // pointer register r2, as the base register.
966       if (isInstructionUpdateForm(insn))
967         error(getErrorLocation(loc) +
968               "Can't toc-optimize an update instruction: 0x" +
969               Twine::utohexstr(insn));
970       insn &= 0xffe00000 | mask;
971       writeFromHalf16(loc, insn | 0x00020000 | lo(val));
972     } else {
973       write16(loc, (read16(loc) & mask) | lo(val));
974     }
975   } break;
976   case R_PPC64_TPREL16:
977     checkInt(loc, val, 16, rel);
978     write16(loc, val);
979     break;
980   case R_PPC64_REL32:
981     checkInt(loc, val, 32, rel);
982     write32(loc, val);
983     break;
984   case R_PPC64_ADDR64:
985   case R_PPC64_REL64:
986   case R_PPC64_TOC:
987     write64(loc, val);
988     break;
989   case R_PPC64_REL14: {
990     uint32_t mask = 0x0000FFFC;
991     checkInt(loc, val, 16, rel);
992     checkAlignment(loc, val, 4, rel);
993     write32(loc, (read32(loc) & ~mask) | (val & mask));
994     break;
995   }
996   case R_PPC64_REL24: {
997     uint32_t mask = 0x03FFFFFC;
998     checkInt(loc, val, 26, rel);
999     checkAlignment(loc, val, 4, rel);
1000     write32(loc, (read32(loc) & ~mask) | (val & mask));
1001     break;
1002   }
1003   case R_PPC64_DTPREL64:
1004     write64(loc, val - dynamicThreadPointerOffset);
1005     break;
1006   case R_PPC64_PCREL34: {
1007     const uint64_t si0Mask = 0x00000003ffff0000;
1008     const uint64_t si1Mask = 0x000000000000ffff;
1009     const uint64_t fullMask = 0x0003ffff0000ffff;
1010     checkInt(loc, val, 34, rel);
1011 
1012     uint64_t instr = readPrefixedInstruction(loc) & ~fullMask;
1013     writePrefixedInstruction(loc, instr | ((val & si0Mask) << 16) |
1014                              (val & si1Mask));
1015     break;
1016   }
1017   case R_PPC64_GOT_PCREL34: {
1018     const uint64_t si0Mask = 0x00000003ffff0000;
1019     const uint64_t si1Mask = 0x000000000000ffff;
1020     const uint64_t fullMask = 0x0003ffff0000ffff;
1021     checkInt(loc, val, 34, rel);
1022 
1023     uint64_t instr = readPrefixedInstruction(loc) & ~fullMask;
1024     writePrefixedInstruction(loc, instr | ((val & si0Mask) << 16) |
1025                              (val & si1Mask));
1026     break;
1027   }
1028   default:
1029     llvm_unreachable("unknown relocation");
1030   }
1031 }
1032 
1033 bool PPC64::needsThunk(RelExpr expr, RelType type, const InputFile *file,
1034                        uint64_t branchAddr, const Symbol &s, int64_t a) const {
1035   if (type != R_PPC64_REL14 && type != R_PPC64_REL24)
1036     return false;
1037 
1038   // If a function is in the Plt it needs to be called with a call-stub.
1039   if (s.isInPlt())
1040     return true;
1041 
1042   // If a symbol is a weak undefined and we are compiling an executable
1043   // it doesn't need a range-extending thunk since it can't be called.
1044   if (s.isUndefWeak() && !config->shared)
1045     return false;
1046 
1047   // If the offset exceeds the range of the branch type then it will need
1048   // a range-extending thunk.
1049   // See the comment in getRelocTargetVA() about R_PPC64_CALL.
1050   return !inBranchRange(type, branchAddr,
1051                         s.getVA(a) +
1052                             getPPC64GlobalEntryToLocalEntryOffset(s.stOther));
1053 }
1054 
1055 uint32_t PPC64::getThunkSectionSpacing() const {
1056   // See comment in Arch/ARM.cpp for a more detailed explanation of
1057   // getThunkSectionSpacing(). For PPC64 we pick the constant here based on
1058   // R_PPC64_REL24, which is used by unconditional branch instructions.
1059   // 0x2000000 = (1 << 24-1) * 4
1060   return 0x2000000;
1061 }
1062 
1063 bool PPC64::inBranchRange(RelType type, uint64_t src, uint64_t dst) const {
1064   int64_t offset = dst - src;
1065   if (type == R_PPC64_REL14)
1066     return isInt<16>(offset);
1067   if (type == R_PPC64_REL24)
1068     return isInt<26>(offset);
1069   llvm_unreachable("unsupported relocation type used in branch");
1070 }
1071 
1072 RelExpr PPC64::adjustRelaxExpr(RelType type, const uint8_t *data,
1073                                RelExpr expr) const {
1074   if (expr == R_RELAX_TLS_GD_TO_IE)
1075     return R_RELAX_TLS_GD_TO_IE_GOT_OFF;
1076   if (expr == R_RELAX_TLS_LD_TO_LE)
1077     return R_RELAX_TLS_LD_TO_LE_ABS;
1078   return expr;
1079 }
1080 
1081 // Reference: 3.7.4.1 of the 64-bit ELF V2 abi supplement.
1082 // The general dynamic code sequence for a global `x` uses 4 instructions.
1083 // Instruction                    Relocation                Symbol
1084 // addis r3, r2, x@got@tlsgd@ha   R_PPC64_GOT_TLSGD16_HA      x
1085 // addi  r3, r3, x@got@tlsgd@l    R_PPC64_GOT_TLSGD16_LO      x
1086 // bl __tls_get_addr(x@tlsgd)     R_PPC64_TLSGD               x
1087 //                                R_PPC64_REL24               __tls_get_addr
1088 // nop                            None                       None
1089 //
1090 // Relaxing to initial-exec entails:
1091 // 1) Convert the addis/addi pair that builds the address of the tls_index
1092 //    struct for 'x' to an addis/ld pair that loads an offset from a got-entry.
1093 // 2) Convert the call to __tls_get_addr to a nop.
1094 // 3) Convert the nop following the call to an add of the loaded offset to the
1095 //    thread pointer.
1096 // Since the nop must directly follow the call, the R_PPC64_TLSGD relocation is
1097 // used as the relaxation hint for both steps 2 and 3.
1098 void PPC64::relaxTlsGdToIe(uint8_t *loc, const Relocation &rel,
1099                            uint64_t val) const {
1100   switch (rel.type) {
1101   case R_PPC64_GOT_TLSGD16_HA:
1102     // This is relaxed from addis rT, r2, sym@got@tlsgd@ha to
1103     //                      addis rT, r2, sym@got@tprel@ha.
1104     relocateNoSym(loc, R_PPC64_GOT_TPREL16_HA, val);
1105     return;
1106   case R_PPC64_GOT_TLSGD16:
1107   case R_PPC64_GOT_TLSGD16_LO: {
1108     // Relax from addi  r3, rA, sym@got@tlsgd@l to
1109     //            ld r3, sym@got@tprel@l(rA)
1110     uint32_t ra = (readFromHalf16(loc) & (0x1f << 16));
1111     writeFromHalf16(loc, 0xe8600000 | ra);
1112     relocateNoSym(loc, R_PPC64_GOT_TPREL16_LO_DS, val);
1113     return;
1114   }
1115   case R_PPC64_TLSGD:
1116     write32(loc, 0x60000000);     // bl __tls_get_addr(sym@tlsgd) --> nop
1117     write32(loc + 4, 0x7c636A14); // nop --> add r3, r3, r13
1118     return;
1119   default:
1120     llvm_unreachable("unsupported relocation for TLS GD to IE relaxation");
1121   }
1122 }
1123 
1124 // The prologue for a split-stack function is expected to look roughly
1125 // like this:
1126 //    .Lglobal_entry_point:
1127 //      # TOC pointer initialization.
1128 //      ...
1129 //    .Llocal_entry_point:
1130 //      # load the __private_ss member of the threads tcbhead.
1131 //      ld r0,-0x7000-64(r13)
1132 //      # subtract the functions stack size from the stack pointer.
1133 //      addis r12, r1, ha(-stack-frame size)
1134 //      addi  r12, r12, l(-stack-frame size)
1135 //      # compare needed to actual and branch to allocate_more_stack if more
1136 //      # space is needed, otherwise fallthrough to 'normal' function body.
1137 //      cmpld cr7,r12,r0
1138 //      blt- cr7, .Lallocate_more_stack
1139 //
1140 // -) The allocate_more_stack block might be placed after the split-stack
1141 //    prologue and the `blt-` replaced with a `bge+ .Lnormal_func_body`
1142 //    instead.
1143 // -) If either the addis or addi is not needed due to the stack size being
1144 //    smaller then 32K or a multiple of 64K they will be replaced with a nop,
1145 //    but there will always be 2 instructions the linker can overwrite for the
1146 //    adjusted stack size.
1147 //
1148 // The linkers job here is to increase the stack size used in the addis/addi
1149 // pair by split-stack-size-adjust.
1150 // addis r12, r1, ha(-stack-frame size - split-stack-adjust-size)
1151 // addi  r12, r12, l(-stack-frame size - split-stack-adjust-size)
1152 bool PPC64::adjustPrologueForCrossSplitStack(uint8_t *loc, uint8_t *end,
1153                                              uint8_t stOther) const {
1154   // If the caller has a global entry point adjust the buffer past it. The start
1155   // of the split-stack prologue will be at the local entry point.
1156   loc += getPPC64GlobalEntryToLocalEntryOffset(stOther);
1157 
1158   // At the very least we expect to see a load of some split-stack data from the
1159   // tcb, and 2 instructions that calculate the ending stack address this
1160   // function will require. If there is not enough room for at least 3
1161   // instructions it can't be a split-stack prologue.
1162   if (loc + 12 >= end)
1163     return false;
1164 
1165   // First instruction must be `ld r0, -0x7000-64(r13)`
1166   if (read32(loc) != 0xe80d8fc0)
1167     return false;
1168 
1169   int16_t hiImm = 0;
1170   int16_t loImm = 0;
1171   // First instruction can be either an addis if the frame size is larger then
1172   // 32K, or an addi if the size is less then 32K.
1173   int32_t firstInstr = read32(loc + 4);
1174   if (getPrimaryOpCode(firstInstr) == 15) {
1175     hiImm = firstInstr & 0xFFFF;
1176   } else if (getPrimaryOpCode(firstInstr) == 14) {
1177     loImm = firstInstr & 0xFFFF;
1178   } else {
1179     return false;
1180   }
1181 
1182   // Second instruction is either an addi or a nop. If the first instruction was
1183   // an addi then LoImm is set and the second instruction must be a nop.
1184   uint32_t secondInstr = read32(loc + 8);
1185   if (!loImm && getPrimaryOpCode(secondInstr) == 14) {
1186     loImm = secondInstr & 0xFFFF;
1187   } else if (secondInstr != 0x60000000) {
1188     return false;
1189   }
1190 
1191   // The register operands of the first instruction should be the stack-pointer
1192   // (r1) as the input (RA) and r12 as the output (RT). If the second
1193   // instruction is not a nop, then it should use r12 as both input and output.
1194   auto checkRegOperands = [](uint32_t instr, uint8_t expectedRT,
1195                              uint8_t expectedRA) {
1196     return ((instr & 0x3E00000) >> 21 == expectedRT) &&
1197            ((instr & 0x1F0000) >> 16 == expectedRA);
1198   };
1199   if (!checkRegOperands(firstInstr, 12, 1))
1200     return false;
1201   if (secondInstr != 0x60000000 && !checkRegOperands(secondInstr, 12, 12))
1202     return false;
1203 
1204   int32_t stackFrameSize = (hiImm * 65536) + loImm;
1205   // Check that the adjusted size doesn't overflow what we can represent with 2
1206   // instructions.
1207   if (stackFrameSize < config->splitStackAdjustSize + INT32_MIN) {
1208     error(getErrorLocation(loc) + "split-stack prologue adjustment overflows");
1209     return false;
1210   }
1211 
1212   int32_t adjustedStackFrameSize =
1213       stackFrameSize - config->splitStackAdjustSize;
1214 
1215   loImm = adjustedStackFrameSize & 0xFFFF;
1216   hiImm = (adjustedStackFrameSize + 0x8000) >> 16;
1217   if (hiImm) {
1218     write32(loc + 4, 0x3D810000 | (uint16_t)hiImm);
1219     // If the low immediate is zero the second instruction will be a nop.
1220     secondInstr = loImm ? 0x398C0000 | (uint16_t)loImm : 0x60000000;
1221     write32(loc + 8, secondInstr);
1222   } else {
1223     // addi r12, r1, imm
1224     write32(loc + 4, (0x39810000) | (uint16_t)loImm);
1225     write32(loc + 8, 0x60000000);
1226   }
1227 
1228   return true;
1229 }
1230 
1231 TargetInfo *elf::getPPC64TargetInfo() {
1232   static PPC64 target;
1233   return &target;
1234 }
1235