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