xref: /llvm-project-15.0.7/lld/ELF/Arch/PPC64.cpp (revision bacf751a)
1 //===- PPC64.cpp ----------------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "Symbols.h"
11 #include "SyntheticSections.h"
12 #include "Target.h"
13 #include "lld/Common/ErrorHandler.h"
14 #include "llvm/Support/Endian.h"
15 
16 using namespace llvm;
17 using namespace llvm::object;
18 using namespace llvm::support::endian;
19 using namespace llvm::ELF;
20 using namespace lld;
21 using namespace lld::elf;
22 
23 static uint64_t PPC64TocOffset = 0x8000;
24 static uint64_t DynamicThreadPointerOffset = 0x8000;
25 
26 // The instruction encoding of bits 21-30 from the ISA for the Xform and Dform
27 // instructions that can be used as part of the initial exec TLS sequence.
28 enum XFormOpcd {
29   LBZX = 87,
30   LHZX = 279,
31   LWZX = 23,
32   LDX = 21,
33   STBX = 215,
34   STHX = 407,
35   STWX = 151,
36   STDX = 149,
37   ADD = 266,
38 };
39 
40 enum DFormOpcd {
41   LBZ = 34,
42   LBZU = 35,
43   LHZ = 40,
44   LHZU = 41,
45   LHAU = 43,
46   LWZ = 32,
47   LWZU = 33,
48   LFSU = 49,
49   LD = 58,
50   LFDU = 51,
51   STB = 38,
52   STBU = 39,
53   STH = 44,
54   STHU = 45,
55   STW = 36,
56   STWU = 37,
57   STFSU = 53,
58   STFDU = 55,
59   STD = 62,
60   ADDI = 14
61 };
62 
63 uint64_t elf::getPPC64TocBase() {
64   // The TOC consists of sections .got, .toc, .tocbss, .plt in that order. The
65   // TOC starts where the first of these sections starts. We always create a
66   // .got when we see a relocation that uses it, so for us the start is always
67   // the .got.
68   uint64_t TocVA = In.Got->getVA();
69 
70   // Per the ppc64-elf-linux ABI, The TOC base is TOC value plus 0x8000
71   // thus permitting a full 64 Kbytes segment. Note that the glibc startup
72   // code (crt1.o) assumes that you can get from the TOC base to the
73   // start of the .toc section with only a single (signed) 16-bit relocation.
74   return TocVA + PPC64TocOffset;
75 }
76 
77 unsigned elf::getPPC64GlobalEntryToLocalEntryOffset(uint8_t StOther) {
78   // The offset is encoded into the 3 most significant bits of the st_other
79   // field, with some special values described in section 3.4.1 of the ABI:
80   // 0   --> Zero offset between the GEP and LEP, and the function does NOT use
81   //         the TOC pointer (r2). r2 will hold the same value on returning from
82   //         the function as it did on entering the function.
83   // 1   --> Zero offset between the GEP and LEP, and r2 should be treated as a
84   //         caller-saved register for all callers.
85   // 2-6 --> The  binary logarithm of the offset eg:
86   //         2 --> 2^2 = 4 bytes -->  1 instruction.
87   //         6 --> 2^6 = 64 bytes --> 16 instructions.
88   // 7   --> Reserved.
89   uint8_t GepToLep = (StOther >> 5) & 7;
90   if (GepToLep < 2)
91     return 0;
92 
93   // The value encoded in the st_other bits is the
94   // log-base-2(offset).
95   if (GepToLep < 7)
96     return 1 << GepToLep;
97 
98   error("reserved value of 7 in the 3 most-significant-bits of st_other");
99   return 0;
100 }
101 
102 namespace {
103 class PPC64 final : public TargetInfo {
104 public:
105   PPC64();
106   uint32_t calcEFlags() const override;
107   RelExpr getRelExpr(RelType Type, const Symbol &S,
108                      const uint8_t *Loc) const override;
109   void writePltHeader(uint8_t *Buf) const override;
110   void writePlt(uint8_t *Buf, uint64_t GotPltEntryAddr, uint64_t PltEntryAddr,
111                 int32_t Index, unsigned RelOff) const override;
112   void relocateOne(uint8_t *Loc, RelType Type, uint64_t Val) const override;
113   void writeGotHeader(uint8_t *Buf) const override;
114   bool needsThunk(RelExpr Expr, RelType Type, const InputFile *File,
115                   uint64_t BranchAddr, const Symbol &S) const override;
116   RelExpr adjustRelaxExpr(RelType Type, const uint8_t *Data,
117                           RelExpr Expr) const override;
118   void relaxTlsGdToIe(uint8_t *Loc, RelType Type, uint64_t Val) const override;
119   void relaxTlsGdToLe(uint8_t *Loc, RelType Type, uint64_t Val) const override;
120   void relaxTlsLdToLe(uint8_t *Loc, RelType Type, uint64_t Val) const override;
121   void relaxTlsIeToLe(uint8_t *Loc, RelType Type, uint64_t Val) const override;
122 
123   bool adjustPrologueForCrossSplitStack(uint8_t *Loc, uint8_t *End,
124                                         uint8_t StOther) const override;
125 };
126 } // namespace
127 
128 // Relocation masks following the #lo(value), #hi(value), #ha(value),
129 // #higher(value), #highera(value), #highest(value), and #highesta(value)
130 // macros defined in section 4.5.1. Relocation Types of the PPC-elf64abi
131 // document.
132 static uint16_t lo(uint64_t V) { return V; }
133 static uint16_t hi(uint64_t V) { return V >> 16; }
134 static uint16_t ha(uint64_t V) { return (V + 0x8000) >> 16; }
135 static uint16_t higher(uint64_t V) { return V >> 32; }
136 static uint16_t highera(uint64_t V) { return (V + 0x8000) >> 32; }
137 static uint16_t highest(uint64_t V) { return V >> 48; }
138 static uint16_t highesta(uint64_t V) { return (V + 0x8000) >> 48; }
139 
140 // Extracts the 'PO' field of an instruction encoding.
141 static uint8_t getPrimaryOpCode(uint32_t Encoding) { return (Encoding >> 26); }
142 
143 static bool isDQFormInstruction(uint32_t Encoding) {
144   switch (getPrimaryOpCode(Encoding)) {
145   default:
146     return false;
147   case 56:
148     // The only instruction with a primary opcode of 56 is `lq`.
149     return true;
150   case 61:
151     // There are both DS and DQ instruction forms with this primary opcode.
152     // Namely `lxv` and `stxv` are the DQ-forms that use it.
153     // The DS 'XO' bits being set to 01 is restricted to DQ form.
154     return (Encoding & 3) == 0x1;
155   }
156 }
157 
158 static bool isInstructionUpdateForm(uint32_t Encoding) {
159   switch (getPrimaryOpCode(Encoding)) {
160   default:
161     return false;
162   case LBZU:
163   case LHAU:
164   case LHZU:
165   case LWZU:
166   case LFSU:
167   case LFDU:
168   case STBU:
169   case STHU:
170   case STWU:
171   case STFSU:
172   case STFDU:
173     return true;
174     // LWA has the same opcode as LD, and the DS bits is what differentiates
175     // between LD/LDU/LWA
176   case LD:
177   case STD:
178     return (Encoding & 3) == 1;
179   }
180 }
181 
182 // There are a number of places when we either want to read or write an
183 // instruction when handling a half16 relocation type. On big-endian the buffer
184 // pointer is pointing into the middle of the word we want to extract, and on
185 // little-endian it is pointing to the start of the word. These 2 helpers are to
186 // simplify reading and writing in that context.
187 static void writeInstrFromHalf16(uint8_t *Loc, uint32_t Instr) {
188   write32(Loc - (Config->EKind == ELF64BEKind ? 2 : 0), Instr);
189 }
190 
191 static uint32_t readInstrFromHalf16(const uint8_t *Loc) {
192   return read32(Loc - (Config->EKind == ELF64BEKind ? 2 : 0));
193 }
194 
195 PPC64::PPC64() {
196   GotRel = R_PPC64_GLOB_DAT;
197   NoneRel = R_PPC64_NONE;
198   PltRel = R_PPC64_JMP_SLOT;
199   RelativeRel = R_PPC64_RELATIVE;
200   IRelativeRel = R_PPC64_IRELATIVE;
201   GotEntrySize = 8;
202   PltEntrySize = 4;
203   GotPltEntrySize = 8;
204   GotBaseSymInGotPlt = false;
205   GotBaseSymOff = 0x8000;
206   GotHeaderEntriesNum = 1;
207   GotPltHeaderEntriesNum = 2;
208   PltHeaderSize = 60;
209   NeedsThunks = true;
210   TcbSize = 8;
211   TlsTpOffset = 0x7000;
212 
213   TlsModuleIndexRel = R_PPC64_DTPMOD64;
214   TlsOffsetRel = R_PPC64_DTPREL64;
215 
216   TlsGotRel = R_PPC64_TPREL64;
217 
218   NeedsMoreStackNonSplit = false;
219 
220   // We need 64K pages (at least under glibc/Linux, the loader won't
221   // set different permissions on a finer granularity than that).
222   DefaultMaxPageSize = 65536;
223 
224   // The PPC64 ELF ABI v1 spec, says:
225   //
226   //   It is normally desirable to put segments with different characteristics
227   //   in separate 256 Mbyte portions of the address space, to give the
228   //   operating system full paging flexibility in the 64-bit address space.
229   //
230   // And because the lowest non-zero 256M boundary is 0x10000000, PPC64 linkers
231   // use 0x10000000 as the starting address.
232   DefaultImageBase = 0x10000000;
233 
234   TrapInstr =
235       (Config->IsLE == sys::IsLittleEndianHost) ? 0x7fe00008 : 0x0800e07f;
236 }
237 
238 static uint32_t getEFlags(InputFile *File) {
239   if (Config->EKind == ELF64BEKind)
240     return cast<ObjFile<ELF64BE>>(File)->getObj().getHeader()->e_flags;
241   return cast<ObjFile<ELF64LE>>(File)->getObj().getHeader()->e_flags;
242 }
243 
244 // This file implements v2 ABI. This function makes sure that all
245 // object files have v2 or an unspecified version as an ABI version.
246 uint32_t PPC64::calcEFlags() const {
247   for (InputFile *F : ObjectFiles) {
248     uint32_t Flag = getEFlags(F);
249     if (Flag == 1)
250       error(toString(F) + ": ABI version 1 is not supported");
251     else if (Flag > 2)
252       error(toString(F) + ": unrecognized e_flags: " + Twine(Flag));
253   }
254   return 2;
255 }
256 
257 void PPC64::relaxTlsGdToLe(uint8_t *Loc, RelType Type, uint64_t Val) const {
258   // Reference: 3.7.4.2 of the 64-bit ELF V2 abi supplement.
259   // The general dynamic code sequence for a global `x` will look like:
260   // Instruction                    Relocation                Symbol
261   // addis r3, r2, x@got@tlsgd@ha   R_PPC64_GOT_TLSGD16_HA      x
262   // addi  r3, r3, x@got@tlsgd@l    R_PPC64_GOT_TLSGD16_LO      x
263   // bl __tls_get_addr(x@tlsgd)     R_PPC64_TLSGD               x
264   //                                R_PPC64_REL24               __tls_get_addr
265   // nop                            None                       None
266 
267   // Relaxing to local exec entails converting:
268   // addis r3, r2, x@got@tlsgd@ha    into      nop
269   // addi  r3, r3, x@got@tlsgd@l     into      addis r3, r13, x@tprel@ha
270   // bl __tls_get_addr(x@tlsgd)      into      nop
271   // nop                             into      addi r3, r3, x@tprel@l
272 
273   switch (Type) {
274   case R_PPC64_GOT_TLSGD16_HA:
275     writeInstrFromHalf16(Loc, 0x60000000); // nop
276     break;
277   case R_PPC64_GOT_TLSGD16:
278   case R_PPC64_GOT_TLSGD16_LO:
279     writeInstrFromHalf16(Loc, 0x3c6d0000); // addis r3, r13
280     relocateOne(Loc, R_PPC64_TPREL16_HA, Val);
281     break;
282   case R_PPC64_TLSGD:
283     write32(Loc, 0x60000000);     // nop
284     write32(Loc + 4, 0x38630000); // addi r3, r3
285     // Since we are relocating a half16 type relocation and Loc + 4 points to
286     // the start of an instruction we need to advance the buffer by an extra
287     // 2 bytes on BE.
288     relocateOne(Loc + 4 + (Config->EKind == ELF64BEKind ? 2 : 0),
289                 R_PPC64_TPREL16_LO, Val);
290     break;
291   default:
292     llvm_unreachable("unsupported relocation for TLS GD to LE relaxation");
293   }
294 }
295 
296 void PPC64::relaxTlsLdToLe(uint8_t *Loc, RelType Type, uint64_t Val) const {
297   // Reference: 3.7.4.3 of the 64-bit ELF V2 abi supplement.
298   // The local dynamic code sequence for a global `x` will look like:
299   // Instruction                    Relocation                Symbol
300   // addis r3, r2, x@got@tlsld@ha   R_PPC64_GOT_TLSLD16_HA      x
301   // addi  r3, r3, x@got@tlsld@l    R_PPC64_GOT_TLSLD16_LO      x
302   // bl __tls_get_addr(x@tlsgd)     R_PPC64_TLSLD               x
303   //                                R_PPC64_REL24               __tls_get_addr
304   // nop                            None                       None
305 
306   // Relaxing to local exec entails converting:
307   // addis r3, r2, x@got@tlsld@ha   into      nop
308   // addi  r3, r3, x@got@tlsld@l    into      addis r3, r13, 0
309   // bl __tls_get_addr(x@tlsgd)     into      nop
310   // nop                            into      addi r3, r3, 4096
311 
312   switch (Type) {
313   case R_PPC64_GOT_TLSLD16_HA:
314     writeInstrFromHalf16(Loc, 0x60000000); // nop
315     break;
316   case R_PPC64_GOT_TLSLD16_LO:
317     writeInstrFromHalf16(Loc, 0x3c6d0000); // addis r3, r13, 0
318     break;
319   case R_PPC64_TLSLD:
320     write32(Loc, 0x60000000);     // nop
321     write32(Loc + 4, 0x38631000); // addi r3, r3, 4096
322     break;
323   case R_PPC64_DTPREL16:
324   case R_PPC64_DTPREL16_HA:
325   case R_PPC64_DTPREL16_HI:
326   case R_PPC64_DTPREL16_DS:
327   case R_PPC64_DTPREL16_LO:
328   case R_PPC64_DTPREL16_LO_DS:
329   case R_PPC64_GOT_DTPREL16_HA:
330   case R_PPC64_GOT_DTPREL16_LO_DS:
331   case R_PPC64_GOT_DTPREL16_DS:
332   case R_PPC64_GOT_DTPREL16_HI:
333     relocateOne(Loc, Type, Val);
334     break;
335   default:
336     llvm_unreachable("unsupported relocation for TLS LD to LE relaxation");
337   }
338 }
339 
340 static unsigned getDFormOp(unsigned SecondaryOp) {
341   switch (SecondaryOp) {
342   case LBZX:
343     return LBZ;
344   case LHZX:
345     return LHZ;
346   case LWZX:
347     return LWZ;
348   case LDX:
349     return LD;
350   case STBX:
351     return STB;
352   case STHX:
353     return STH;
354   case STWX:
355     return STW;
356   case STDX:
357     return STD;
358   case ADD:
359     return ADDI;
360   default:
361     error("unrecognized instruction for IE to LE R_PPC64_TLS");
362     return 0;
363   }
364 }
365 
366 void PPC64::relaxTlsIeToLe(uint8_t *Loc, RelType Type, uint64_t Val) const {
367   // The initial exec code sequence for a global `x` will look like:
368   // Instruction                    Relocation                Symbol
369   // addis r9, r2, x@got@tprel@ha   R_PPC64_GOT_TPREL16_HA      x
370   // ld    r9, x@got@tprel@l(r9)    R_PPC64_GOT_TPREL16_LO_DS   x
371   // add r9, r9, x@tls              R_PPC64_TLS                 x
372 
373   // Relaxing to local exec entails converting:
374   // addis r9, r2, x@got@tprel@ha       into        nop
375   // ld r9, x@got@tprel@l(r9)           into        addis r9, r13, x@tprel@ha
376   // add r9, r9, x@tls                  into        addi r9, r9, x@tprel@l
377 
378   // x@tls R_PPC64_TLS is a relocation which does not compute anything,
379   // it is replaced with r13 (thread pointer).
380 
381   // The add instruction in the initial exec sequence has multiple variations
382   // that need to be handled. If we are building an address it will use an add
383   // instruction, if we are accessing memory it will use any of the X-form
384   // indexed load or store instructions.
385 
386   unsigned Offset = (Config->EKind == ELF64BEKind) ? 2 : 0;
387   switch (Type) {
388   case R_PPC64_GOT_TPREL16_HA:
389     write32(Loc - Offset, 0x60000000); // nop
390     break;
391   case R_PPC64_GOT_TPREL16_LO_DS:
392   case R_PPC64_GOT_TPREL16_DS: {
393     uint32_t RegNo = read32(Loc - Offset) & 0x03E00000; // bits 6-10
394     write32(Loc - Offset, 0x3C0D0000 | RegNo);          // addis RegNo, r13
395     relocateOne(Loc, R_PPC64_TPREL16_HA, Val);
396     break;
397   }
398   case R_PPC64_TLS: {
399     uint32_t PrimaryOp = getPrimaryOpCode(read32(Loc));
400     if (PrimaryOp != 31)
401       error("unrecognized instruction for IE to LE R_PPC64_TLS");
402     uint32_t SecondaryOp = (read32(Loc) & 0x000007FE) >> 1; // bits 21-30
403     uint32_t DFormOp = getDFormOp(SecondaryOp);
404     write32(Loc, ((DFormOp << 26) | (read32(Loc) & 0x03FFFFFF)));
405     relocateOne(Loc + Offset, R_PPC64_TPREL16_LO, Val);
406     break;
407   }
408   default:
409     llvm_unreachable("unknown relocation for IE to LE");
410     break;
411   }
412 }
413 
414 RelExpr PPC64::getRelExpr(RelType Type, const Symbol &S,
415                           const uint8_t *Loc) const {
416   switch (Type) {
417   case R_PPC64_TOC16:
418   case R_PPC64_TOC16_DS:
419   case R_PPC64_TOC16_HA:
420   case R_PPC64_TOC16_HI:
421   case R_PPC64_TOC16_LO:
422   case R_PPC64_TOC16_LO_DS:
423     return R_GOTREL;
424   case R_PPC64_TOC:
425     return R_PPC_TOC;
426   case R_PPC64_REL24:
427     return R_PPC_CALL_PLT;
428   case R_PPC64_REL16_LO:
429   case R_PPC64_REL16_HA:
430   case R_PPC64_REL32:
431   case R_PPC64_REL64:
432     return R_PC;
433   case R_PPC64_GOT_TLSGD16:
434   case R_PPC64_GOT_TLSGD16_HA:
435   case R_PPC64_GOT_TLSGD16_HI:
436   case R_PPC64_GOT_TLSGD16_LO:
437     return R_TLSGD_GOT;
438   case R_PPC64_GOT_TLSLD16:
439   case R_PPC64_GOT_TLSLD16_HA:
440   case R_PPC64_GOT_TLSLD16_HI:
441   case R_PPC64_GOT_TLSLD16_LO:
442     return R_TLSLD_GOT;
443   case R_PPC64_GOT_TPREL16_HA:
444   case R_PPC64_GOT_TPREL16_LO_DS:
445   case R_PPC64_GOT_TPREL16_DS:
446   case R_PPC64_GOT_TPREL16_HI:
447     return R_GOT_OFF;
448   case R_PPC64_GOT_DTPREL16_HA:
449   case R_PPC64_GOT_DTPREL16_LO_DS:
450   case R_PPC64_GOT_DTPREL16_DS:
451   case R_PPC64_GOT_DTPREL16_HI:
452     return R_TLSLD_GOT_OFF;
453   case R_PPC64_TPREL16:
454   case R_PPC64_TPREL16_HA:
455   case R_PPC64_TPREL16_LO:
456   case R_PPC64_TPREL16_HI:
457   case R_PPC64_TPREL16_DS:
458   case R_PPC64_TPREL16_LO_DS:
459   case R_PPC64_TPREL16_HIGHER:
460   case R_PPC64_TPREL16_HIGHERA:
461   case R_PPC64_TPREL16_HIGHEST:
462   case R_PPC64_TPREL16_HIGHESTA:
463     return R_TLS;
464   case R_PPC64_DTPREL16:
465   case R_PPC64_DTPREL16_DS:
466   case R_PPC64_DTPREL16_HA:
467   case R_PPC64_DTPREL16_HI:
468   case R_PPC64_DTPREL16_HIGHER:
469   case R_PPC64_DTPREL16_HIGHERA:
470   case R_PPC64_DTPREL16_HIGHEST:
471   case R_PPC64_DTPREL16_HIGHESTA:
472   case R_PPC64_DTPREL16_LO:
473   case R_PPC64_DTPREL16_LO_DS:
474   case R_PPC64_DTPREL64:
475     return R_ABS;
476   case R_PPC64_TLSGD:
477     return R_TLSDESC_CALL;
478   case R_PPC64_TLSLD:
479     return R_TLSLD_HINT;
480   case R_PPC64_TLS:
481     return R_TLSIE_HINT;
482   default:
483     return R_ABS;
484   }
485 }
486 
487 void PPC64::writeGotHeader(uint8_t *Buf) const {
488   write64(Buf, getPPC64TocBase());
489 }
490 
491 void PPC64::writePltHeader(uint8_t *Buf) const {
492   // The generic resolver stub goes first.
493   write32(Buf +  0, 0x7c0802a6); // mflr r0
494   write32(Buf +  4, 0x429f0005); // bcl  20,4*cr7+so,8 <_glink+0x8>
495   write32(Buf +  8, 0x7d6802a6); // mflr r11
496   write32(Buf + 12, 0x7c0803a6); // mtlr r0
497   write32(Buf + 16, 0x7d8b6050); // subf r12, r11, r12
498   write32(Buf + 20, 0x380cffcc); // subi r0,r12,52
499   write32(Buf + 24, 0x7800f082); // srdi r0,r0,62,2
500   write32(Buf + 28, 0xe98b002c); // ld   r12,44(r11)
501   write32(Buf + 32, 0x7d6c5a14); // add  r11,r12,r11
502   write32(Buf + 36, 0xe98b0000); // ld   r12,0(r11)
503   write32(Buf + 40, 0xe96b0008); // ld   r11,8(r11)
504   write32(Buf + 44, 0x7d8903a6); // mtctr   r12
505   write32(Buf + 48, 0x4e800420); // bctr
506 
507   // The 'bcl' instruction will set the link register to the address of the
508   // following instruction ('mflr r11'). Here we store the offset from that
509   // instruction  to the first entry in the GotPlt section.
510   int64_t GotPltOffset = In.GotPlt->getVA() - (In.Plt->getVA() + 8);
511   write64(Buf + 52, GotPltOffset);
512 }
513 
514 void PPC64::writePlt(uint8_t *Buf, uint64_t GotPltEntryAddr,
515                      uint64_t PltEntryAddr, int32_t Index,
516                      unsigned RelOff) const {
517   int32_t Offset = PltHeaderSize + Index * PltEntrySize;
518   // bl __glink_PLTresolve
519   write32(Buf, 0x48000000 | ((-Offset) & 0x03FFFFFc));
520 }
521 
522 static std::pair<RelType, uint64_t> toAddr16Rel(RelType Type, uint64_t Val) {
523   // Relocations relative to the toc-base need to be adjusted by the Toc offset.
524   uint64_t TocBiasedVal = Val - PPC64TocOffset;
525   // Relocations relative to dtv[dtpmod] need to be adjusted by the DTP offset.
526   uint64_t DTPBiasedVal = Val - DynamicThreadPointerOffset;
527 
528   switch (Type) {
529   // TOC biased relocation.
530   case R_PPC64_GOT_TLSGD16:
531   case R_PPC64_GOT_TLSLD16:
532   case R_PPC64_TOC16:
533     return {R_PPC64_ADDR16, TocBiasedVal};
534   case R_PPC64_TOC16_DS:
535   case R_PPC64_GOT_TPREL16_DS:
536   case R_PPC64_GOT_DTPREL16_DS:
537     return {R_PPC64_ADDR16_DS, TocBiasedVal};
538   case R_PPC64_GOT_TLSGD16_HA:
539   case R_PPC64_GOT_TLSLD16_HA:
540   case R_PPC64_GOT_TPREL16_HA:
541   case R_PPC64_GOT_DTPREL16_HA:
542   case R_PPC64_TOC16_HA:
543     return {R_PPC64_ADDR16_HA, TocBiasedVal};
544   case R_PPC64_GOT_TLSGD16_HI:
545   case R_PPC64_GOT_TLSLD16_HI:
546   case R_PPC64_GOT_TPREL16_HI:
547   case R_PPC64_GOT_DTPREL16_HI:
548   case R_PPC64_TOC16_HI:
549     return {R_PPC64_ADDR16_HI, TocBiasedVal};
550   case R_PPC64_GOT_TLSGD16_LO:
551   case R_PPC64_GOT_TLSLD16_LO:
552   case R_PPC64_TOC16_LO:
553     return {R_PPC64_ADDR16_LO, TocBiasedVal};
554   case R_PPC64_TOC16_LO_DS:
555   case R_PPC64_GOT_TPREL16_LO_DS:
556   case R_PPC64_GOT_DTPREL16_LO_DS:
557     return {R_PPC64_ADDR16_LO_DS, TocBiasedVal};
558 
559   // Dynamic Thread pointer biased relocation types.
560   case R_PPC64_DTPREL16:
561     return {R_PPC64_ADDR16, DTPBiasedVal};
562   case R_PPC64_DTPREL16_DS:
563     return {R_PPC64_ADDR16_DS, DTPBiasedVal};
564   case R_PPC64_DTPREL16_HA:
565     return {R_PPC64_ADDR16_HA, DTPBiasedVal};
566   case R_PPC64_DTPREL16_HI:
567     return {R_PPC64_ADDR16_HI, DTPBiasedVal};
568   case R_PPC64_DTPREL16_HIGHER:
569     return {R_PPC64_ADDR16_HIGHER, DTPBiasedVal};
570   case R_PPC64_DTPREL16_HIGHERA:
571     return {R_PPC64_ADDR16_HIGHERA, DTPBiasedVal};
572   case R_PPC64_DTPREL16_HIGHEST:
573     return {R_PPC64_ADDR16_HIGHEST, DTPBiasedVal};
574   case R_PPC64_DTPREL16_HIGHESTA:
575     return {R_PPC64_ADDR16_HIGHESTA, DTPBiasedVal};
576   case R_PPC64_DTPREL16_LO:
577     return {R_PPC64_ADDR16_LO, DTPBiasedVal};
578   case R_PPC64_DTPREL16_LO_DS:
579     return {R_PPC64_ADDR16_LO_DS, DTPBiasedVal};
580   case R_PPC64_DTPREL64:
581     return {R_PPC64_ADDR64, DTPBiasedVal};
582 
583   default:
584     return {Type, Val};
585   }
586 }
587 
588 static bool isTocRelType(RelType Type) {
589   return Type == R_PPC64_TOC16_HA || Type == R_PPC64_TOC16_LO_DS ||
590          Type == R_PPC64_TOC16_LO;
591 }
592 
593 void PPC64::relocateOne(uint8_t *Loc, RelType Type, uint64_t Val) const {
594   // For a TOC-relative relocation, proceed in terms of the corresponding
595   // ADDR16 relocation type.
596   bool IsTocRelType = isTocRelType(Type);
597   std::tie(Type, Val) = toAddr16Rel(Type, Val);
598 
599   switch (Type) {
600   case R_PPC64_ADDR14: {
601     checkAlignment(Loc, Val, 4, Type);
602     // Preserve the AA/LK bits in the branch instruction
603     uint8_t AALK = Loc[3];
604     write16(Loc + 2, (AALK & 3) | (Val & 0xfffc));
605     break;
606   }
607   case R_PPC64_ADDR16:
608   case R_PPC64_TPREL16:
609     checkInt(Loc, Val, 16, Type);
610     write16(Loc, Val);
611     break;
612   case R_PPC64_ADDR16_DS:
613   case R_PPC64_TPREL16_DS: {
614     checkInt(Loc, Val, 16, Type);
615     // DQ-form instructions use bits 28-31 as part of the instruction encoding
616     // DS-form instructions only use bits 30-31.
617     uint16_t Mask = isDQFormInstruction(readInstrFromHalf16(Loc)) ? 0xF : 0x3;
618     checkAlignment(Loc, lo(Val), Mask + 1, Type);
619     write16(Loc, (read16(Loc) & Mask) | lo(Val));
620   } break;
621   case R_PPC64_ADDR16_HA:
622   case R_PPC64_REL16_HA:
623   case R_PPC64_TPREL16_HA:
624     if (Config->TocOptimize && IsTocRelType && ha(Val) == 0)
625       writeInstrFromHalf16(Loc, 0x60000000);
626     else
627       write16(Loc, ha(Val));
628     break;
629   case R_PPC64_ADDR16_HI:
630   case R_PPC64_REL16_HI:
631   case R_PPC64_TPREL16_HI:
632     write16(Loc, hi(Val));
633     break;
634   case R_PPC64_ADDR16_HIGHER:
635   case R_PPC64_TPREL16_HIGHER:
636     write16(Loc, higher(Val));
637     break;
638   case R_PPC64_ADDR16_HIGHERA:
639   case R_PPC64_TPREL16_HIGHERA:
640     write16(Loc, highera(Val));
641     break;
642   case R_PPC64_ADDR16_HIGHEST:
643   case R_PPC64_TPREL16_HIGHEST:
644     write16(Loc, highest(Val));
645     break;
646   case R_PPC64_ADDR16_HIGHESTA:
647   case R_PPC64_TPREL16_HIGHESTA:
648     write16(Loc, highesta(Val));
649     break;
650   case R_PPC64_ADDR16_LO:
651   case R_PPC64_REL16_LO:
652   case R_PPC64_TPREL16_LO:
653     // When the high-adjusted part of a toc relocation evalutes to 0, it is
654     // changed into a nop. The lo part then needs to be updated to use the
655     // toc-pointer register r2, as the base register.
656     if (Config->TocOptimize && IsTocRelType && ha(Val) == 0) {
657       uint32_t Instr = readInstrFromHalf16(Loc);
658       if (isInstructionUpdateForm(Instr))
659         error(getErrorLocation(Loc) +
660               "can't toc-optimize an update instruction: 0x" +
661               utohexstr(Instr));
662       Instr = (Instr & 0xFFE00000) | 0x00020000;
663       writeInstrFromHalf16(Loc, Instr);
664     }
665     write16(Loc, lo(Val));
666     break;
667   case R_PPC64_ADDR16_LO_DS:
668   case R_PPC64_TPREL16_LO_DS: {
669     // DQ-form instructions use bits 28-31 as part of the instruction encoding
670     // DS-form instructions only use bits 30-31.
671     uint32_t Inst = readInstrFromHalf16(Loc);
672     uint16_t Mask = isDQFormInstruction(Inst) ? 0xF : 0x3;
673     checkAlignment(Loc, lo(Val), Mask + 1, Type);
674     if (Config->TocOptimize && IsTocRelType && ha(Val) == 0) {
675       // When the high-adjusted part of a toc relocation evalutes to 0, it is
676       // changed into a nop. The lo part then needs to be updated to use the toc
677       // pointer register r2, as the base register.
678       if (isInstructionUpdateForm(Inst))
679         error(getErrorLocation(Loc) +
680               "Can't toc-optimize an update instruction: 0x" +
681               Twine::utohexstr(Inst));
682       Inst = (Inst & 0xFFE0000F) | 0x00020000;
683       writeInstrFromHalf16(Loc, Inst);
684     }
685     write16(Loc, (read16(Loc) & Mask) | lo(Val));
686   } break;
687   case R_PPC64_ADDR32:
688   case R_PPC64_REL32:
689     checkInt(Loc, Val, 32, Type);
690     write32(Loc, Val);
691     break;
692   case R_PPC64_ADDR64:
693   case R_PPC64_REL64:
694   case R_PPC64_TOC:
695     write64(Loc, Val);
696     break;
697   case R_PPC64_REL24: {
698     uint32_t Mask = 0x03FFFFFC;
699     checkInt(Loc, Val, 26, Type);
700     checkAlignment(Loc, Val, 4, Type);
701     write32(Loc, (read32(Loc) & ~Mask) | (Val & Mask));
702     break;
703   }
704   case R_PPC64_DTPREL64:
705     write64(Loc, Val - DynamicThreadPointerOffset);
706     break;
707   default:
708     error(getErrorLocation(Loc) + "unrecognized reloc " + Twine(Type));
709   }
710 }
711 
712 bool PPC64::needsThunk(RelExpr Expr, RelType Type, const InputFile *File,
713                        uint64_t BranchAddr, const Symbol &S) const {
714   // If a function is in the plt it needs to be called through
715   // a call stub.
716   return Type == R_PPC64_REL24 && S.isInPlt();
717 }
718 
719 RelExpr PPC64::adjustRelaxExpr(RelType Type, const uint8_t *Data,
720                                RelExpr Expr) const {
721   if (Expr == R_RELAX_TLS_GD_TO_IE)
722     return R_RELAX_TLS_GD_TO_IE_GOT_OFF;
723   if (Expr == R_RELAX_TLS_LD_TO_LE)
724     return R_RELAX_TLS_LD_TO_LE_ABS;
725   return Expr;
726 }
727 
728 // Reference: 3.7.4.1 of the 64-bit ELF V2 abi supplement.
729 // The general dynamic code sequence for a global `x` uses 4 instructions.
730 // Instruction                    Relocation                Symbol
731 // addis r3, r2, x@got@tlsgd@ha   R_PPC64_GOT_TLSGD16_HA      x
732 // addi  r3, r3, x@got@tlsgd@l    R_PPC64_GOT_TLSGD16_LO      x
733 // bl __tls_get_addr(x@tlsgd)     R_PPC64_TLSGD               x
734 //                                R_PPC64_REL24               __tls_get_addr
735 // nop                            None                       None
736 //
737 // Relaxing to initial-exec entails:
738 // 1) Convert the addis/addi pair that builds the address of the tls_index
739 //    struct for 'x' to an addis/ld pair that loads an offset from a got-entry.
740 // 2) Convert the call to __tls_get_addr to a nop.
741 // 3) Convert the nop following the call to an add of the loaded offset to the
742 //    thread pointer.
743 // Since the nop must directly follow the call, the R_PPC64_TLSGD relocation is
744 // used as the relaxation hint for both steps 2 and 3.
745 void PPC64::relaxTlsGdToIe(uint8_t *Loc, RelType Type, uint64_t Val) const {
746   switch (Type) {
747   case R_PPC64_GOT_TLSGD16_HA:
748     // This is relaxed from addis rT, r2, sym@got@tlsgd@ha to
749     //                      addis rT, r2, sym@got@tprel@ha.
750     relocateOne(Loc, R_PPC64_GOT_TPREL16_HA, Val);
751     return;
752   case R_PPC64_GOT_TLSGD16_LO: {
753     // Relax from addi  r3, rA, sym@got@tlsgd@l to
754     //            ld r3, sym@got@tprel@l(rA)
755     uint32_t InputRegister = (readInstrFromHalf16(Loc) & (0x1f << 16));
756     writeInstrFromHalf16(Loc, 0xE8600000 | InputRegister);
757     relocateOne(Loc, R_PPC64_GOT_TPREL16_LO_DS, Val);
758     return;
759   }
760   case R_PPC64_TLSGD:
761     write32(Loc, 0x60000000);     // bl __tls_get_addr(sym@tlsgd) --> nop
762     write32(Loc + 4, 0x7c636A14); // nop --> add r3, r3, r13
763     return;
764   default:
765     llvm_unreachable("unsupported relocation for TLS GD to IE relaxation");
766   }
767 }
768 
769 // The prologue for a split-stack function is expected to look roughly
770 // like this:
771 //    .Lglobal_entry_point:
772 //      # TOC pointer initalization.
773 //      ...
774 //    .Llocal_entry_point:
775 //      # load the __private_ss member of the threads tcbhead.
776 //      ld r0,-0x7000-64(r13)
777 //      # subtract the functions stack size from the stack pointer.
778 //      addis r12, r1, ha(-stack-frame size)
779 //      addi  r12, r12, l(-stack-frame size)
780 //      # compare needed to actual and branch to allocate_more_stack if more
781 //      # space is needed, otherwise fallthrough to 'normal' function body.
782 //      cmpld cr7,r12,r0
783 //      blt- cr7, .Lallocate_more_stack
784 //
785 // -) The allocate_more_stack block might be placed after the split-stack
786 //    prologue and the `blt-` replaced with a `bge+ .Lnormal_func_body`
787 //    instead.
788 // -) If either the addis or addi is not needed due to the stack size being
789 //    smaller then 32K or a multiple of 64K they will be replaced with a nop,
790 //    but there will always be 2 instructions the linker can overwrite for the
791 //    adjusted stack size.
792 //
793 // The linkers job here is to increase the stack size used in the addis/addi
794 // pair by split-stack-size-adjust.
795 // addis r12, r1, ha(-stack-frame size - split-stack-adjust-size)
796 // addi  r12, r12, l(-stack-frame size - split-stack-adjust-size)
797 bool PPC64::adjustPrologueForCrossSplitStack(uint8_t *Loc, uint8_t *End,
798                                              uint8_t StOther) const {
799   // If the caller has a global entry point adjust the buffer past it. The start
800   // of the split-stack prologue will be at the local entry point.
801   Loc += getPPC64GlobalEntryToLocalEntryOffset(StOther);
802 
803   // At the very least we expect to see a load of some split-stack data from the
804   // tcb, and 2 instructions that calculate the ending stack address this
805   // function will require. If there is not enough room for at least 3
806   // instructions it can't be a split-stack prologue.
807   if (Loc + 12 >= End)
808     return false;
809 
810   // First instruction must be `ld r0, -0x7000-64(r13)`
811   if (read32(Loc) != 0xe80d8fc0)
812     return false;
813 
814   int16_t HiImm = 0;
815   int16_t LoImm = 0;
816   // First instruction can be either an addis if the frame size is larger then
817   // 32K, or an addi if the size is less then 32K.
818   int32_t FirstInstr = read32(Loc + 4);
819   if (getPrimaryOpCode(FirstInstr) == 15) {
820     HiImm = FirstInstr & 0xFFFF;
821   } else if (getPrimaryOpCode(FirstInstr) == 14) {
822     LoImm = FirstInstr & 0xFFFF;
823   } else {
824     return false;
825   }
826 
827   // Second instruction is either an addi or a nop. If the first instruction was
828   // an addi then LoImm is set and the second instruction must be a nop.
829   uint32_t SecondInstr = read32(Loc + 8);
830   if (!LoImm && getPrimaryOpCode(SecondInstr) == 14) {
831     LoImm = SecondInstr & 0xFFFF;
832   } else if (SecondInstr != 0x60000000) {
833     return false;
834   }
835 
836   // The register operands of the first instruction should be the stack-pointer
837   // (r1) as the input (RA) and r12 as the output (RT). If the second
838   // instruction is not a nop, then it should use r12 as both input and output.
839   auto CheckRegOperands = [](uint32_t Instr, uint8_t ExpectedRT,
840                              uint8_t ExpectedRA) {
841     return ((Instr & 0x3E00000) >> 21 == ExpectedRT) &&
842            ((Instr & 0x1F0000) >> 16 == ExpectedRA);
843   };
844   if (!CheckRegOperands(FirstInstr, 12, 1))
845     return false;
846   if (SecondInstr != 0x60000000 && !CheckRegOperands(SecondInstr, 12, 12))
847     return false;
848 
849   int32_t StackFrameSize = (HiImm * 65536) + LoImm;
850   // Check that the adjusted size doesn't overflow what we can represent with 2
851   // instructions.
852   if (StackFrameSize <
853       std::numeric_limits<int32_t>::min() + Config->SplitStackAdjustSize) {
854     error(getErrorLocation(Loc) + "split-stack prologue adjustment overflows");
855     return false;
856   }
857 
858   int32_t AdjustedStackFrameSize =
859       StackFrameSize - Config->SplitStackAdjustSize;
860 
861   LoImm = AdjustedStackFrameSize & 0xFFFF;
862   HiImm = (AdjustedStackFrameSize + 0x8000) >> 16;
863   if (HiImm) {
864     write32(Loc + 4, 0x3D810000 | (uint16_t)HiImm);
865     // If the low immediate is zero the second instruction will be a nop.
866     SecondInstr = LoImm ? 0x398C0000 | (uint16_t)LoImm : 0x60000000;
867     write32(Loc + 8, SecondInstr);
868   } else {
869     // addi r12, r1, imm
870     write32(Loc + 4, (0x39810000) | (uint16_t)LoImm);
871     write32(Loc + 8, 0x60000000);
872   }
873 
874   return true;
875 }
876 
877 TargetInfo *elf::getPPC64TargetInfo() {
878   static PPC64 Target;
879   return &Target;
880 }
881