xref: /llvm-project-15.0.7/lld/ELF/Target.cpp (revision 3e254a6e)
1 //===- Target.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 // Machine-specific things, such as applying relocations, creation of
11 // GOT or PLT entries, etc., are handled in this file.
12 //
13 // Refer the ELF spec for the single letter variables, S, A or P, used
14 // in this file.
15 //
16 // Some functions defined in this file has "relaxTls" as part of their names.
17 // They do peephole optimization for TLS variables by rewriting instructions.
18 // They are not part of the ABI but optional optimization, so you can skip
19 // them if you are not interested in how TLS variables are optimized.
20 // See the following paper for the details.
21 //
22 //   Ulrich Drepper, ELF Handling For Thread-Local Storage
23 //   http://www.akkadia.org/drepper/tls.pdf
24 //
25 //===----------------------------------------------------------------------===//
26 
27 #include "Target.h"
28 #include "Error.h"
29 #include "InputFiles.h"
30 #include "Memory.h"
31 #include "OutputSections.h"
32 #include "SymbolTable.h"
33 #include "Symbols.h"
34 #include "SyntheticSections.h"
35 #include "Thunks.h"
36 #include "Writer.h"
37 #include "llvm/ADT/ArrayRef.h"
38 #include "llvm/Object/ELF.h"
39 #include "llvm/Support/ELF.h"
40 #include "llvm/Support/Endian.h"
41 
42 using namespace llvm;
43 using namespace llvm::object;
44 using namespace llvm::support::endian;
45 using namespace llvm::ELF;
46 
47 std::string lld::toString(uint32_t Type) {
48   StringRef S = getELFRelocationTypeName(elf::Config->EMachine, Type);
49   if (S == "Unknown")
50     return ("Unknown (" + Twine(Type) + ")").str();
51   return S;
52 }
53 
54 namespace lld {
55 namespace elf {
56 
57 TargetInfo *Target;
58 
59 static void or32le(uint8_t *P, int32_t V) { write32le(P, read32le(P) | V); }
60 static void or32be(uint8_t *P, int32_t V) { write32be(P, read32be(P) | V); }
61 
62 template <class ELFT> static std::string getErrorLoc(const uint8_t *Loc) {
63   for (InputSectionBase *D : InputSections) {
64     auto *IS = dyn_cast_or_null<InputSection>(D);
65     if (!IS || !IS->OutSec)
66       continue;
67 
68     uint8_t *ISLoc = cast<OutputSection>(IS->OutSec)->Loc + IS->OutSecOff;
69     if (ISLoc <= Loc && Loc < ISLoc + IS->getSize())
70       return IS->template getLocation<ELFT>(Loc - ISLoc) + ": ";
71   }
72   return "";
73 }
74 
75 static std::string getErrorLocation(const uint8_t *Loc) {
76   switch (Config->EKind) {
77   case ELF32LEKind:
78     return getErrorLoc<ELF32LE>(Loc);
79   case ELF32BEKind:
80     return getErrorLoc<ELF32BE>(Loc);
81   case ELF64LEKind:
82     return getErrorLoc<ELF64LE>(Loc);
83   case ELF64BEKind:
84     return getErrorLoc<ELF64BE>(Loc);
85   default:
86     llvm_unreachable("unknown ELF type");
87   }
88 }
89 
90 template <unsigned N>
91 static void checkInt(uint8_t *Loc, int64_t V, uint32_t Type) {
92   if (!isInt<N>(V))
93     error(getErrorLocation(Loc) + "relocation " + toString(Type) +
94           " out of range");
95 }
96 
97 template <unsigned N>
98 static void checkUInt(uint8_t *Loc, uint64_t V, uint32_t Type) {
99   if (!isUInt<N>(V))
100     error(getErrorLocation(Loc) + "relocation " + toString(Type) +
101           " out of range");
102 }
103 
104 template <unsigned N>
105 static void checkIntUInt(uint8_t *Loc, uint64_t V, uint32_t Type) {
106   if (!isInt<N>(V) && !isUInt<N>(V))
107     error(getErrorLocation(Loc) + "relocation " + toString(Type) +
108           " out of range");
109 }
110 
111 template <unsigned N>
112 static void checkAlignment(uint8_t *Loc, uint64_t V, uint32_t Type) {
113   if ((V & (N - 1)) != 0)
114     error(getErrorLocation(Loc) + "improper alignment for relocation " +
115           toString(Type));
116 }
117 
118 namespace {
119 class X86TargetInfo final : public TargetInfo {
120 public:
121   X86TargetInfo();
122   RelExpr getRelExpr(uint32_t Type, const SymbolBody &S,
123                      const uint8_t *Loc) const override;
124   int64_t getImplicitAddend(const uint8_t *Buf, uint32_t Type) const override;
125   void writeGotPltHeader(uint8_t *Buf) const override;
126   uint32_t getDynRel(uint32_t Type) const override;
127   void writeGotPlt(uint8_t *Buf, const SymbolBody &S) const override;
128   void writeIgotPlt(uint8_t *Buf, const SymbolBody &S) const override;
129   void writePltHeader(uint8_t *Buf) const override;
130   void writePlt(uint8_t *Buf, uint64_t GotPltEntryAddr, uint64_t PltEntryAddr,
131                 int32_t Index, unsigned RelOff) const override;
132   void relocateOne(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
133 
134   RelExpr adjustRelaxExpr(uint32_t Type, const uint8_t *Data,
135                           RelExpr Expr) const override;
136   void relaxTlsGdToIe(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
137   void relaxTlsGdToLe(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
138   void relaxTlsIeToLe(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
139   void relaxTlsLdToLe(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
140 };
141 
142 template <class ELFT> class X86_64TargetInfo final : public TargetInfo {
143 public:
144   X86_64TargetInfo();
145   RelExpr getRelExpr(uint32_t Type, const SymbolBody &S,
146                      const uint8_t *Loc) const override;
147   bool isPicRel(uint32_t Type) const override;
148   void writeGotPltHeader(uint8_t *Buf) const override;
149   void writeGotPlt(uint8_t *Buf, const SymbolBody &S) const override;
150   void writePltHeader(uint8_t *Buf) const override;
151   void writePlt(uint8_t *Buf, uint64_t GotPltEntryAddr, uint64_t PltEntryAddr,
152                 int32_t Index, unsigned RelOff) const override;
153   void relocateOne(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
154 
155   RelExpr adjustRelaxExpr(uint32_t Type, const uint8_t *Data,
156                           RelExpr Expr) const override;
157   void relaxGot(uint8_t *Loc, uint64_t Val) const override;
158   void relaxTlsGdToIe(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
159   void relaxTlsGdToLe(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
160   void relaxTlsIeToLe(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
161   void relaxTlsLdToLe(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
162 
163 private:
164   void relaxGotNoPic(uint8_t *Loc, uint64_t Val, uint8_t Op,
165                      uint8_t ModRm) const;
166 };
167 
168 class PPCTargetInfo final : public TargetInfo {
169 public:
170   PPCTargetInfo();
171   void relocateOne(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
172   RelExpr getRelExpr(uint32_t Type, const SymbolBody &S,
173                      const uint8_t *Loc) const override;
174 };
175 
176 class PPC64TargetInfo final : public TargetInfo {
177 public:
178   PPC64TargetInfo();
179   RelExpr getRelExpr(uint32_t Type, const SymbolBody &S,
180                      const uint8_t *Loc) const override;
181   void writePlt(uint8_t *Buf, uint64_t GotPltEntryAddr, uint64_t PltEntryAddr,
182                 int32_t Index, unsigned RelOff) const override;
183   void relocateOne(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
184 };
185 
186 class AArch64TargetInfo final : public TargetInfo {
187 public:
188   AArch64TargetInfo();
189   RelExpr getRelExpr(uint32_t Type, const SymbolBody &S,
190                      const uint8_t *Loc) const override;
191   bool isPicRel(uint32_t Type) const override;
192   void writeGotPlt(uint8_t *Buf, const SymbolBody &S) const override;
193   void writePltHeader(uint8_t *Buf) const override;
194   void writePlt(uint8_t *Buf, uint64_t GotPltEntryAddr, uint64_t PltEntryAddr,
195                 int32_t Index, unsigned RelOff) const override;
196   bool usesOnlyLowPageBits(uint32_t Type) const override;
197   void relocateOne(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
198   RelExpr adjustRelaxExpr(uint32_t Type, const uint8_t *Data,
199                           RelExpr Expr) const override;
200   void relaxTlsGdToLe(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
201   void relaxTlsGdToIe(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
202   void relaxTlsIeToLe(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
203 };
204 
205 class AMDGPUTargetInfo final : public TargetInfo {
206 public:
207   AMDGPUTargetInfo();
208   void relocateOne(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
209   RelExpr getRelExpr(uint32_t Type, const SymbolBody &S,
210                      const uint8_t *Loc) const override;
211 };
212 
213 class ARMTargetInfo final : public TargetInfo {
214 public:
215   ARMTargetInfo();
216   RelExpr getRelExpr(uint32_t Type, const SymbolBody &S,
217                      const uint8_t *Loc) const override;
218   bool isPicRel(uint32_t Type) const override;
219   uint32_t getDynRel(uint32_t Type) const override;
220   int64_t getImplicitAddend(const uint8_t *Buf, uint32_t Type) const override;
221   void writeGotPlt(uint8_t *Buf, const SymbolBody &S) const override;
222   void writeIgotPlt(uint8_t *Buf, const SymbolBody &S) const override;
223   void writePltHeader(uint8_t *Buf) const override;
224   void writePlt(uint8_t *Buf, uint64_t GotPltEntryAddr, uint64_t PltEntryAddr,
225                 int32_t Index, unsigned RelOff) const override;
226   void addPltSymbols(InputSectionBase *IS, uint64_t Off) const override;
227   void addPltHeaderSymbols(InputSectionBase *ISD) const override;
228   bool needsThunk(RelExpr Expr, uint32_t RelocType, const InputFile *File,
229                   const SymbolBody &S) const override;
230   void relocateOne(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
231 };
232 
233 template <class ELFT> class MipsTargetInfo final : public TargetInfo {
234 public:
235   MipsTargetInfo();
236   RelExpr getRelExpr(uint32_t Type, const SymbolBody &S,
237                      const uint8_t *Loc) const override;
238   int64_t getImplicitAddend(const uint8_t *Buf, uint32_t Type) const override;
239   bool isPicRel(uint32_t Type) const override;
240   uint32_t getDynRel(uint32_t Type) const override;
241   void writeGotPlt(uint8_t *Buf, const SymbolBody &S) const override;
242   void writePltHeader(uint8_t *Buf) const override;
243   void writePlt(uint8_t *Buf, uint64_t GotPltEntryAddr, uint64_t PltEntryAddr,
244                 int32_t Index, unsigned RelOff) const override;
245   bool needsThunk(RelExpr Expr, uint32_t RelocType, const InputFile *File,
246                   const SymbolBody &S) const override;
247   void relocateOne(uint8_t *Loc, uint32_t Type, uint64_t Val) const override;
248   bool usesOnlyLowPageBits(uint32_t Type) const override;
249 };
250 } // anonymous namespace
251 
252 TargetInfo *createTarget() {
253   switch (Config->EMachine) {
254   case EM_386:
255   case EM_IAMCU:
256     return make<X86TargetInfo>();
257   case EM_AARCH64:
258     return make<AArch64TargetInfo>();
259   case EM_AMDGPU:
260     return make<AMDGPUTargetInfo>();
261   case EM_ARM:
262     return make<ARMTargetInfo>();
263   case EM_MIPS:
264     switch (Config->EKind) {
265     case ELF32LEKind:
266       return make<MipsTargetInfo<ELF32LE>>();
267     case ELF32BEKind:
268       return make<MipsTargetInfo<ELF32BE>>();
269     case ELF64LEKind:
270       return make<MipsTargetInfo<ELF64LE>>();
271     case ELF64BEKind:
272       return make<MipsTargetInfo<ELF64BE>>();
273     default:
274       fatal("unsupported MIPS target");
275     }
276   case EM_PPC:
277     return make<PPCTargetInfo>();
278   case EM_PPC64:
279     return make<PPC64TargetInfo>();
280   case EM_X86_64:
281     if (Config->EKind == ELF32LEKind)
282       return make<X86_64TargetInfo<ELF32LE>>();
283     return make<X86_64TargetInfo<ELF64LE>>();
284   }
285   fatal("unknown target machine");
286 }
287 
288 TargetInfo::~TargetInfo() {}
289 
290 int64_t TargetInfo::getImplicitAddend(const uint8_t *Buf, uint32_t Type) const {
291   return 0;
292 }
293 
294 bool TargetInfo::usesOnlyLowPageBits(uint32_t Type) const { return false; }
295 
296 bool TargetInfo::needsThunk(RelExpr Expr, uint32_t RelocType,
297                             const InputFile *File, const SymbolBody &S) const {
298   return false;
299 }
300 
301 void TargetInfo::writeIgotPlt(uint8_t *Buf, const SymbolBody &S) const {
302   writeGotPlt(Buf, S);
303 }
304 
305 RelExpr TargetInfo::adjustRelaxExpr(uint32_t Type, const uint8_t *Data,
306                                     RelExpr Expr) const {
307   return Expr;
308 }
309 
310 void TargetInfo::relaxGot(uint8_t *Loc, uint64_t Val) const {
311   llvm_unreachable("Should not have claimed to be relaxable");
312 }
313 
314 void TargetInfo::relaxTlsGdToLe(uint8_t *Loc, uint32_t Type,
315                                 uint64_t Val) const {
316   llvm_unreachable("Should not have claimed to be relaxable");
317 }
318 
319 void TargetInfo::relaxTlsGdToIe(uint8_t *Loc, uint32_t Type,
320                                 uint64_t Val) const {
321   llvm_unreachable("Should not have claimed to be relaxable");
322 }
323 
324 void TargetInfo::relaxTlsIeToLe(uint8_t *Loc, uint32_t Type,
325                                 uint64_t Val) const {
326   llvm_unreachable("Should not have claimed to be relaxable");
327 }
328 
329 void TargetInfo::relaxTlsLdToLe(uint8_t *Loc, uint32_t Type,
330                                 uint64_t Val) const {
331   llvm_unreachable("Should not have claimed to be relaxable");
332 }
333 
334 X86TargetInfo::X86TargetInfo() {
335   CopyRel = R_386_COPY;
336   GotRel = R_386_GLOB_DAT;
337   PltRel = R_386_JUMP_SLOT;
338   IRelativeRel = R_386_IRELATIVE;
339   RelativeRel = R_386_RELATIVE;
340   TlsGotRel = R_386_TLS_TPOFF;
341   TlsModuleIndexRel = R_386_TLS_DTPMOD32;
342   TlsOffsetRel = R_386_TLS_DTPOFF32;
343   GotEntrySize = 4;
344   GotPltEntrySize = 4;
345   PltEntrySize = 16;
346   PltHeaderSize = 16;
347   TlsGdRelaxSkip = 2;
348   // 0xCC is the "int3" (call debug exception handler) instruction.
349   TrapInstr = 0xcccccccc;
350 }
351 
352 RelExpr X86TargetInfo::getRelExpr(uint32_t Type, const SymbolBody &S,
353                                   const uint8_t *Loc) const {
354   switch (Type) {
355   case R_386_8:
356   case R_386_16:
357   case R_386_32:
358   case R_386_TLS_LDO_32:
359     return R_ABS;
360   case R_386_TLS_GD:
361     return R_TLSGD;
362   case R_386_TLS_LDM:
363     return R_TLSLD;
364   case R_386_PLT32:
365     return R_PLT_PC;
366   case R_386_PC8:
367   case R_386_PC16:
368   case R_386_PC32:
369     return R_PC;
370   case R_386_GOTPC:
371     return R_GOTONLY_PC_FROM_END;
372   case R_386_TLS_IE:
373     return R_GOT;
374   case R_386_GOT32:
375   case R_386_GOT32X:
376     // These relocations can be calculated in two different ways.
377     // Usual calculation is G + A - GOT what means an offset in GOT table
378     // (R_GOT_FROM_END). When instruction pointed by relocation has no base
379     // register, then relocations can be used when PIC code is disabled. In that
380     // case calculation is G + A, it resolves to an address of entry in GOT
381     // (R_GOT) and not an offset.
382     //
383     // To check that instruction has no base register we scan ModR/M byte.
384     // See "Table 2-2. 32-Bit Addressing Forms with the ModR/M Byte"
385     // (http://www.intel.com/content/dam/www/public/us/en/documents/manuals/
386     //  64-ia-32-architectures-software-developer-instruction-set-reference-manual-325383.pdf)
387     if ((Loc[-1] & 0xc7) != 0x5)
388       return R_GOT_FROM_END;
389     if (Config->Pic)
390       error(toString(S.File) + ": relocation " + toString(Type) + " against '" +
391             S.getName() +
392             "' without base register can not be used when PIC enabled");
393     return R_GOT;
394   case R_386_TLS_GOTIE:
395     return R_GOT_FROM_END;
396   case R_386_GOTOFF:
397     return R_GOTREL_FROM_END;
398   case R_386_TLS_LE:
399     return R_TLS;
400   case R_386_TLS_LE_32:
401     return R_NEG_TLS;
402   case R_386_NONE:
403     return R_NONE;
404   default:
405     error(toString(S.File) + ": unknown relocation type: " + toString(Type));
406     return R_HINT;
407   }
408 }
409 
410 RelExpr X86TargetInfo::adjustRelaxExpr(uint32_t Type, const uint8_t *Data,
411                                        RelExpr Expr) const {
412   switch (Expr) {
413   default:
414     return Expr;
415   case R_RELAX_TLS_GD_TO_IE:
416     return R_RELAX_TLS_GD_TO_IE_END;
417   case R_RELAX_TLS_GD_TO_LE:
418     return R_RELAX_TLS_GD_TO_LE_NEG;
419   }
420 }
421 
422 void X86TargetInfo::writeGotPltHeader(uint8_t *Buf) const {
423   write32le(Buf, In<ELF32LE>::Dynamic->getVA());
424 }
425 
426 void X86TargetInfo::writeGotPlt(uint8_t *Buf, const SymbolBody &S) const {
427   // Entries in .got.plt initially points back to the corresponding
428   // PLT entries with a fixed offset to skip the first instruction.
429   write32le(Buf, S.getPltVA() + 6);
430 }
431 
432 void X86TargetInfo::writeIgotPlt(uint8_t *Buf, const SymbolBody &S) const {
433   // An x86 entry is the address of the ifunc resolver function.
434   write32le(Buf, S.getVA());
435 }
436 
437 uint32_t X86TargetInfo::getDynRel(uint32_t Type) const {
438   if (Type == R_386_TLS_LE)
439     return R_386_TLS_TPOFF;
440   if (Type == R_386_TLS_LE_32)
441     return R_386_TLS_TPOFF32;
442   return Type;
443 }
444 
445 void X86TargetInfo::writePltHeader(uint8_t *Buf) const {
446   if (Config->Pic) {
447     const uint8_t V[] = {
448         0xff, 0xb3, 0x04, 0x00, 0x00, 0x00, // pushl GOTPLT+4(%ebx)
449         0xff, 0xa3, 0x08, 0x00, 0x00, 0x00, // jmp *GOTPLT+8(%ebx)
450         0x90, 0x90, 0x90, 0x90              // nop
451     };
452     memcpy(Buf, V, sizeof(V));
453 
454     uint32_t Ebx = In<ELF32LE>::Got->getVA() + In<ELF32LE>::Got->getSize();
455     uint32_t GotPlt = In<ELF32LE>::GotPlt->getVA() - Ebx;
456     write32le(Buf + 2, GotPlt + 4);
457     write32le(Buf + 8, GotPlt + 8);
458     return;
459   }
460 
461   const uint8_t PltData[] = {
462       0xff, 0x35, 0x00, 0x00, 0x00, 0x00, // pushl (GOTPLT+4)
463       0xff, 0x25, 0x00, 0x00, 0x00, 0x00, // jmp *(GOTPLT+8)
464       0x90, 0x90, 0x90, 0x90              // nop
465   };
466   memcpy(Buf, PltData, sizeof(PltData));
467   uint32_t GotPlt = In<ELF32LE>::GotPlt->getVA();
468   write32le(Buf + 2, GotPlt + 4);
469   write32le(Buf + 8, GotPlt + 8);
470 }
471 
472 void X86TargetInfo::writePlt(uint8_t *Buf, uint64_t GotPltEntryAddr,
473                              uint64_t PltEntryAddr, int32_t Index,
474                              unsigned RelOff) const {
475   const uint8_t Inst[] = {
476       0xff, 0x00, 0x00, 0x00, 0x00, 0x00, // jmp *foo_in_GOT|*foo@GOT(%ebx)
477       0x68, 0x00, 0x00, 0x00, 0x00,       // pushl $reloc_offset
478       0xe9, 0x00, 0x00, 0x00, 0x00        // jmp .PLT0@PC
479   };
480   memcpy(Buf, Inst, sizeof(Inst));
481 
482   if (Config->Pic) {
483     // jmp *foo@GOT(%ebx)
484     uint32_t Ebx = In<ELF32LE>::Got->getVA() + In<ELF32LE>::Got->getSize();
485     Buf[1] = 0xa3;
486     write32le(Buf + 2, GotPltEntryAddr - Ebx);
487   } else {
488     // jmp *foo_in_GOT
489     Buf[1] = 0x25;
490     write32le(Buf + 2, GotPltEntryAddr);
491   }
492 
493   write32le(Buf + 7, RelOff);
494   write32le(Buf + 12, -Index * PltEntrySize - PltHeaderSize - 16);
495 }
496 
497 int64_t X86TargetInfo::getImplicitAddend(const uint8_t *Buf,
498                                          uint32_t Type) const {
499   switch (Type) {
500   default:
501     return 0;
502   case R_386_8:
503   case R_386_PC8:
504     return SignExtend64<8>(*Buf);
505   case R_386_16:
506   case R_386_PC16:
507     return SignExtend64<16>(read16le(Buf));
508   case R_386_32:
509   case R_386_GOT32:
510   case R_386_GOT32X:
511   case R_386_GOTOFF:
512   case R_386_GOTPC:
513   case R_386_PC32:
514   case R_386_PLT32:
515   case R_386_TLS_LDO_32:
516   case R_386_TLS_LE:
517     return SignExtend64<32>(read32le(Buf));
518   }
519 }
520 
521 void X86TargetInfo::relocateOne(uint8_t *Loc, uint32_t Type,
522                                 uint64_t Val) const {
523   // R_386_{PC,}{8,16} are not part of the i386 psABI, but they are
524   // being used for some 16-bit programs such as boot loaders, so
525   // we want to support them.
526   switch (Type) {
527   case R_386_8:
528     checkUInt<8>(Loc, Val, Type);
529     *Loc = Val;
530     break;
531   case R_386_PC8:
532     checkInt<8>(Loc, Val, Type);
533     *Loc = Val;
534     break;
535   case R_386_16:
536     checkUInt<16>(Loc, Val, Type);
537     write16le(Loc, Val);
538     break;
539   case R_386_PC16:
540     checkInt<16>(Loc, Val, Type);
541     write16le(Loc, Val);
542     break;
543   default:
544     checkInt<32>(Loc, Val, Type);
545     write32le(Loc, Val);
546   }
547 }
548 
549 void X86TargetInfo::relaxTlsGdToLe(uint8_t *Loc, uint32_t Type,
550                                    uint64_t Val) const {
551   // Convert
552   //   leal x@tlsgd(, %ebx, 1),
553   //   call __tls_get_addr@plt
554   // to
555   //   movl %gs:0,%eax
556   //   subl $x@ntpoff,%eax
557   const uint8_t Inst[] = {
558       0x65, 0xa1, 0x00, 0x00, 0x00, 0x00, // movl %gs:0, %eax
559       0x81, 0xe8, 0x00, 0x00, 0x00, 0x00  // subl 0(%ebx), %eax
560   };
561   memcpy(Loc - 3, Inst, sizeof(Inst));
562   write32le(Loc + 5, Val);
563 }
564 
565 void X86TargetInfo::relaxTlsGdToIe(uint8_t *Loc, uint32_t Type,
566                                    uint64_t Val) const {
567   // Convert
568   //   leal x@tlsgd(, %ebx, 1),
569   //   call __tls_get_addr@plt
570   // to
571   //   movl %gs:0, %eax
572   //   addl x@gotntpoff(%ebx), %eax
573   const uint8_t Inst[] = {
574       0x65, 0xa1, 0x00, 0x00, 0x00, 0x00, // movl %gs:0, %eax
575       0x03, 0x83, 0x00, 0x00, 0x00, 0x00  // addl 0(%ebx), %eax
576   };
577   memcpy(Loc - 3, Inst, sizeof(Inst));
578   write32le(Loc + 5, Val);
579 }
580 
581 // In some conditions, relocations can be optimized to avoid using GOT.
582 // This function does that for Initial Exec to Local Exec case.
583 void X86TargetInfo::relaxTlsIeToLe(uint8_t *Loc, uint32_t Type,
584                                    uint64_t Val) const {
585   // Ulrich's document section 6.2 says that @gotntpoff can
586   // be used with MOVL or ADDL instructions.
587   // @indntpoff is similar to @gotntpoff, but for use in
588   // position dependent code.
589   uint8_t Reg = (Loc[-1] >> 3) & 7;
590 
591   if (Type == R_386_TLS_IE) {
592     if (Loc[-1] == 0xa1) {
593       // "movl foo@indntpoff,%eax" -> "movl $foo,%eax"
594       // This case is different from the generic case below because
595       // this is a 5 byte instruction while below is 6 bytes.
596       Loc[-1] = 0xb8;
597     } else if (Loc[-2] == 0x8b) {
598       // "movl foo@indntpoff,%reg" -> "movl $foo,%reg"
599       Loc[-2] = 0xc7;
600       Loc[-1] = 0xc0 | Reg;
601     } else {
602       // "addl foo@indntpoff,%reg" -> "addl $foo,%reg"
603       Loc[-2] = 0x81;
604       Loc[-1] = 0xc0 | Reg;
605     }
606   } else {
607     assert(Type == R_386_TLS_GOTIE);
608     if (Loc[-2] == 0x8b) {
609       // "movl foo@gottpoff(%rip),%reg" -> "movl $foo,%reg"
610       Loc[-2] = 0xc7;
611       Loc[-1] = 0xc0 | Reg;
612     } else {
613       // "addl foo@gotntpoff(%rip),%reg" -> "leal foo(%reg),%reg"
614       Loc[-2] = 0x8d;
615       Loc[-1] = 0x80 | (Reg << 3) | Reg;
616     }
617   }
618   write32le(Loc, Val);
619 }
620 
621 void X86TargetInfo::relaxTlsLdToLe(uint8_t *Loc, uint32_t Type,
622                                    uint64_t Val) const {
623   if (Type == R_386_TLS_LDO_32) {
624     write32le(Loc, Val);
625     return;
626   }
627 
628   // Convert
629   //   leal foo(%reg),%eax
630   //   call ___tls_get_addr
631   // to
632   //   movl %gs:0,%eax
633   //   nop
634   //   leal 0(%esi,1),%esi
635   const uint8_t Inst[] = {
636       0x65, 0xa1, 0x00, 0x00, 0x00, 0x00, // movl %gs:0,%eax
637       0x90,                               // nop
638       0x8d, 0x74, 0x26, 0x00              // leal 0(%esi,1),%esi
639   };
640   memcpy(Loc - 2, Inst, sizeof(Inst));
641 }
642 
643 template <class ELFT> X86_64TargetInfo<ELFT>::X86_64TargetInfo() {
644   CopyRel = R_X86_64_COPY;
645   GotRel = R_X86_64_GLOB_DAT;
646   PltRel = R_X86_64_JUMP_SLOT;
647   RelativeRel = R_X86_64_RELATIVE;
648   IRelativeRel = R_X86_64_IRELATIVE;
649   TlsGotRel = R_X86_64_TPOFF64;
650   TlsModuleIndexRel = R_X86_64_DTPMOD64;
651   TlsOffsetRel = R_X86_64_DTPOFF64;
652   GotEntrySize = 8;
653   GotPltEntrySize = 8;
654   PltEntrySize = 16;
655   PltHeaderSize = 16;
656   TlsGdRelaxSkip = 2;
657   // Align to the large page size (known as a superpage or huge page).
658   // FreeBSD automatically promotes large, superpage-aligned allocations.
659   DefaultImageBase = 0x200000;
660   // 0xCC is the "int3" (call debug exception handler) instruction.
661   TrapInstr = 0xcccccccc;
662 }
663 
664 template <class ELFT>
665 RelExpr X86_64TargetInfo<ELFT>::getRelExpr(uint32_t Type, const SymbolBody &S,
666                                            const uint8_t *Loc) const {
667   switch (Type) {
668   case R_X86_64_8:
669   case R_X86_64_16:
670   case R_X86_64_32:
671   case R_X86_64_32S:
672   case R_X86_64_64:
673   case R_X86_64_DTPOFF32:
674   case R_X86_64_DTPOFF64:
675     return R_ABS;
676   case R_X86_64_TPOFF32:
677     return R_TLS;
678   case R_X86_64_TLSLD:
679     return R_TLSLD_PC;
680   case R_X86_64_TLSGD:
681     return R_TLSGD_PC;
682   case R_X86_64_SIZE32:
683   case R_X86_64_SIZE64:
684     return R_SIZE;
685   case R_X86_64_PLT32:
686     return R_PLT_PC;
687   case R_X86_64_PC32:
688   case R_X86_64_PC64:
689     return R_PC;
690   case R_X86_64_GOT32:
691   case R_X86_64_GOT64:
692     return R_GOT_FROM_END;
693   case R_X86_64_GOTPCREL:
694   case R_X86_64_GOTPCRELX:
695   case R_X86_64_REX_GOTPCRELX:
696   case R_X86_64_GOTTPOFF:
697     return R_GOT_PC;
698   case R_X86_64_NONE:
699     return R_NONE;
700   default:
701     error(toString(S.File) + ": unknown relocation type: " + toString(Type));
702     return R_HINT;
703   }
704 }
705 
706 template <class ELFT>
707 void X86_64TargetInfo<ELFT>::writeGotPltHeader(uint8_t *Buf) const {
708   // The first entry holds the value of _DYNAMIC. It is not clear why that is
709   // required, but it is documented in the psabi and the glibc dynamic linker
710   // seems to use it (note that this is relevant for linking ld.so, not any
711   // other program).
712   write64le(Buf, In<ELFT>::Dynamic->getVA());
713 }
714 
715 template <class ELFT>
716 void X86_64TargetInfo<ELFT>::writeGotPlt(uint8_t *Buf,
717                                          const SymbolBody &S) const {
718   // See comments in X86TargetInfo::writeGotPlt.
719   write32le(Buf, S.getPltVA() + 6);
720 }
721 
722 template <class ELFT>
723 void X86_64TargetInfo<ELFT>::writePltHeader(uint8_t *Buf) const {
724   const uint8_t PltData[] = {
725       0xff, 0x35, 0x00, 0x00, 0x00, 0x00, // pushq GOTPLT+8(%rip)
726       0xff, 0x25, 0x00, 0x00, 0x00, 0x00, // jmp *GOTPLT+16(%rip)
727       0x0f, 0x1f, 0x40, 0x00              // nop
728   };
729   memcpy(Buf, PltData, sizeof(PltData));
730   uint64_t GotPlt = In<ELFT>::GotPlt->getVA();
731   uint64_t Plt = In<ELFT>::Plt->getVA();
732   write32le(Buf + 2, GotPlt - Plt + 2); // GOTPLT+8
733   write32le(Buf + 8, GotPlt - Plt + 4); // GOTPLT+16
734 }
735 
736 template <class ELFT>
737 void X86_64TargetInfo<ELFT>::writePlt(uint8_t *Buf, uint64_t GotPltEntryAddr,
738                                       uint64_t PltEntryAddr, int32_t Index,
739                                       unsigned RelOff) const {
740   const uint8_t Inst[] = {
741       0xff, 0x25, 0x00, 0x00, 0x00, 0x00, // jmpq *got(%rip)
742       0x68, 0x00, 0x00, 0x00, 0x00,       // pushq <relocation index>
743       0xe9, 0x00, 0x00, 0x00, 0x00        // jmpq plt[0]
744   };
745   memcpy(Buf, Inst, sizeof(Inst));
746 
747   write32le(Buf + 2, GotPltEntryAddr - PltEntryAddr - 6);
748   write32le(Buf + 7, Index);
749   write32le(Buf + 12, -Index * PltEntrySize - PltHeaderSize - 16);
750 }
751 
752 template <class ELFT>
753 bool X86_64TargetInfo<ELFT>::isPicRel(uint32_t Type) const {
754   return Type != R_X86_64_PC32 && Type != R_X86_64_32;
755 }
756 
757 template <class ELFT>
758 void X86_64TargetInfo<ELFT>::relaxTlsGdToLe(uint8_t *Loc, uint32_t Type,
759                                             uint64_t Val) const {
760   // Convert
761   //   .byte 0x66
762   //   leaq x@tlsgd(%rip), %rdi
763   //   .word 0x6666
764   //   rex64
765   //   call __tls_get_addr@plt
766   // to
767   //   mov %fs:0x0,%rax
768   //   lea x@tpoff,%rax
769   const uint8_t Inst[] = {
770       0x64, 0x48, 0x8b, 0x04, 0x25, 0x00, 0x00, 0x00, 0x00, // mov %fs:0x0,%rax
771       0x48, 0x8d, 0x80, 0x00, 0x00, 0x00, 0x00              // lea x@tpoff,%rax
772   };
773   memcpy(Loc - 4, Inst, sizeof(Inst));
774 
775   // The original code used a pc relative relocation and so we have to
776   // compensate for the -4 in had in the addend.
777   write32le(Loc + 8, Val + 4);
778 }
779 
780 template <class ELFT>
781 void X86_64TargetInfo<ELFT>::relaxTlsGdToIe(uint8_t *Loc, uint32_t Type,
782                                             uint64_t Val) const {
783   // Convert
784   //   .byte 0x66
785   //   leaq x@tlsgd(%rip), %rdi
786   //   .word 0x6666
787   //   rex64
788   //   call __tls_get_addr@plt
789   // to
790   //   mov %fs:0x0,%rax
791   //   addq x@tpoff,%rax
792   const uint8_t Inst[] = {
793       0x64, 0x48, 0x8b, 0x04, 0x25, 0x00, 0x00, 0x00, 0x00, // mov %fs:0x0,%rax
794       0x48, 0x03, 0x05, 0x00, 0x00, 0x00, 0x00              // addq x@tpoff,%rax
795   };
796   memcpy(Loc - 4, Inst, sizeof(Inst));
797 
798   // Both code sequences are PC relatives, but since we are moving the constant
799   // forward by 8 bytes we have to subtract the value by 8.
800   write32le(Loc + 8, Val - 8);
801 }
802 
803 // In some conditions, R_X86_64_GOTTPOFF relocation can be optimized to
804 // R_X86_64_TPOFF32 so that it does not use GOT.
805 template <class ELFT>
806 void X86_64TargetInfo<ELFT>::relaxTlsIeToLe(uint8_t *Loc, uint32_t Type,
807                                             uint64_t Val) const {
808   uint8_t *Inst = Loc - 3;
809   uint8_t Reg = Loc[-1] >> 3;
810   uint8_t *RegSlot = Loc - 1;
811 
812   // Note that ADD with RSP or R12 is converted to ADD instead of LEA
813   // because LEA with these registers needs 4 bytes to encode and thus
814   // wouldn't fit the space.
815 
816   if (memcmp(Inst, "\x48\x03\x25", 3) == 0) {
817     // "addq foo@gottpoff(%rip),%rsp" -> "addq $foo,%rsp"
818     memcpy(Inst, "\x48\x81\xc4", 3);
819   } else if (memcmp(Inst, "\x4c\x03\x25", 3) == 0) {
820     // "addq foo@gottpoff(%rip),%r12" -> "addq $foo,%r12"
821     memcpy(Inst, "\x49\x81\xc4", 3);
822   } else if (memcmp(Inst, "\x4c\x03", 2) == 0) {
823     // "addq foo@gottpoff(%rip),%r[8-15]" -> "leaq foo(%r[8-15]),%r[8-15]"
824     memcpy(Inst, "\x4d\x8d", 2);
825     *RegSlot = 0x80 | (Reg << 3) | Reg;
826   } else if (memcmp(Inst, "\x48\x03", 2) == 0) {
827     // "addq foo@gottpoff(%rip),%reg -> "leaq foo(%reg),%reg"
828     memcpy(Inst, "\x48\x8d", 2);
829     *RegSlot = 0x80 | (Reg << 3) | Reg;
830   } else if (memcmp(Inst, "\x4c\x8b", 2) == 0) {
831     // "movq foo@gottpoff(%rip),%r[8-15]" -> "movq $foo,%r[8-15]"
832     memcpy(Inst, "\x49\xc7", 2);
833     *RegSlot = 0xc0 | Reg;
834   } else if (memcmp(Inst, "\x48\x8b", 2) == 0) {
835     // "movq foo@gottpoff(%rip),%reg" -> "movq $foo,%reg"
836     memcpy(Inst, "\x48\xc7", 2);
837     *RegSlot = 0xc0 | Reg;
838   } else {
839     error(getErrorLocation(Loc - 3) +
840           "R_X86_64_GOTTPOFF must be used in MOVQ or ADDQ instructions only");
841   }
842 
843   // The original code used a PC relative relocation.
844   // Need to compensate for the -4 it had in the addend.
845   write32le(Loc, Val + 4);
846 }
847 
848 template <class ELFT>
849 void X86_64TargetInfo<ELFT>::relaxTlsLdToLe(uint8_t *Loc, uint32_t Type,
850                                             uint64_t Val) const {
851   // Convert
852   //   leaq bar@tlsld(%rip), %rdi
853   //   callq __tls_get_addr@PLT
854   //   leaq bar@dtpoff(%rax), %rcx
855   // to
856   //   .word 0x6666
857   //   .byte 0x66
858   //   mov %fs:0,%rax
859   //   leaq bar@tpoff(%rax), %rcx
860   if (Type == R_X86_64_DTPOFF64) {
861     write64le(Loc, Val);
862     return;
863   }
864   if (Type == R_X86_64_DTPOFF32) {
865     write32le(Loc, Val);
866     return;
867   }
868 
869   const uint8_t Inst[] = {
870       0x66, 0x66,                                          // .word 0x6666
871       0x66,                                                // .byte 0x66
872       0x64, 0x48, 0x8b, 0x04, 0x25, 0x00, 0x00, 0x00, 0x00 // mov %fs:0,%rax
873   };
874   memcpy(Loc - 3, Inst, sizeof(Inst));
875 }
876 
877 template <class ELFT>
878 void X86_64TargetInfo<ELFT>::relocateOne(uint8_t *Loc, uint32_t Type,
879                                          uint64_t Val) const {
880   switch (Type) {
881   case R_X86_64_8:
882     checkUInt<8>(Loc, Val, Type);
883     *Loc = Val;
884     break;
885   case R_X86_64_16:
886     checkUInt<16>(Loc, Val, Type);
887     write16le(Loc, Val);
888     break;
889   case R_X86_64_32:
890     checkUInt<32>(Loc, Val, Type);
891     write32le(Loc, Val);
892     break;
893   case R_X86_64_32S:
894   case R_X86_64_TPOFF32:
895   case R_X86_64_GOT32:
896   case R_X86_64_GOTPCREL:
897   case R_X86_64_GOTPCRELX:
898   case R_X86_64_REX_GOTPCRELX:
899   case R_X86_64_PC32:
900   case R_X86_64_GOTTPOFF:
901   case R_X86_64_PLT32:
902   case R_X86_64_TLSGD:
903   case R_X86_64_TLSLD:
904   case R_X86_64_DTPOFF32:
905   case R_X86_64_SIZE32:
906     checkInt<32>(Loc, Val, Type);
907     write32le(Loc, Val);
908     break;
909   case R_X86_64_64:
910   case R_X86_64_DTPOFF64:
911   case R_X86_64_GLOB_DAT:
912   case R_X86_64_PC64:
913   case R_X86_64_SIZE64:
914   case R_X86_64_GOT64:
915     write64le(Loc, Val);
916     break;
917   default:
918     llvm_unreachable("unexpected relocation");
919   }
920 }
921 
922 template <class ELFT>
923 RelExpr X86_64TargetInfo<ELFT>::adjustRelaxExpr(uint32_t Type,
924                                                 const uint8_t *Data,
925                                                 RelExpr RelExpr) const {
926   if (Type != R_X86_64_GOTPCRELX && Type != R_X86_64_REX_GOTPCRELX)
927     return RelExpr;
928   const uint8_t Op = Data[-2];
929   const uint8_t ModRm = Data[-1];
930 
931   // FIXME: When PIC is disabled and foo is defined locally in the
932   // lower 32 bit address space, memory operand in mov can be converted into
933   // immediate operand. Otherwise, mov must be changed to lea. We support only
934   // latter relaxation at this moment.
935   if (Op == 0x8b)
936     return R_RELAX_GOT_PC;
937 
938   // Relax call and jmp.
939   if (Op == 0xff && (ModRm == 0x15 || ModRm == 0x25))
940     return R_RELAX_GOT_PC;
941 
942   // Relaxation of test, adc, add, and, cmp, or, sbb, sub, xor.
943   // If PIC then no relaxation is available.
944   // We also don't relax test/binop instructions without REX byte,
945   // they are 32bit operations and not common to have.
946   assert(Type == R_X86_64_REX_GOTPCRELX);
947   return Config->Pic ? RelExpr : R_RELAX_GOT_PC_NOPIC;
948 }
949 
950 // A subset of relaxations can only be applied for no-PIC. This method
951 // handles such relaxations. Instructions encoding information was taken from:
952 // "Intel 64 and IA-32 Architectures Software Developer's Manual V2"
953 // (http://www.intel.com/content/dam/www/public/us/en/documents/manuals/
954 //    64-ia-32-architectures-software-developer-instruction-set-reference-manual-325383.pdf)
955 template <class ELFT>
956 void X86_64TargetInfo<ELFT>::relaxGotNoPic(uint8_t *Loc, uint64_t Val,
957                                            uint8_t Op, uint8_t ModRm) const {
958   const uint8_t Rex = Loc[-3];
959   // Convert "test %reg, foo@GOTPCREL(%rip)" to "test $foo, %reg".
960   if (Op == 0x85) {
961     // See "TEST-Logical Compare" (4-428 Vol. 2B),
962     // TEST r/m64, r64 uses "full" ModR / M byte (no opcode extension).
963 
964     // ModR/M byte has form XX YYY ZZZ, where
965     // YYY is MODRM.reg(register 2), ZZZ is MODRM.rm(register 1).
966     // XX has different meanings:
967     // 00: The operand's memory address is in reg1.
968     // 01: The operand's memory address is reg1 + a byte-sized displacement.
969     // 10: The operand's memory address is reg1 + a word-sized displacement.
970     // 11: The operand is reg1 itself.
971     // If an instruction requires only one operand, the unused reg2 field
972     // holds extra opcode bits rather than a register code
973     // 0xC0 == 11 000 000 binary.
974     // 0x38 == 00 111 000 binary.
975     // We transfer reg2 to reg1 here as operand.
976     // See "2.1.3 ModR/M and SIB Bytes" (Vol. 2A 2-3).
977     Loc[-1] = 0xc0 | (ModRm & 0x38) >> 3; // ModR/M byte.
978 
979     // Change opcode from TEST r/m64, r64 to TEST r/m64, imm32
980     // See "TEST-Logical Compare" (4-428 Vol. 2B).
981     Loc[-2] = 0xf7;
982 
983     // Move R bit to the B bit in REX byte.
984     // REX byte is encoded as 0100WRXB, where
985     // 0100 is 4bit fixed pattern.
986     // REX.W When 1, a 64-bit operand size is used. Otherwise, when 0, the
987     //   default operand size is used (which is 32-bit for most but not all
988     //   instructions).
989     // REX.R This 1-bit value is an extension to the MODRM.reg field.
990     // REX.X This 1-bit value is an extension to the SIB.index field.
991     // REX.B This 1-bit value is an extension to the MODRM.rm field or the
992     // SIB.base field.
993     // See "2.2.1.2 More on REX Prefix Fields " (2-8 Vol. 2A).
994     Loc[-3] = (Rex & ~0x4) | (Rex & 0x4) >> 2;
995     write32le(Loc, Val);
996     return;
997   }
998 
999   // If we are here then we need to relax the adc, add, and, cmp, or, sbb, sub
1000   // or xor operations.
1001 
1002   // Convert "binop foo@GOTPCREL(%rip), %reg" to "binop $foo, %reg".
1003   // Logic is close to one for test instruction above, but we also
1004   // write opcode extension here, see below for details.
1005   Loc[-1] = 0xc0 | (ModRm & 0x38) >> 3 | (Op & 0x3c); // ModR/M byte.
1006 
1007   // Primary opcode is 0x81, opcode extension is one of:
1008   // 000b = ADD, 001b is OR, 010b is ADC, 011b is SBB,
1009   // 100b is AND, 101b is SUB, 110b is XOR, 111b is CMP.
1010   // This value was wrote to MODRM.reg in a line above.
1011   // See "3.2 INSTRUCTIONS (A-M)" (Vol. 2A 3-15),
1012   // "INSTRUCTION SET REFERENCE, N-Z" (Vol. 2B 4-1) for
1013   // descriptions about each operation.
1014   Loc[-2] = 0x81;
1015   Loc[-3] = (Rex & ~0x4) | (Rex & 0x4) >> 2;
1016   write32le(Loc, Val);
1017 }
1018 
1019 template <class ELFT>
1020 void X86_64TargetInfo<ELFT>::relaxGot(uint8_t *Loc, uint64_t Val) const {
1021   const uint8_t Op = Loc[-2];
1022   const uint8_t ModRm = Loc[-1];
1023 
1024   // Convert "mov foo@GOTPCREL(%rip),%reg" to "lea foo(%rip),%reg".
1025   if (Op == 0x8b) {
1026     Loc[-2] = 0x8d;
1027     write32le(Loc, Val);
1028     return;
1029   }
1030 
1031   if (Op != 0xff) {
1032     // We are relaxing a rip relative to an absolute, so compensate
1033     // for the old -4 addend.
1034     assert(!Config->Pic);
1035     relaxGotNoPic(Loc, Val + 4, Op, ModRm);
1036     return;
1037   }
1038 
1039   // Convert call/jmp instructions.
1040   if (ModRm == 0x15) {
1041     // ABI says we can convert "call *foo@GOTPCREL(%rip)" to "nop; call foo".
1042     // Instead we convert to "addr32 call foo" where addr32 is an instruction
1043     // prefix. That makes result expression to be a single instruction.
1044     Loc[-2] = 0x67; // addr32 prefix
1045     Loc[-1] = 0xe8; // call
1046     write32le(Loc, Val);
1047     return;
1048   }
1049 
1050   // Convert "jmp *foo@GOTPCREL(%rip)" to "jmp foo; nop".
1051   // jmp doesn't return, so it is fine to use nop here, it is just a stub.
1052   assert(ModRm == 0x25);
1053   Loc[-2] = 0xe9; // jmp
1054   Loc[3] = 0x90;  // nop
1055   write32le(Loc - 1, Val + 1);
1056 }
1057 
1058 // Relocation masks following the #lo(value), #hi(value), #ha(value),
1059 // #higher(value), #highera(value), #highest(value), and #highesta(value)
1060 // macros defined in section 4.5.1. Relocation Types of the PPC-elf64abi
1061 // document.
1062 static uint16_t applyPPCLo(uint64_t V) { return V; }
1063 static uint16_t applyPPCHi(uint64_t V) { return V >> 16; }
1064 static uint16_t applyPPCHa(uint64_t V) { return (V + 0x8000) >> 16; }
1065 static uint16_t applyPPCHigher(uint64_t V) { return V >> 32; }
1066 static uint16_t applyPPCHighera(uint64_t V) { return (V + 0x8000) >> 32; }
1067 static uint16_t applyPPCHighest(uint64_t V) { return V >> 48; }
1068 static uint16_t applyPPCHighesta(uint64_t V) { return (V + 0x8000) >> 48; }
1069 
1070 PPCTargetInfo::PPCTargetInfo() {}
1071 
1072 void PPCTargetInfo::relocateOne(uint8_t *Loc, uint32_t Type,
1073                                 uint64_t Val) const {
1074   switch (Type) {
1075   case R_PPC_ADDR16_HA:
1076     write16be(Loc, applyPPCHa(Val));
1077     break;
1078   case R_PPC_ADDR16_LO:
1079     write16be(Loc, applyPPCLo(Val));
1080     break;
1081   case R_PPC_ADDR32:
1082   case R_PPC_REL32:
1083     write32be(Loc, Val);
1084     break;
1085   case R_PPC_REL24:
1086     or32be(Loc, Val & 0x3FFFFFC);
1087     break;
1088   default:
1089     error(getErrorLocation(Loc) + "unrecognized reloc " + Twine(Type));
1090   }
1091 }
1092 
1093 RelExpr PPCTargetInfo::getRelExpr(uint32_t Type, const SymbolBody &S,
1094                                   const uint8_t *Loc) const {
1095   switch (Type) {
1096   case R_PPC_REL24:
1097   case R_PPC_REL32:
1098     return R_PC;
1099   default:
1100     return R_ABS;
1101   }
1102 }
1103 
1104 PPC64TargetInfo::PPC64TargetInfo() {
1105   PltRel = GotRel = R_PPC64_GLOB_DAT;
1106   RelativeRel = R_PPC64_RELATIVE;
1107   GotEntrySize = 8;
1108   GotPltEntrySize = 8;
1109   PltEntrySize = 32;
1110   PltHeaderSize = 0;
1111 
1112   // We need 64K pages (at least under glibc/Linux, the loader won't
1113   // set different permissions on a finer granularity than that).
1114   DefaultMaxPageSize = 65536;
1115 
1116   // The PPC64 ELF ABI v1 spec, says:
1117   //
1118   //   It is normally desirable to put segments with different characteristics
1119   //   in separate 256 Mbyte portions of the address space, to give the
1120   //   operating system full paging flexibility in the 64-bit address space.
1121   //
1122   // And because the lowest non-zero 256M boundary is 0x10000000, PPC64 linkers
1123   // use 0x10000000 as the starting address.
1124   DefaultImageBase = 0x10000000;
1125 }
1126 
1127 static uint64_t PPC64TocOffset = 0x8000;
1128 
1129 uint64_t getPPC64TocBase() {
1130   // The TOC consists of sections .got, .toc, .tocbss, .plt in that order. The
1131   // TOC starts where the first of these sections starts. We always create a
1132   // .got when we see a relocation that uses it, so for us the start is always
1133   // the .got.
1134   uint64_t TocVA = In<ELF64BE>::Got->getVA();
1135 
1136   // Per the ppc64-elf-linux ABI, The TOC base is TOC value plus 0x8000
1137   // thus permitting a full 64 Kbytes segment. Note that the glibc startup
1138   // code (crt1.o) assumes that you can get from the TOC base to the
1139   // start of the .toc section with only a single (signed) 16-bit relocation.
1140   return TocVA + PPC64TocOffset;
1141 }
1142 
1143 RelExpr PPC64TargetInfo::getRelExpr(uint32_t Type, const SymbolBody &S,
1144                                     const uint8_t *Loc) const {
1145   switch (Type) {
1146   default:
1147     return R_ABS;
1148   case R_PPC64_TOC16:
1149   case R_PPC64_TOC16_DS:
1150   case R_PPC64_TOC16_HA:
1151   case R_PPC64_TOC16_HI:
1152   case R_PPC64_TOC16_LO:
1153   case R_PPC64_TOC16_LO_DS:
1154     return R_GOTREL;
1155   case R_PPC64_TOC:
1156     return R_PPC_TOC;
1157   case R_PPC64_REL24:
1158     return R_PPC_PLT_OPD;
1159   }
1160 }
1161 
1162 void PPC64TargetInfo::writePlt(uint8_t *Buf, uint64_t GotPltEntryAddr,
1163                                uint64_t PltEntryAddr, int32_t Index,
1164                                unsigned RelOff) const {
1165   uint64_t Off = GotPltEntryAddr - getPPC64TocBase();
1166 
1167   // FIXME: What we should do, in theory, is get the offset of the function
1168   // descriptor in the .opd section, and use that as the offset from %r2 (the
1169   // TOC-base pointer). Instead, we have the GOT-entry offset, and that will
1170   // be a pointer to the function descriptor in the .opd section. Using
1171   // this scheme is simpler, but requires an extra indirection per PLT dispatch.
1172 
1173   write32be(Buf, 0xf8410028);                       // std %r2, 40(%r1)
1174   write32be(Buf + 4, 0x3d620000 | applyPPCHa(Off)); // addis %r11, %r2, X@ha
1175   write32be(Buf + 8, 0xe98b0000 | applyPPCLo(Off)); // ld %r12, X@l(%r11)
1176   write32be(Buf + 12, 0xe96c0000);                  // ld %r11,0(%r12)
1177   write32be(Buf + 16, 0x7d6903a6);                  // mtctr %r11
1178   write32be(Buf + 20, 0xe84c0008);                  // ld %r2,8(%r12)
1179   write32be(Buf + 24, 0xe96c0010);                  // ld %r11,16(%r12)
1180   write32be(Buf + 28, 0x4e800420);                  // bctr
1181 }
1182 
1183 static std::pair<uint32_t, uint64_t> toAddr16Rel(uint32_t Type, uint64_t Val) {
1184   uint64_t V = Val - PPC64TocOffset;
1185   switch (Type) {
1186   case R_PPC64_TOC16:
1187     return {R_PPC64_ADDR16, V};
1188   case R_PPC64_TOC16_DS:
1189     return {R_PPC64_ADDR16_DS, V};
1190   case R_PPC64_TOC16_HA:
1191     return {R_PPC64_ADDR16_HA, V};
1192   case R_PPC64_TOC16_HI:
1193     return {R_PPC64_ADDR16_HI, V};
1194   case R_PPC64_TOC16_LO:
1195     return {R_PPC64_ADDR16_LO, V};
1196   case R_PPC64_TOC16_LO_DS:
1197     return {R_PPC64_ADDR16_LO_DS, V};
1198   default:
1199     return {Type, Val};
1200   }
1201 }
1202 
1203 void PPC64TargetInfo::relocateOne(uint8_t *Loc, uint32_t Type,
1204                                   uint64_t Val) const {
1205   // For a TOC-relative relocation, proceed in terms of the corresponding
1206   // ADDR16 relocation type.
1207   std::tie(Type, Val) = toAddr16Rel(Type, Val);
1208 
1209   switch (Type) {
1210   case R_PPC64_ADDR14: {
1211     checkAlignment<4>(Loc, Val, Type);
1212     // Preserve the AA/LK bits in the branch instruction
1213     uint8_t AALK = Loc[3];
1214     write16be(Loc + 2, (AALK & 3) | (Val & 0xfffc));
1215     break;
1216   }
1217   case R_PPC64_ADDR16:
1218     checkInt<16>(Loc, Val, Type);
1219     write16be(Loc, Val);
1220     break;
1221   case R_PPC64_ADDR16_DS:
1222     checkInt<16>(Loc, Val, Type);
1223     write16be(Loc, (read16be(Loc) & 3) | (Val & ~3));
1224     break;
1225   case R_PPC64_ADDR16_HA:
1226   case R_PPC64_REL16_HA:
1227     write16be(Loc, applyPPCHa(Val));
1228     break;
1229   case R_PPC64_ADDR16_HI:
1230   case R_PPC64_REL16_HI:
1231     write16be(Loc, applyPPCHi(Val));
1232     break;
1233   case R_PPC64_ADDR16_HIGHER:
1234     write16be(Loc, applyPPCHigher(Val));
1235     break;
1236   case R_PPC64_ADDR16_HIGHERA:
1237     write16be(Loc, applyPPCHighera(Val));
1238     break;
1239   case R_PPC64_ADDR16_HIGHEST:
1240     write16be(Loc, applyPPCHighest(Val));
1241     break;
1242   case R_PPC64_ADDR16_HIGHESTA:
1243     write16be(Loc, applyPPCHighesta(Val));
1244     break;
1245   case R_PPC64_ADDR16_LO:
1246     write16be(Loc, applyPPCLo(Val));
1247     break;
1248   case R_PPC64_ADDR16_LO_DS:
1249   case R_PPC64_REL16_LO:
1250     write16be(Loc, (read16be(Loc) & 3) | (applyPPCLo(Val) & ~3));
1251     break;
1252   case R_PPC64_ADDR32:
1253   case R_PPC64_REL32:
1254     checkInt<32>(Loc, Val, Type);
1255     write32be(Loc, Val);
1256     break;
1257   case R_PPC64_ADDR64:
1258   case R_PPC64_REL64:
1259   case R_PPC64_TOC:
1260     write64be(Loc, Val);
1261     break;
1262   case R_PPC64_REL24: {
1263     uint32_t Mask = 0x03FFFFFC;
1264     checkInt<24>(Loc, Val, Type);
1265     write32be(Loc, (read32be(Loc) & ~Mask) | (Val & Mask));
1266     break;
1267   }
1268   default:
1269     error(getErrorLocation(Loc) + "unrecognized reloc " + Twine(Type));
1270   }
1271 }
1272 
1273 AArch64TargetInfo::AArch64TargetInfo() {
1274   CopyRel = R_AARCH64_COPY;
1275   RelativeRel = R_AARCH64_RELATIVE;
1276   IRelativeRel = R_AARCH64_IRELATIVE;
1277   GotRel = R_AARCH64_GLOB_DAT;
1278   PltRel = R_AARCH64_JUMP_SLOT;
1279   TlsDescRel = R_AARCH64_TLSDESC;
1280   TlsGotRel = R_AARCH64_TLS_TPREL64;
1281   GotEntrySize = 8;
1282   GotPltEntrySize = 8;
1283   PltEntrySize = 16;
1284   PltHeaderSize = 32;
1285   DefaultMaxPageSize = 65536;
1286 
1287   // It doesn't seem to be documented anywhere, but tls on aarch64 uses variant
1288   // 1 of the tls structures and the tcb size is 16.
1289   TcbSize = 16;
1290 }
1291 
1292 RelExpr AArch64TargetInfo::getRelExpr(uint32_t Type, const SymbolBody &S,
1293                                       const uint8_t *Loc) const {
1294   switch (Type) {
1295   default:
1296     return R_ABS;
1297   case R_AARCH64_TLSDESC_ADR_PAGE21:
1298     return R_TLSDESC_PAGE;
1299   case R_AARCH64_TLSDESC_LD64_LO12:
1300   case R_AARCH64_TLSDESC_ADD_LO12:
1301     return R_TLSDESC;
1302   case R_AARCH64_TLSDESC_CALL:
1303     return R_TLSDESC_CALL;
1304   case R_AARCH64_TLSLE_ADD_TPREL_HI12:
1305   case R_AARCH64_TLSLE_ADD_TPREL_LO12_NC:
1306     return R_TLS;
1307   case R_AARCH64_CALL26:
1308   case R_AARCH64_CONDBR19:
1309   case R_AARCH64_JUMP26:
1310   case R_AARCH64_TSTBR14:
1311     return R_PLT_PC;
1312   case R_AARCH64_PREL16:
1313   case R_AARCH64_PREL32:
1314   case R_AARCH64_PREL64:
1315   case R_AARCH64_ADR_PREL_LO21:
1316     return R_PC;
1317   case R_AARCH64_ADR_PREL_PG_HI21:
1318     return R_PAGE_PC;
1319   case R_AARCH64_LD64_GOT_LO12_NC:
1320   case R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC:
1321     return R_GOT;
1322   case R_AARCH64_ADR_GOT_PAGE:
1323   case R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21:
1324     return R_GOT_PAGE_PC;
1325   case R_AARCH64_NONE:
1326     return R_NONE;
1327   }
1328 }
1329 
1330 RelExpr AArch64TargetInfo::adjustRelaxExpr(uint32_t Type, const uint8_t *Data,
1331                                            RelExpr Expr) const {
1332   if (Expr == R_RELAX_TLS_GD_TO_IE) {
1333     if (Type == R_AARCH64_TLSDESC_ADR_PAGE21)
1334       return R_RELAX_TLS_GD_TO_IE_PAGE_PC;
1335     return R_RELAX_TLS_GD_TO_IE_ABS;
1336   }
1337   return Expr;
1338 }
1339 
1340 bool AArch64TargetInfo::usesOnlyLowPageBits(uint32_t Type) const {
1341   switch (Type) {
1342   default:
1343     return false;
1344   case R_AARCH64_ADD_ABS_LO12_NC:
1345   case R_AARCH64_LD64_GOT_LO12_NC:
1346   case R_AARCH64_LDST128_ABS_LO12_NC:
1347   case R_AARCH64_LDST16_ABS_LO12_NC:
1348   case R_AARCH64_LDST32_ABS_LO12_NC:
1349   case R_AARCH64_LDST64_ABS_LO12_NC:
1350   case R_AARCH64_LDST8_ABS_LO12_NC:
1351   case R_AARCH64_TLSDESC_ADD_LO12:
1352   case R_AARCH64_TLSDESC_LD64_LO12:
1353   case R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC:
1354     return true;
1355   }
1356 }
1357 
1358 bool AArch64TargetInfo::isPicRel(uint32_t Type) const {
1359   return Type == R_AARCH64_ABS32 || Type == R_AARCH64_ABS64;
1360 }
1361 
1362 void AArch64TargetInfo::writeGotPlt(uint8_t *Buf, const SymbolBody &) const {
1363   write64le(Buf, In<ELF64LE>::Plt->getVA());
1364 }
1365 
1366 // Page(Expr) is the page address of the expression Expr, defined
1367 // as (Expr & ~0xFFF). (This applies even if the machine page size
1368 // supported by the platform has a different value.)
1369 uint64_t getAArch64Page(uint64_t Expr) {
1370   return Expr & (~static_cast<uint64_t>(0xFFF));
1371 }
1372 
1373 void AArch64TargetInfo::writePltHeader(uint8_t *Buf) const {
1374   const uint8_t PltData[] = {
1375       0xf0, 0x7b, 0xbf, 0xa9, // stp	x16, x30, [sp,#-16]!
1376       0x10, 0x00, 0x00, 0x90, // adrp	x16, Page(&(.plt.got[2]))
1377       0x11, 0x02, 0x40, 0xf9, // ldr	x17, [x16, Offset(&(.plt.got[2]))]
1378       0x10, 0x02, 0x00, 0x91, // add	x16, x16, Offset(&(.plt.got[2]))
1379       0x20, 0x02, 0x1f, 0xd6, // br	x17
1380       0x1f, 0x20, 0x03, 0xd5, // nop
1381       0x1f, 0x20, 0x03, 0xd5, // nop
1382       0x1f, 0x20, 0x03, 0xd5  // nop
1383   };
1384   memcpy(Buf, PltData, sizeof(PltData));
1385 
1386   uint64_t Got = In<ELF64LE>::GotPlt->getVA();
1387   uint64_t Plt = In<ELF64LE>::Plt->getVA();
1388   relocateOne(Buf + 4, R_AARCH64_ADR_PREL_PG_HI21,
1389               getAArch64Page(Got + 16) - getAArch64Page(Plt + 4));
1390   relocateOne(Buf + 8, R_AARCH64_LDST64_ABS_LO12_NC, Got + 16);
1391   relocateOne(Buf + 12, R_AARCH64_ADD_ABS_LO12_NC, Got + 16);
1392 }
1393 
1394 void AArch64TargetInfo::writePlt(uint8_t *Buf, uint64_t GotPltEntryAddr,
1395                                  uint64_t PltEntryAddr, int32_t Index,
1396                                  unsigned RelOff) const {
1397   const uint8_t Inst[] = {
1398       0x10, 0x00, 0x00, 0x90, // adrp x16, Page(&(.plt.got[n]))
1399       0x11, 0x02, 0x40, 0xf9, // ldr  x17, [x16, Offset(&(.plt.got[n]))]
1400       0x10, 0x02, 0x00, 0x91, // add  x16, x16, Offset(&(.plt.got[n]))
1401       0x20, 0x02, 0x1f, 0xd6  // br   x17
1402   };
1403   memcpy(Buf, Inst, sizeof(Inst));
1404 
1405   relocateOne(Buf, R_AARCH64_ADR_PREL_PG_HI21,
1406               getAArch64Page(GotPltEntryAddr) - getAArch64Page(PltEntryAddr));
1407   relocateOne(Buf + 4, R_AARCH64_LDST64_ABS_LO12_NC, GotPltEntryAddr);
1408   relocateOne(Buf + 8, R_AARCH64_ADD_ABS_LO12_NC, GotPltEntryAddr);
1409 }
1410 
1411 static void write32AArch64Addr(uint8_t *L, uint64_t Imm) {
1412   uint32_t ImmLo = (Imm & 0x3) << 29;
1413   uint32_t ImmHi = (Imm & 0x1FFFFC) << 3;
1414   uint64_t Mask = (0x3 << 29) | (0x1FFFFC << 3);
1415   write32le(L, (read32le(L) & ~Mask) | ImmLo | ImmHi);
1416 }
1417 
1418 // Return the bits [Start, End] from Val shifted Start bits.
1419 // For instance, getBits(0xF0, 4, 8) returns 0xF.
1420 static uint64_t getBits(uint64_t Val, int Start, int End) {
1421   uint64_t Mask = ((uint64_t)1 << (End + 1 - Start)) - 1;
1422   return (Val >> Start) & Mask;
1423 }
1424 
1425 // Update the immediate field in a AARCH64 ldr, str, and add instruction.
1426 static void or32AArch64Imm(uint8_t *L, uint64_t Imm) {
1427   or32le(L, (Imm & 0xFFF) << 10);
1428 }
1429 
1430 void AArch64TargetInfo::relocateOne(uint8_t *Loc, uint32_t Type,
1431                                     uint64_t Val) const {
1432   switch (Type) {
1433   case R_AARCH64_ABS16:
1434   case R_AARCH64_PREL16:
1435     checkIntUInt<16>(Loc, Val, Type);
1436     write16le(Loc, Val);
1437     break;
1438   case R_AARCH64_ABS32:
1439   case R_AARCH64_PREL32:
1440     checkIntUInt<32>(Loc, Val, Type);
1441     write32le(Loc, Val);
1442     break;
1443   case R_AARCH64_ABS64:
1444   case R_AARCH64_GLOB_DAT:
1445   case R_AARCH64_PREL64:
1446     write64le(Loc, Val);
1447     break;
1448   case R_AARCH64_ADD_ABS_LO12_NC:
1449     or32AArch64Imm(Loc, Val);
1450     break;
1451   case R_AARCH64_ADR_GOT_PAGE:
1452   case R_AARCH64_ADR_PREL_PG_HI21:
1453   case R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21:
1454   case R_AARCH64_TLSDESC_ADR_PAGE21:
1455     checkInt<33>(Loc, Val, Type);
1456     write32AArch64Addr(Loc, Val >> 12);
1457     break;
1458   case R_AARCH64_ADR_PREL_LO21:
1459     checkInt<21>(Loc, Val, Type);
1460     write32AArch64Addr(Loc, Val);
1461     break;
1462   case R_AARCH64_CALL26:
1463   case R_AARCH64_JUMP26:
1464     checkInt<28>(Loc, Val, Type);
1465     or32le(Loc, (Val & 0x0FFFFFFC) >> 2);
1466     break;
1467   case R_AARCH64_CONDBR19:
1468     checkInt<21>(Loc, Val, Type);
1469     or32le(Loc, (Val & 0x1FFFFC) << 3);
1470     break;
1471   case R_AARCH64_LD64_GOT_LO12_NC:
1472   case R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC:
1473   case R_AARCH64_TLSDESC_LD64_LO12:
1474     checkAlignment<8>(Loc, Val, Type);
1475     or32le(Loc, (Val & 0xFF8) << 7);
1476     break;
1477   case R_AARCH64_LDST8_ABS_LO12_NC:
1478     or32AArch64Imm(Loc, getBits(Val, 0, 11));
1479     break;
1480   case R_AARCH64_LDST16_ABS_LO12_NC:
1481     or32AArch64Imm(Loc, getBits(Val, 1, 11));
1482     break;
1483   case R_AARCH64_LDST32_ABS_LO12_NC:
1484     or32AArch64Imm(Loc, getBits(Val, 2, 11));
1485     break;
1486   case R_AARCH64_LDST64_ABS_LO12_NC:
1487     or32AArch64Imm(Loc, getBits(Val, 3, 11));
1488     break;
1489   case R_AARCH64_LDST128_ABS_LO12_NC:
1490     or32AArch64Imm(Loc, getBits(Val, 4, 11));
1491     break;
1492   case R_AARCH64_MOVW_UABS_G0_NC:
1493     or32le(Loc, (Val & 0xFFFF) << 5);
1494     break;
1495   case R_AARCH64_MOVW_UABS_G1_NC:
1496     or32le(Loc, (Val & 0xFFFF0000) >> 11);
1497     break;
1498   case R_AARCH64_MOVW_UABS_G2_NC:
1499     or32le(Loc, (Val & 0xFFFF00000000) >> 27);
1500     break;
1501   case R_AARCH64_MOVW_UABS_G3:
1502     or32le(Loc, (Val & 0xFFFF000000000000) >> 43);
1503     break;
1504   case R_AARCH64_TSTBR14:
1505     checkInt<16>(Loc, Val, Type);
1506     or32le(Loc, (Val & 0xFFFC) << 3);
1507     break;
1508   case R_AARCH64_TLSLE_ADD_TPREL_HI12:
1509     checkInt<24>(Loc, Val, Type);
1510     or32AArch64Imm(Loc, Val >> 12);
1511     break;
1512   case R_AARCH64_TLSLE_ADD_TPREL_LO12_NC:
1513   case R_AARCH64_TLSDESC_ADD_LO12:
1514     or32AArch64Imm(Loc, Val);
1515     break;
1516   default:
1517     error(getErrorLocation(Loc) + "unrecognized reloc " + Twine(Type));
1518   }
1519 }
1520 
1521 void AArch64TargetInfo::relaxTlsGdToLe(uint8_t *Loc, uint32_t Type,
1522                                        uint64_t Val) const {
1523   // TLSDESC Global-Dynamic relocation are in the form:
1524   //   adrp    x0, :tlsdesc:v             [R_AARCH64_TLSDESC_ADR_PAGE21]
1525   //   ldr     x1, [x0, #:tlsdesc_lo12:v  [R_AARCH64_TLSDESC_LD64_LO12]
1526   //   add     x0, x0, :tlsdesc_los:v     [R_AARCH64_TLSDESC_ADD_LO12]
1527   //   .tlsdesccall                       [R_AARCH64_TLSDESC_CALL]
1528   //   blr     x1
1529   // And it can optimized to:
1530   //   movz    x0, #0x0, lsl #16
1531   //   movk    x0, #0x10
1532   //   nop
1533   //   nop
1534   checkUInt<32>(Loc, Val, Type);
1535 
1536   switch (Type) {
1537   case R_AARCH64_TLSDESC_ADD_LO12:
1538   case R_AARCH64_TLSDESC_CALL:
1539     write32le(Loc, 0xd503201f); // nop
1540     return;
1541   case R_AARCH64_TLSDESC_ADR_PAGE21:
1542     write32le(Loc, 0xd2a00000 | (((Val >> 16) & 0xffff) << 5)); // movz
1543     return;
1544   case R_AARCH64_TLSDESC_LD64_LO12:
1545     write32le(Loc, 0xf2800000 | ((Val & 0xffff) << 5)); // movk
1546     return;
1547   default:
1548     llvm_unreachable("unsupported relocation for TLS GD to LE relaxation");
1549   }
1550 }
1551 
1552 void AArch64TargetInfo::relaxTlsGdToIe(uint8_t *Loc, uint32_t Type,
1553                                        uint64_t Val) const {
1554   // TLSDESC Global-Dynamic relocation are in the form:
1555   //   adrp    x0, :tlsdesc:v             [R_AARCH64_TLSDESC_ADR_PAGE21]
1556   //   ldr     x1, [x0, #:tlsdesc_lo12:v  [R_AARCH64_TLSDESC_LD64_LO12]
1557   //   add     x0, x0, :tlsdesc_los:v     [R_AARCH64_TLSDESC_ADD_LO12]
1558   //   .tlsdesccall                       [R_AARCH64_TLSDESC_CALL]
1559   //   blr     x1
1560   // And it can optimized to:
1561   //   adrp    x0, :gottprel:v
1562   //   ldr     x0, [x0, :gottprel_lo12:v]
1563   //   nop
1564   //   nop
1565 
1566   switch (Type) {
1567   case R_AARCH64_TLSDESC_ADD_LO12:
1568   case R_AARCH64_TLSDESC_CALL:
1569     write32le(Loc, 0xd503201f); // nop
1570     break;
1571   case R_AARCH64_TLSDESC_ADR_PAGE21:
1572     write32le(Loc, 0x90000000); // adrp
1573     relocateOne(Loc, R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21, Val);
1574     break;
1575   case R_AARCH64_TLSDESC_LD64_LO12:
1576     write32le(Loc, 0xf9400000); // ldr
1577     relocateOne(Loc, R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC, Val);
1578     break;
1579   default:
1580     llvm_unreachable("unsupported relocation for TLS GD to LE relaxation");
1581   }
1582 }
1583 
1584 void AArch64TargetInfo::relaxTlsIeToLe(uint8_t *Loc, uint32_t Type,
1585                                        uint64_t Val) const {
1586   checkUInt<32>(Loc, Val, Type);
1587 
1588   if (Type == R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21) {
1589     // Generate MOVZ.
1590     uint32_t RegNo = read32le(Loc) & 0x1f;
1591     write32le(Loc, (0xd2a00000 | RegNo) | (((Val >> 16) & 0xffff) << 5));
1592     return;
1593   }
1594   if (Type == R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC) {
1595     // Generate MOVK.
1596     uint32_t RegNo = read32le(Loc) & 0x1f;
1597     write32le(Loc, (0xf2800000 | RegNo) | ((Val & 0xffff) << 5));
1598     return;
1599   }
1600   llvm_unreachable("invalid relocation for TLS IE to LE relaxation");
1601 }
1602 
1603 AMDGPUTargetInfo::AMDGPUTargetInfo() {
1604   RelativeRel = R_AMDGPU_REL64;
1605   GotRel = R_AMDGPU_ABS64;
1606   GotEntrySize = 8;
1607 }
1608 
1609 void AMDGPUTargetInfo::relocateOne(uint8_t *Loc, uint32_t Type,
1610                                    uint64_t Val) const {
1611   switch (Type) {
1612   case R_AMDGPU_ABS32:
1613   case R_AMDGPU_GOTPCREL:
1614   case R_AMDGPU_GOTPCREL32_LO:
1615   case R_AMDGPU_REL32:
1616   case R_AMDGPU_REL32_LO:
1617     write32le(Loc, Val);
1618     break;
1619   case R_AMDGPU_ABS64:
1620     write64le(Loc, Val);
1621     break;
1622   case R_AMDGPU_GOTPCREL32_HI:
1623   case R_AMDGPU_REL32_HI:
1624     write32le(Loc, Val >> 32);
1625     break;
1626   default:
1627     error(getErrorLocation(Loc) + "unrecognized reloc " + Twine(Type));
1628   }
1629 }
1630 
1631 RelExpr AMDGPUTargetInfo::getRelExpr(uint32_t Type, const SymbolBody &S,
1632                                      const uint8_t *Loc) const {
1633   switch (Type) {
1634   case R_AMDGPU_ABS32:
1635   case R_AMDGPU_ABS64:
1636     return R_ABS;
1637   case R_AMDGPU_REL32:
1638   case R_AMDGPU_REL32_LO:
1639   case R_AMDGPU_REL32_HI:
1640     return R_PC;
1641   case R_AMDGPU_GOTPCREL:
1642   case R_AMDGPU_GOTPCREL32_LO:
1643   case R_AMDGPU_GOTPCREL32_HI:
1644     return R_GOT_PC;
1645   default:
1646     error(toString(S.File) + ": unknown relocation type: " + toString(Type));
1647     return R_HINT;
1648   }
1649 }
1650 
1651 ARMTargetInfo::ARMTargetInfo() {
1652   CopyRel = R_ARM_COPY;
1653   RelativeRel = R_ARM_RELATIVE;
1654   IRelativeRel = R_ARM_IRELATIVE;
1655   GotRel = R_ARM_GLOB_DAT;
1656   PltRel = R_ARM_JUMP_SLOT;
1657   TlsGotRel = R_ARM_TLS_TPOFF32;
1658   TlsModuleIndexRel = R_ARM_TLS_DTPMOD32;
1659   TlsOffsetRel = R_ARM_TLS_DTPOFF32;
1660   GotEntrySize = 4;
1661   GotPltEntrySize = 4;
1662   PltEntrySize = 16;
1663   PltHeaderSize = 20;
1664   // ARM uses Variant 1 TLS
1665   TcbSize = 8;
1666   NeedsThunks = true;
1667 }
1668 
1669 RelExpr ARMTargetInfo::getRelExpr(uint32_t Type, const SymbolBody &S,
1670                                   const uint8_t *Loc) const {
1671   switch (Type) {
1672   default:
1673     return R_ABS;
1674   case R_ARM_THM_JUMP11:
1675     return R_PC;
1676   case R_ARM_CALL:
1677   case R_ARM_JUMP24:
1678   case R_ARM_PC24:
1679   case R_ARM_PLT32:
1680   case R_ARM_PREL31:
1681   case R_ARM_THM_JUMP19:
1682   case R_ARM_THM_JUMP24:
1683   case R_ARM_THM_CALL:
1684     return R_PLT_PC;
1685   case R_ARM_GOTOFF32:
1686     // (S + A) - GOT_ORG
1687     return R_GOTREL;
1688   case R_ARM_GOT_BREL:
1689     // GOT(S) + A - GOT_ORG
1690     return R_GOT_OFF;
1691   case R_ARM_GOT_PREL:
1692   case R_ARM_TLS_IE32:
1693     // GOT(S) + A - P
1694     return R_GOT_PC;
1695   case R_ARM_TARGET1:
1696     return Config->Target1Rel ? R_PC : R_ABS;
1697   case R_ARM_TARGET2:
1698     if (Config->Target2 == Target2Policy::Rel)
1699       return R_PC;
1700     if (Config->Target2 == Target2Policy::Abs)
1701       return R_ABS;
1702     return R_GOT_PC;
1703   case R_ARM_TLS_GD32:
1704     return R_TLSGD_PC;
1705   case R_ARM_TLS_LDM32:
1706     return R_TLSLD_PC;
1707   case R_ARM_BASE_PREL:
1708     // B(S) + A - P
1709     // FIXME: currently B(S) assumed to be .got, this may not hold for all
1710     // platforms.
1711     return R_GOTONLY_PC;
1712   case R_ARM_MOVW_PREL_NC:
1713   case R_ARM_MOVT_PREL:
1714   case R_ARM_REL32:
1715   case R_ARM_THM_MOVW_PREL_NC:
1716   case R_ARM_THM_MOVT_PREL:
1717     return R_PC;
1718   case R_ARM_NONE:
1719     return R_NONE;
1720   case R_ARM_TLS_LE32:
1721     return R_TLS;
1722   }
1723 }
1724 
1725 bool ARMTargetInfo::isPicRel(uint32_t Type) const {
1726   return (Type == R_ARM_TARGET1 && !Config->Target1Rel) ||
1727          (Type == R_ARM_ABS32);
1728 }
1729 
1730 uint32_t ARMTargetInfo::getDynRel(uint32_t Type) const {
1731   if (Type == R_ARM_TARGET1 && !Config->Target1Rel)
1732     return R_ARM_ABS32;
1733   if (Type == R_ARM_ABS32)
1734     return Type;
1735   // Keep it going with a dummy value so that we can find more reloc errors.
1736   return R_ARM_ABS32;
1737 }
1738 
1739 void ARMTargetInfo::writeGotPlt(uint8_t *Buf, const SymbolBody &) const {
1740   write32le(Buf, In<ELF32LE>::Plt->getVA());
1741 }
1742 
1743 void ARMTargetInfo::writeIgotPlt(uint8_t *Buf, const SymbolBody &S) const {
1744   // An ARM entry is the address of the ifunc resolver function.
1745   write32le(Buf, S.getVA());
1746 }
1747 
1748 void ARMTargetInfo::writePltHeader(uint8_t *Buf) const {
1749   const uint8_t PltData[] = {
1750       0x04, 0xe0, 0x2d, 0xe5, //     str lr, [sp,#-4]!
1751       0x04, 0xe0, 0x9f, 0xe5, //     ldr lr, L2
1752       0x0e, 0xe0, 0x8f, 0xe0, // L1: add lr, pc, lr
1753       0x08, 0xf0, 0xbe, 0xe5, //     ldr pc, [lr, #8]
1754       0x00, 0x00, 0x00, 0x00, // L2: .word   &(.got.plt) - L1 - 8
1755   };
1756   memcpy(Buf, PltData, sizeof(PltData));
1757   uint64_t GotPlt = In<ELF32LE>::GotPlt->getVA();
1758   uint64_t L1 = In<ELF32LE>::Plt->getVA() + 8;
1759   write32le(Buf + 16, GotPlt - L1 - 8);
1760 }
1761 
1762 void ARMTargetInfo::addPltHeaderSymbols(InputSectionBase *ISD) const {
1763   auto *IS = cast<InputSection>(ISD);
1764   addSyntheticLocal<ELF32LE>("$a", STT_NOTYPE, 0, 0, IS);
1765   addSyntheticLocal<ELF32LE>("$d", STT_NOTYPE, 16, 0, IS);
1766 }
1767 
1768 void ARMTargetInfo::writePlt(uint8_t *Buf, uint64_t GotPltEntryAddr,
1769                              uint64_t PltEntryAddr, int32_t Index,
1770                              unsigned RelOff) const {
1771   // FIXME: Using simple code sequence with simple relocations.
1772   // There is a more optimal sequence but it requires support for the group
1773   // relocations. See ELF for the ARM Architecture Appendix A.3
1774   const uint8_t PltData[] = {
1775       0x04, 0xc0, 0x9f, 0xe5, //     ldr ip, L2
1776       0x0f, 0xc0, 0x8c, 0xe0, // L1: add ip, ip, pc
1777       0x00, 0xf0, 0x9c, 0xe5, //     ldr pc, [ip]
1778       0x00, 0x00, 0x00, 0x00, // L2: .word   Offset(&(.plt.got) - L1 - 8
1779   };
1780   memcpy(Buf, PltData, sizeof(PltData));
1781   uint64_t L1 = PltEntryAddr + 4;
1782   write32le(Buf + 12, GotPltEntryAddr - L1 - 8);
1783 }
1784 
1785 void ARMTargetInfo::addPltSymbols(InputSectionBase *ISD, uint64_t Off) const {
1786   auto *IS = cast<InputSection>(ISD);
1787   addSyntheticLocal<ELF32LE>("$a", STT_NOTYPE, Off, 0, IS);
1788   addSyntheticLocal<ELF32LE>("$d", STT_NOTYPE, Off + 12, 0, IS);
1789 }
1790 
1791 bool ARMTargetInfo::needsThunk(RelExpr Expr, uint32_t RelocType,
1792                                const InputFile *File,
1793                                const SymbolBody &S) const {
1794   // If S is an undefined weak symbol in an executable we don't need a Thunk.
1795   // In a DSO calls to undefined symbols, including weak ones get PLT entries
1796   // which may need a thunk.
1797   if (S.isUndefined() && !S.isLocal() && S.symbol()->isWeak() &&
1798       !Config->Shared)
1799     return false;
1800   // A state change from ARM to Thumb and vice versa must go through an
1801   // interworking thunk if the relocation type is not R_ARM_CALL or
1802   // R_ARM_THM_CALL.
1803   switch (RelocType) {
1804   case R_ARM_PC24:
1805   case R_ARM_PLT32:
1806   case R_ARM_JUMP24:
1807     // Source is ARM, all PLT entries are ARM so no interworking required.
1808     // Otherwise we need to interwork if Symbol has bit 0 set (Thumb).
1809     if (Expr == R_PC && ((S.getVA() & 1) == 1))
1810       return true;
1811     break;
1812   case R_ARM_THM_JUMP19:
1813   case R_ARM_THM_JUMP24:
1814     // Source is Thumb, all PLT entries are ARM so interworking is required.
1815     // Otherwise we need to interwork if Symbol has bit 0 clear (ARM).
1816     if (Expr == R_PLT_PC || ((S.getVA() & 1) == 0))
1817       return true;
1818     break;
1819   }
1820   return false;
1821 }
1822 
1823 void ARMTargetInfo::relocateOne(uint8_t *Loc, uint32_t Type,
1824                                 uint64_t Val) const {
1825   switch (Type) {
1826   case R_ARM_ABS32:
1827   case R_ARM_BASE_PREL:
1828   case R_ARM_GLOB_DAT:
1829   case R_ARM_GOTOFF32:
1830   case R_ARM_GOT_BREL:
1831   case R_ARM_GOT_PREL:
1832   case R_ARM_REL32:
1833   case R_ARM_RELATIVE:
1834   case R_ARM_TARGET1:
1835   case R_ARM_TARGET2:
1836   case R_ARM_TLS_GD32:
1837   case R_ARM_TLS_IE32:
1838   case R_ARM_TLS_LDM32:
1839   case R_ARM_TLS_LDO32:
1840   case R_ARM_TLS_LE32:
1841   case R_ARM_TLS_TPOFF32:
1842   case R_ARM_TLS_DTPOFF32:
1843     write32le(Loc, Val);
1844     break;
1845   case R_ARM_TLS_DTPMOD32:
1846     write32le(Loc, 1);
1847     break;
1848   case R_ARM_PREL31:
1849     checkInt<31>(Loc, Val, Type);
1850     write32le(Loc, (read32le(Loc) & 0x80000000) | (Val & ~0x80000000));
1851     break;
1852   case R_ARM_CALL:
1853     // R_ARM_CALL is used for BL and BLX instructions, depending on the
1854     // value of bit 0 of Val, we must select a BL or BLX instruction
1855     if (Val & 1) {
1856       // If bit 0 of Val is 1 the target is Thumb, we must select a BLX.
1857       // The BLX encoding is 0xfa:H:imm24 where Val = imm24:H:'1'
1858       checkInt<26>(Loc, Val, Type);
1859       write32le(Loc, 0xfa000000 |                    // opcode
1860                          ((Val & 2) << 23) |         // H
1861                          ((Val >> 2) & 0x00ffffff)); // imm24
1862       break;
1863     }
1864     if ((read32le(Loc) & 0xfe000000) == 0xfa000000)
1865       // BLX (always unconditional) instruction to an ARM Target, select an
1866       // unconditional BL.
1867       write32le(Loc, 0xeb000000 | (read32le(Loc) & 0x00ffffff));
1868   // fall through as BL encoding is shared with B
1869   case R_ARM_JUMP24:
1870   case R_ARM_PC24:
1871   case R_ARM_PLT32:
1872     checkInt<26>(Loc, Val, Type);
1873     write32le(Loc, (read32le(Loc) & ~0x00ffffff) | ((Val >> 2) & 0x00ffffff));
1874     break;
1875   case R_ARM_THM_JUMP11:
1876     checkInt<12>(Loc, Val, Type);
1877     write16le(Loc, (read32le(Loc) & 0xf800) | ((Val >> 1) & 0x07ff));
1878     break;
1879   case R_ARM_THM_JUMP19:
1880     // Encoding T3: Val = S:J2:J1:imm6:imm11:0
1881     checkInt<21>(Loc, Val, Type);
1882     write16le(Loc,
1883               (read16le(Loc) & 0xfbc0) |   // opcode cond
1884                   ((Val >> 10) & 0x0400) | // S
1885                   ((Val >> 12) & 0x003f)); // imm6
1886     write16le(Loc + 2,
1887               0x8000 |                    // opcode
1888                   ((Val >> 8) & 0x0800) | // J2
1889                   ((Val >> 5) & 0x2000) | // J1
1890                   ((Val >> 1) & 0x07ff)); // imm11
1891     break;
1892   case R_ARM_THM_CALL:
1893     // R_ARM_THM_CALL is used for BL and BLX instructions, depending on the
1894     // value of bit 0 of Val, we must select a BL or BLX instruction
1895     if ((Val & 1) == 0) {
1896       // Ensure BLX destination is 4-byte aligned. As BLX instruction may
1897       // only be two byte aligned. This must be done before overflow check
1898       Val = alignTo(Val, 4);
1899     }
1900     // Bit 12 is 0 for BLX, 1 for BL
1901     write16le(Loc + 2, (read16le(Loc + 2) & ~0x1000) | (Val & 1) << 12);
1902   // Fall through as rest of encoding is the same as B.W
1903   case R_ARM_THM_JUMP24:
1904     // Encoding B  T4, BL T1, BLX T2: Val = S:I1:I2:imm10:imm11:0
1905     // FIXME: Use of I1 and I2 require v6T2ops
1906     checkInt<25>(Loc, Val, Type);
1907     write16le(Loc,
1908               0xf000 |                     // opcode
1909                   ((Val >> 14) & 0x0400) | // S
1910                   ((Val >> 12) & 0x03ff)); // imm10
1911     write16le(Loc + 2,
1912               (read16le(Loc + 2) & 0xd000) |                  // opcode
1913                   (((~(Val >> 10)) ^ (Val >> 11)) & 0x2000) | // J1
1914                   (((~(Val >> 11)) ^ (Val >> 13)) & 0x0800) | // J2
1915                   ((Val >> 1) & 0x07ff));                     // imm11
1916     break;
1917   case R_ARM_MOVW_ABS_NC:
1918   case R_ARM_MOVW_PREL_NC:
1919     write32le(Loc, (read32le(Loc) & ~0x000f0fff) | ((Val & 0xf000) << 4) |
1920                        (Val & 0x0fff));
1921     break;
1922   case R_ARM_MOVT_ABS:
1923   case R_ARM_MOVT_PREL:
1924     checkInt<32>(Loc, Val, Type);
1925     write32le(Loc, (read32le(Loc) & ~0x000f0fff) |
1926                        (((Val >> 16) & 0xf000) << 4) | ((Val >> 16) & 0xfff));
1927     break;
1928   case R_ARM_THM_MOVT_ABS:
1929   case R_ARM_THM_MOVT_PREL:
1930     // Encoding T1: A = imm4:i:imm3:imm8
1931     checkInt<32>(Loc, Val, Type);
1932     write16le(Loc,
1933               0xf2c0 |                     // opcode
1934                   ((Val >> 17) & 0x0400) | // i
1935                   ((Val >> 28) & 0x000f)); // imm4
1936     write16le(Loc + 2,
1937               (read16le(Loc + 2) & 0x8f00) | // opcode
1938                   ((Val >> 12) & 0x7000) |   // imm3
1939                   ((Val >> 16) & 0x00ff));   // imm8
1940     break;
1941   case R_ARM_THM_MOVW_ABS_NC:
1942   case R_ARM_THM_MOVW_PREL_NC:
1943     // Encoding T3: A = imm4:i:imm3:imm8
1944     write16le(Loc,
1945               0xf240 |                     // opcode
1946                   ((Val >> 1) & 0x0400) |  // i
1947                   ((Val >> 12) & 0x000f)); // imm4
1948     write16le(Loc + 2,
1949               (read16le(Loc + 2) & 0x8f00) | // opcode
1950                   ((Val << 4) & 0x7000) |    // imm3
1951                   (Val & 0x00ff));           // imm8
1952     break;
1953   default:
1954     error(getErrorLocation(Loc) + "unrecognized reloc " + Twine(Type));
1955   }
1956 }
1957 
1958 int64_t ARMTargetInfo::getImplicitAddend(const uint8_t *Buf,
1959                                          uint32_t Type) const {
1960   switch (Type) {
1961   default:
1962     return 0;
1963   case R_ARM_ABS32:
1964   case R_ARM_BASE_PREL:
1965   case R_ARM_GOTOFF32:
1966   case R_ARM_GOT_BREL:
1967   case R_ARM_GOT_PREL:
1968   case R_ARM_REL32:
1969   case R_ARM_TARGET1:
1970   case R_ARM_TARGET2:
1971   case R_ARM_TLS_GD32:
1972   case R_ARM_TLS_LDM32:
1973   case R_ARM_TLS_LDO32:
1974   case R_ARM_TLS_IE32:
1975   case R_ARM_TLS_LE32:
1976     return SignExtend64<32>(read32le(Buf));
1977   case R_ARM_PREL31:
1978     return SignExtend64<31>(read32le(Buf));
1979   case R_ARM_CALL:
1980   case R_ARM_JUMP24:
1981   case R_ARM_PC24:
1982   case R_ARM_PLT32:
1983     return SignExtend64<26>(read32le(Buf) << 2);
1984   case R_ARM_THM_JUMP11:
1985     return SignExtend64<12>(read16le(Buf) << 1);
1986   case R_ARM_THM_JUMP19: {
1987     // Encoding T3: A = S:J2:J1:imm10:imm6:0
1988     uint16_t Hi = read16le(Buf);
1989     uint16_t Lo = read16le(Buf + 2);
1990     return SignExtend64<20>(((Hi & 0x0400) << 10) | // S
1991                             ((Lo & 0x0800) << 8) |  // J2
1992                             ((Lo & 0x2000) << 5) |  // J1
1993                             ((Hi & 0x003f) << 12) | // imm6
1994                             ((Lo & 0x07ff) << 1));  // imm11:0
1995   }
1996   case R_ARM_THM_CALL:
1997   case R_ARM_THM_JUMP24: {
1998     // Encoding B T4, BL T1, BLX T2: A = S:I1:I2:imm10:imm11:0
1999     // I1 = NOT(J1 EOR S), I2 = NOT(J2 EOR S)
2000     // FIXME: I1 and I2 require v6T2ops
2001     uint16_t Hi = read16le(Buf);
2002     uint16_t Lo = read16le(Buf + 2);
2003     return SignExtend64<24>(((Hi & 0x0400) << 14) |                    // S
2004                             (~((Lo ^ (Hi << 3)) << 10) & 0x00800000) | // I1
2005                             (~((Lo ^ (Hi << 1)) << 11) & 0x00400000) | // I2
2006                             ((Hi & 0x003ff) << 12) |                   // imm0
2007                             ((Lo & 0x007ff) << 1)); // imm11:0
2008   }
2009   // ELF for the ARM Architecture 4.6.1.1 the implicit addend for MOVW and
2010   // MOVT is in the range -32768 <= A < 32768
2011   case R_ARM_MOVW_ABS_NC:
2012   case R_ARM_MOVT_ABS:
2013   case R_ARM_MOVW_PREL_NC:
2014   case R_ARM_MOVT_PREL: {
2015     uint64_t Val = read32le(Buf) & 0x000f0fff;
2016     return SignExtend64<16>(((Val & 0x000f0000) >> 4) | (Val & 0x00fff));
2017   }
2018   case R_ARM_THM_MOVW_ABS_NC:
2019   case R_ARM_THM_MOVT_ABS:
2020   case R_ARM_THM_MOVW_PREL_NC:
2021   case R_ARM_THM_MOVT_PREL: {
2022     // Encoding T3: A = imm4:i:imm3:imm8
2023     uint16_t Hi = read16le(Buf);
2024     uint16_t Lo = read16le(Buf + 2);
2025     return SignExtend64<16>(((Hi & 0x000f) << 12) | // imm4
2026                             ((Hi & 0x0400) << 1) |  // i
2027                             ((Lo & 0x7000) >> 4) |  // imm3
2028                             (Lo & 0x00ff));         // imm8
2029   }
2030   }
2031 }
2032 
2033 template <class ELFT> MipsTargetInfo<ELFT>::MipsTargetInfo() {
2034   GotPltHeaderEntriesNum = 2;
2035   DefaultMaxPageSize = 65536;
2036   GotEntrySize = sizeof(typename ELFT::uint);
2037   GotPltEntrySize = sizeof(typename ELFT::uint);
2038   PltEntrySize = 16;
2039   PltHeaderSize = 32;
2040   CopyRel = R_MIPS_COPY;
2041   PltRel = R_MIPS_JUMP_SLOT;
2042   NeedsThunks = true;
2043   if (ELFT::Is64Bits) {
2044     RelativeRel = (R_MIPS_64 << 8) | R_MIPS_REL32;
2045     TlsGotRel = R_MIPS_TLS_TPREL64;
2046     TlsModuleIndexRel = R_MIPS_TLS_DTPMOD64;
2047     TlsOffsetRel = R_MIPS_TLS_DTPREL64;
2048   } else {
2049     RelativeRel = R_MIPS_REL32;
2050     TlsGotRel = R_MIPS_TLS_TPREL32;
2051     TlsModuleIndexRel = R_MIPS_TLS_DTPMOD32;
2052     TlsOffsetRel = R_MIPS_TLS_DTPREL32;
2053   }
2054 }
2055 
2056 template <class ELFT>
2057 RelExpr MipsTargetInfo<ELFT>::getRelExpr(uint32_t Type, const SymbolBody &S,
2058                                          const uint8_t *Loc) const {
2059   // See comment in the calculateMipsRelChain.
2060   if (ELFT::Is64Bits || Config->MipsN32Abi)
2061     Type &= 0xff;
2062   switch (Type) {
2063   default:
2064     return R_ABS;
2065   case R_MIPS_JALR:
2066     return R_HINT;
2067   case R_MIPS_GPREL16:
2068   case R_MIPS_GPREL32:
2069     return R_MIPS_GOTREL;
2070   case R_MIPS_26:
2071     return R_PLT;
2072   case R_MIPS_HI16:
2073   case R_MIPS_LO16:
2074     // R_MIPS_HI16/R_MIPS_LO16 relocations against _gp_disp calculate
2075     // offset between start of function and 'gp' value which by default
2076     // equal to the start of .got section. In that case we consider these
2077     // relocations as relative.
2078     if (&S == ElfSym::MipsGpDisp)
2079       return R_MIPS_GOT_GP_PC;
2080     if (&S == ElfSym::MipsLocalGp)
2081       return R_MIPS_GOT_GP;
2082     // fallthrough
2083   case R_MIPS_GOT_OFST:
2084     return R_ABS;
2085   case R_MIPS_PC32:
2086   case R_MIPS_PC16:
2087   case R_MIPS_PC19_S2:
2088   case R_MIPS_PC21_S2:
2089   case R_MIPS_PC26_S2:
2090   case R_MIPS_PCHI16:
2091   case R_MIPS_PCLO16:
2092     return R_PC;
2093   case R_MIPS_GOT16:
2094     if (S.isLocal())
2095       return R_MIPS_GOT_LOCAL_PAGE;
2096   // fallthrough
2097   case R_MIPS_CALL16:
2098   case R_MIPS_GOT_DISP:
2099   case R_MIPS_TLS_GOTTPREL:
2100     return R_MIPS_GOT_OFF;
2101   case R_MIPS_CALL_HI16:
2102   case R_MIPS_CALL_LO16:
2103   case R_MIPS_GOT_HI16:
2104   case R_MIPS_GOT_LO16:
2105     return R_MIPS_GOT_OFF32;
2106   case R_MIPS_GOT_PAGE:
2107     return R_MIPS_GOT_LOCAL_PAGE;
2108   case R_MIPS_TLS_GD:
2109     return R_MIPS_TLSGD;
2110   case R_MIPS_TLS_LDM:
2111     return R_MIPS_TLSLD;
2112   }
2113 }
2114 
2115 template <class ELFT> bool MipsTargetInfo<ELFT>::isPicRel(uint32_t Type) const {
2116   return Type == R_MIPS_32 || Type == R_MIPS_64;
2117 }
2118 
2119 template <class ELFT>
2120 uint32_t MipsTargetInfo<ELFT>::getDynRel(uint32_t Type) const {
2121   return RelativeRel;
2122 }
2123 
2124 template <class ELFT>
2125 void MipsTargetInfo<ELFT>::writeGotPlt(uint8_t *Buf, const SymbolBody &) const {
2126   write32<ELFT::TargetEndianness>(Buf, In<ELFT>::Plt->getVA());
2127 }
2128 
2129 template <endianness E, uint8_t BSIZE, uint8_t SHIFT>
2130 static int64_t getPcRelocAddend(const uint8_t *Loc) {
2131   uint32_t Instr = read32<E>(Loc);
2132   uint32_t Mask = 0xffffffff >> (32 - BSIZE);
2133   return SignExtend64<BSIZE + SHIFT>((Instr & Mask) << SHIFT);
2134 }
2135 
2136 template <endianness E, uint8_t BSIZE, uint8_t SHIFT>
2137 static void applyMipsPcReloc(uint8_t *Loc, uint32_t Type, uint64_t V) {
2138   uint32_t Mask = 0xffffffff >> (32 - BSIZE);
2139   uint32_t Instr = read32<E>(Loc);
2140   if (SHIFT > 0)
2141     checkAlignment<(1 << SHIFT)>(Loc, V, Type);
2142   checkInt<BSIZE + SHIFT>(Loc, V, Type);
2143   write32<E>(Loc, (Instr & ~Mask) | ((V >> SHIFT) & Mask));
2144 }
2145 
2146 template <endianness E> static void writeMipsHi16(uint8_t *Loc, uint64_t V) {
2147   uint32_t Instr = read32<E>(Loc);
2148   uint16_t Res = ((V + 0x8000) >> 16) & 0xffff;
2149   write32<E>(Loc, (Instr & 0xffff0000) | Res);
2150 }
2151 
2152 template <endianness E> static void writeMipsHigher(uint8_t *Loc, uint64_t V) {
2153   uint32_t Instr = read32<E>(Loc);
2154   uint16_t Res = ((V + 0x80008000) >> 32) & 0xffff;
2155   write32<E>(Loc, (Instr & 0xffff0000) | Res);
2156 }
2157 
2158 template <endianness E> static void writeMipsHighest(uint8_t *Loc, uint64_t V) {
2159   uint32_t Instr = read32<E>(Loc);
2160   uint16_t Res = ((V + 0x800080008000) >> 48) & 0xffff;
2161   write32<E>(Loc, (Instr & 0xffff0000) | Res);
2162 }
2163 
2164 template <endianness E> static void writeMipsLo16(uint8_t *Loc, uint64_t V) {
2165   uint32_t Instr = read32<E>(Loc);
2166   write32<E>(Loc, (Instr & 0xffff0000) | (V & 0xffff));
2167 }
2168 
2169 template <class ELFT> static bool isMipsR6() {
2170   const auto &FirstObj = cast<ELFFileBase<ELFT>>(*Config->FirstElf);
2171   uint32_t Arch = FirstObj.getObj().getHeader()->e_flags & EF_MIPS_ARCH;
2172   return Arch == EF_MIPS_ARCH_32R6 || Arch == EF_MIPS_ARCH_64R6;
2173 }
2174 
2175 template <class ELFT>
2176 void MipsTargetInfo<ELFT>::writePltHeader(uint8_t *Buf) const {
2177   const endianness E = ELFT::TargetEndianness;
2178   if (Config->MipsN32Abi) {
2179     write32<E>(Buf, 0x3c0e0000);      // lui   $14, %hi(&GOTPLT[0])
2180     write32<E>(Buf + 4, 0x8dd90000);  // lw    $25, %lo(&GOTPLT[0])($14)
2181     write32<E>(Buf + 8, 0x25ce0000);  // addiu $14, $14, %lo(&GOTPLT[0])
2182     write32<E>(Buf + 12, 0x030ec023); // subu  $24, $24, $14
2183   } else {
2184     write32<E>(Buf, 0x3c1c0000);      // lui   $28, %hi(&GOTPLT[0])
2185     write32<E>(Buf + 4, 0x8f990000);  // lw    $25, %lo(&GOTPLT[0])($28)
2186     write32<E>(Buf + 8, 0x279c0000);  // addiu $28, $28, %lo(&GOTPLT[0])
2187     write32<E>(Buf + 12, 0x031cc023); // subu  $24, $24, $28
2188   }
2189 
2190   write32<E>(Buf + 16, 0x03e07825); // move  $15, $31
2191   write32<E>(Buf + 20, 0x0018c082); // srl   $24, $24, 2
2192   write32<E>(Buf + 24, 0x0320f809); // jalr  $25
2193   write32<E>(Buf + 28, 0x2718fffe); // subu  $24, $24, 2
2194 
2195   uint64_t GotPlt = In<ELFT>::GotPlt->getVA();
2196   writeMipsHi16<E>(Buf, GotPlt);
2197   writeMipsLo16<E>(Buf + 4, GotPlt);
2198   writeMipsLo16<E>(Buf + 8, GotPlt);
2199 }
2200 
2201 template <class ELFT>
2202 void MipsTargetInfo<ELFT>::writePlt(uint8_t *Buf, uint64_t GotPltEntryAddr,
2203                                     uint64_t PltEntryAddr, int32_t Index,
2204                                     unsigned RelOff) const {
2205   const endianness E = ELFT::TargetEndianness;
2206   write32<E>(Buf, 0x3c0f0000);     // lui   $15, %hi(.got.plt entry)
2207   write32<E>(Buf + 4, 0x8df90000); // l[wd] $25, %lo(.got.plt entry)($15)
2208                                    // jr    $25
2209   write32<E>(Buf + 8, isMipsR6<ELFT>() ? 0x03200009 : 0x03200008);
2210   write32<E>(Buf + 12, 0x25f80000); // addiu $24, $15, %lo(.got.plt entry)
2211   writeMipsHi16<E>(Buf, GotPltEntryAddr);
2212   writeMipsLo16<E>(Buf + 4, GotPltEntryAddr);
2213   writeMipsLo16<E>(Buf + 12, GotPltEntryAddr);
2214 }
2215 
2216 template <class ELFT>
2217 bool MipsTargetInfo<ELFT>::needsThunk(RelExpr Expr, uint32_t Type,
2218                                       const InputFile *File,
2219                                       const SymbolBody &S) const {
2220   // Any MIPS PIC code function is invoked with its address in register $t9.
2221   // So if we have a branch instruction from non-PIC code to the PIC one
2222   // we cannot make the jump directly and need to create a small stubs
2223   // to save the target function address.
2224   // See page 3-38 ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
2225   if (Type != R_MIPS_26)
2226     return false;
2227   auto *F = dyn_cast_or_null<ELFFileBase<ELFT>>(File);
2228   if (!F)
2229     return false;
2230   // If current file has PIC code, LA25 stub is not required.
2231   if (F->getObj().getHeader()->e_flags & EF_MIPS_PIC)
2232     return false;
2233   auto *D = dyn_cast<DefinedRegular>(&S);
2234   // LA25 is required if target file has PIC code
2235   // or target symbol is a PIC symbol.
2236   return D && D->isMipsPIC<ELFT>();
2237 }
2238 
2239 template <class ELFT>
2240 int64_t MipsTargetInfo<ELFT>::getImplicitAddend(const uint8_t *Buf,
2241                                                 uint32_t Type) const {
2242   const endianness E = ELFT::TargetEndianness;
2243   switch (Type) {
2244   default:
2245     return 0;
2246   case R_MIPS_32:
2247   case R_MIPS_GPREL32:
2248   case R_MIPS_TLS_DTPREL32:
2249   case R_MIPS_TLS_TPREL32:
2250     return SignExtend64<32>(read32<E>(Buf));
2251   case R_MIPS_26:
2252     // FIXME (simon): If the relocation target symbol is not a PLT entry
2253     // we should use another expression for calculation:
2254     // ((A << 2) | (P & 0xf0000000)) >> 2
2255     return SignExtend64<28>((read32<E>(Buf) & 0x3ffffff) << 2);
2256   case R_MIPS_GPREL16:
2257   case R_MIPS_LO16:
2258   case R_MIPS_PCLO16:
2259   case R_MIPS_TLS_DTPREL_HI16:
2260   case R_MIPS_TLS_DTPREL_LO16:
2261   case R_MIPS_TLS_TPREL_HI16:
2262   case R_MIPS_TLS_TPREL_LO16:
2263     return SignExtend64<16>(read32<E>(Buf));
2264   case R_MIPS_PC16:
2265     return getPcRelocAddend<E, 16, 2>(Buf);
2266   case R_MIPS_PC19_S2:
2267     return getPcRelocAddend<E, 19, 2>(Buf);
2268   case R_MIPS_PC21_S2:
2269     return getPcRelocAddend<E, 21, 2>(Buf);
2270   case R_MIPS_PC26_S2:
2271     return getPcRelocAddend<E, 26, 2>(Buf);
2272   case R_MIPS_PC32:
2273     return getPcRelocAddend<E, 32, 0>(Buf);
2274   }
2275 }
2276 
2277 static std::pair<uint32_t, uint64_t>
2278 calculateMipsRelChain(uint8_t *Loc, uint32_t Type, uint64_t Val) {
2279   // MIPS N64 ABI packs multiple relocations into the single relocation
2280   // record. In general, all up to three relocations can have arbitrary
2281   // types. In fact, Clang and GCC uses only a few combinations. For now,
2282   // we support two of them. That is allow to pass at least all LLVM
2283   // test suite cases.
2284   // <any relocation> / R_MIPS_SUB / R_MIPS_HI16 | R_MIPS_LO16
2285   // <any relocation> / R_MIPS_64 / R_MIPS_NONE
2286   // The first relocation is a 'real' relocation which is calculated
2287   // using the corresponding symbol's value. The second and the third
2288   // relocations used to modify result of the first one: extend it to
2289   // 64-bit, extract high or low part etc. For details, see part 2.9 Relocation
2290   // at the https://dmz-portal.mips.com/mw/images/8/82/007-4658-001.pdf
2291   uint32_t Type2 = (Type >> 8) & 0xff;
2292   uint32_t Type3 = (Type >> 16) & 0xff;
2293   if (Type2 == R_MIPS_NONE && Type3 == R_MIPS_NONE)
2294     return std::make_pair(Type, Val);
2295   if (Type2 == R_MIPS_64 && Type3 == R_MIPS_NONE)
2296     return std::make_pair(Type2, Val);
2297   if (Type2 == R_MIPS_SUB && (Type3 == R_MIPS_HI16 || Type3 == R_MIPS_LO16))
2298     return std::make_pair(Type3, -Val);
2299   error(getErrorLocation(Loc) + "unsupported relocations combination " +
2300         Twine(Type));
2301   return std::make_pair(Type & 0xff, Val);
2302 }
2303 
2304 template <class ELFT>
2305 void MipsTargetInfo<ELFT>::relocateOne(uint8_t *Loc, uint32_t Type,
2306                                        uint64_t Val) const {
2307   const endianness E = ELFT::TargetEndianness;
2308   // Thread pointer and DRP offsets from the start of TLS data area.
2309   // https://www.linux-mips.org/wiki/NPTL
2310   if (Type == R_MIPS_TLS_DTPREL_HI16 || Type == R_MIPS_TLS_DTPREL_LO16 ||
2311       Type == R_MIPS_TLS_DTPREL32 || Type == R_MIPS_TLS_DTPREL64)
2312     Val -= 0x8000;
2313   else if (Type == R_MIPS_TLS_TPREL_HI16 || Type == R_MIPS_TLS_TPREL_LO16 ||
2314            Type == R_MIPS_TLS_TPREL32 || Type == R_MIPS_TLS_TPREL64)
2315     Val -= 0x7000;
2316   if (ELFT::Is64Bits || Config->MipsN32Abi)
2317     std::tie(Type, Val) = calculateMipsRelChain(Loc, Type, Val);
2318   switch (Type) {
2319   case R_MIPS_32:
2320   case R_MIPS_GPREL32:
2321   case R_MIPS_TLS_DTPREL32:
2322   case R_MIPS_TLS_TPREL32:
2323     write32<E>(Loc, Val);
2324     break;
2325   case R_MIPS_64:
2326   case R_MIPS_TLS_DTPREL64:
2327   case R_MIPS_TLS_TPREL64:
2328     write64<E>(Loc, Val);
2329     break;
2330   case R_MIPS_26:
2331     write32<E>(Loc, (read32<E>(Loc) & ~0x3ffffff) | ((Val >> 2) & 0x3ffffff));
2332     break;
2333   case R_MIPS_GOT16:
2334     // The R_MIPS_GOT16 relocation's value in "relocatable" linking mode
2335     // is updated addend (not a GOT index). In that case write high 16 bits
2336     // to store a correct addend value.
2337     if (Config->Relocatable)
2338       writeMipsHi16<E>(Loc, Val);
2339     else {
2340       checkInt<16>(Loc, Val, Type);
2341       writeMipsLo16<E>(Loc, Val);
2342     }
2343     break;
2344   case R_MIPS_GOT_DISP:
2345   case R_MIPS_GOT_PAGE:
2346   case R_MIPS_GPREL16:
2347   case R_MIPS_TLS_GD:
2348   case R_MIPS_TLS_LDM:
2349     checkInt<16>(Loc, Val, Type);
2350   // fallthrough
2351   case R_MIPS_CALL16:
2352   case R_MIPS_CALL_LO16:
2353   case R_MIPS_GOT_LO16:
2354   case R_MIPS_GOT_OFST:
2355   case R_MIPS_LO16:
2356   case R_MIPS_PCLO16:
2357   case R_MIPS_TLS_DTPREL_LO16:
2358   case R_MIPS_TLS_GOTTPREL:
2359   case R_MIPS_TLS_TPREL_LO16:
2360     writeMipsLo16<E>(Loc, Val);
2361     break;
2362   case R_MIPS_CALL_HI16:
2363   case R_MIPS_GOT_HI16:
2364   case R_MIPS_HI16:
2365   case R_MIPS_PCHI16:
2366   case R_MIPS_TLS_DTPREL_HI16:
2367   case R_MIPS_TLS_TPREL_HI16:
2368     writeMipsHi16<E>(Loc, Val);
2369     break;
2370   case R_MIPS_HIGHER:
2371     writeMipsHigher<E>(Loc, Val);
2372     break;
2373   case R_MIPS_HIGHEST:
2374     writeMipsHighest<E>(Loc, Val);
2375     break;
2376   case R_MIPS_JALR:
2377     // Ignore this optimization relocation for now
2378     break;
2379   case R_MIPS_PC16:
2380     applyMipsPcReloc<E, 16, 2>(Loc, Type, Val);
2381     break;
2382   case R_MIPS_PC19_S2:
2383     applyMipsPcReloc<E, 19, 2>(Loc, Type, Val);
2384     break;
2385   case R_MIPS_PC21_S2:
2386     applyMipsPcReloc<E, 21, 2>(Loc, Type, Val);
2387     break;
2388   case R_MIPS_PC26_S2:
2389     applyMipsPcReloc<E, 26, 2>(Loc, Type, Val);
2390     break;
2391   case R_MIPS_PC32:
2392     applyMipsPcReloc<E, 32, 0>(Loc, Type, Val);
2393     break;
2394   default:
2395     error(getErrorLocation(Loc) + "unrecognized reloc " + Twine(Type));
2396   }
2397 }
2398 
2399 template <class ELFT>
2400 bool MipsTargetInfo<ELFT>::usesOnlyLowPageBits(uint32_t Type) const {
2401   return Type == R_MIPS_LO16 || Type == R_MIPS_GOT_OFST;
2402 }
2403 }
2404 }
2405