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