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