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