]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lld/ELF/Thunks.cpp
MFV r350898: 8423 8199 7432 Implement large_dnode pool feature
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lld / ELF / Thunks.cpp
1 //===- Thunks.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 // This file contains Thunk subclasses.
11 //
12 // A thunk is a small piece of code written after an input section
13 // which is used to jump between "incompatible" functions
14 // such as MIPS PIC and non-PIC or ARM non-Thumb and Thumb functions.
15 //
16 // If a jump target is too far and its address doesn't fit to a
17 // short jump instruction, we need to create a thunk too, but we
18 // haven't supported it yet.
19 //
20 // i386 and x86-64 don't need thunks.
21 //
22 //===---------------------------------------------------------------------===//
23
24 #include "Thunks.h"
25 #include "Config.h"
26 #include "InputSection.h"
27 #include "OutputSections.h"
28 #include "Symbols.h"
29 #include "SyntheticSections.h"
30 #include "Target.h"
31 #include "lld/Common/ErrorHandler.h"
32 #include "lld/Common/Memory.h"
33 #include "llvm/BinaryFormat/ELF.h"
34 #include "llvm/Support/Casting.h"
35 #include "llvm/Support/Endian.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include <cstdint>
39 #include <cstring>
40
41 using namespace llvm;
42 using namespace llvm::object;
43 using namespace llvm::ELF;
44
45 namespace lld {
46 namespace elf {
47
48 namespace {
49
50 // AArch64 long range Thunks
51 class AArch64ABSLongThunk final : public Thunk {
52 public:
53   AArch64ABSLongThunk(Symbol &Dest) : Thunk(Dest) {}
54   uint32_t size() override { return 16; }
55   void writeTo(uint8_t *Buf) override;
56   void addSymbols(ThunkSection &IS) override;
57 };
58
59 class AArch64ADRPThunk final : public Thunk {
60 public:
61   AArch64ADRPThunk(Symbol &Dest) : Thunk(Dest) {}
62   uint32_t size() override { return 12; }
63   void writeTo(uint8_t *Buf) override;
64   void addSymbols(ThunkSection &IS) override;
65 };
66
67 // Base class for ARM thunks.
68 //
69 // An ARM thunk may be either short or long. A short thunk is simply a branch
70 // (B) instruction, and it may be used to call ARM functions when the distance
71 // from the thunk to the target is less than 32MB. Long thunks can branch to any
72 // virtual address and can switch between ARM and Thumb, and they are
73 // implemented in the derived classes. This class tries to create a short thunk
74 // if the target is in range, otherwise it creates a long thunk.
75 class ARMThunk : public Thunk {
76 public:
77   ARMThunk(Symbol &Dest) : Thunk(Dest) {}
78
79   bool mayUseShortThunk();
80   uint32_t size() override { return mayUseShortThunk() ? 4 : sizeLong(); }
81   void writeTo(uint8_t *Buf) override;
82   bool isCompatibleWith(RelType Type) const override;
83
84   // Returns the size of a long thunk.
85   virtual uint32_t sizeLong() = 0;
86
87   // Writes a long thunk to Buf.
88   virtual void writeLong(uint8_t *Buf) = 0;
89
90 private:
91   // This field tracks whether all previously considered layouts would allow
92   // this thunk to be short. If we have ever needed a long thunk, we always
93   // create a long thunk, even if the thunk may be short given the current
94   // distance to the target. We do this because transitioning from long to short
95   // can create layout oscillations in certain corner cases which would prevent
96   // the layout from converging.
97   bool MayUseShortThunk = true;
98 };
99
100 // Base class for Thumb-2 thunks.
101 //
102 // This class is similar to ARMThunk, but it uses the Thumb-2 B.W instruction
103 // which has a range of 16MB.
104 class ThumbThunk : public Thunk {
105 public:
106   ThumbThunk(Symbol &Dest) : Thunk(Dest) { Alignment = 2; }
107
108   bool mayUseShortThunk();
109   uint32_t size() override { return mayUseShortThunk() ? 4 : sizeLong(); }
110   void writeTo(uint8_t *Buf) override;
111   bool isCompatibleWith(RelType Type) const override;
112
113   // Returns the size of a long thunk.
114   virtual uint32_t sizeLong() = 0;
115
116   // Writes a long thunk to Buf.
117   virtual void writeLong(uint8_t *Buf) = 0;
118
119 private:
120   // See comment in ARMThunk above.
121   bool MayUseShortThunk = true;
122 };
123
124 // Specific ARM Thunk implementations. The naming convention is:
125 // Source State, TargetState, Target Requirement, ABS or PI, Range
126 class ARMV7ABSLongThunk final : public ARMThunk {
127 public:
128   ARMV7ABSLongThunk(Symbol &Dest) : ARMThunk(Dest) {}
129
130   uint32_t sizeLong() override { return 12; }
131   void writeLong(uint8_t *Buf) override;
132   void addSymbols(ThunkSection &IS) override;
133 };
134
135 class ARMV7PILongThunk final : public ARMThunk {
136 public:
137   ARMV7PILongThunk(Symbol &Dest) : ARMThunk(Dest) {}
138
139   uint32_t sizeLong() override { return 16; }
140   void writeLong(uint8_t *Buf) override;
141   void addSymbols(ThunkSection &IS) override;
142 };
143
144 class ThumbV7ABSLongThunk final : public ThumbThunk {
145 public:
146   ThumbV7ABSLongThunk(Symbol &Dest) : ThumbThunk(Dest) {}
147
148   uint32_t sizeLong() override { return 10; }
149   void writeLong(uint8_t *Buf) override;
150   void addSymbols(ThunkSection &IS) override;
151 };
152
153 class ThumbV7PILongThunk final : public ThumbThunk {
154 public:
155   ThumbV7PILongThunk(Symbol &Dest) : ThumbThunk(Dest) {}
156
157   uint32_t sizeLong() override { return 12; }
158   void writeLong(uint8_t *Buf) override;
159   void addSymbols(ThunkSection &IS) override;
160 };
161
162 // Implementations of Thunks for older Arm architectures that do not support
163 // the movt/movw instructions. These thunks require at least Architecture v5
164 // as used on processors such as the Arm926ej-s. There are no Thumb entry
165 // points as there is no Thumb branch instruction on these architecture that
166 // can result in a thunk
167 class ARMV5ABSLongThunk final : public ARMThunk {
168 public:
169   ARMV5ABSLongThunk(Symbol &Dest) : ARMThunk(Dest) {}
170
171   uint32_t sizeLong() override { return 8; }
172   void writeLong(uint8_t *Buf) override;
173   void addSymbols(ThunkSection &IS) override;
174   bool isCompatibleWith(uint32_t RelocType) const override;
175 };
176
177 class ARMV5PILongThunk final : public ARMThunk {
178 public:
179   ARMV5PILongThunk(Symbol &Dest) : ARMThunk(Dest) {}
180
181   uint32_t sizeLong() override { return 16; }
182   void writeLong(uint8_t *Buf) override;
183   void addSymbols(ThunkSection &IS) override;
184   bool isCompatibleWith(uint32_t RelocType) const override;
185 };
186
187 // Implementations of Thunks for Arm v6-M. Only Thumb instructions are permitted
188 class ThumbV6MABSLongThunk final : public ThumbThunk {
189 public:
190   ThumbV6MABSLongThunk(Symbol &Dest) : ThumbThunk(Dest) {}
191
192   uint32_t sizeLong() override { return 12; }
193   void writeLong(uint8_t *Buf) override;
194   void addSymbols(ThunkSection &IS) override;
195 };
196
197 class ThumbV6MPILongThunk final : public ThumbThunk {
198 public:
199   ThumbV6MPILongThunk(Symbol &Dest) : ThumbThunk(Dest) {}
200
201   uint32_t sizeLong() override { return 16; }
202   void writeLong(uint8_t *Buf) override;
203   void addSymbols(ThunkSection &IS) override;
204 };
205
206 // MIPS LA25 thunk
207 class MipsThunk final : public Thunk {
208 public:
209   MipsThunk(Symbol &Dest) : Thunk(Dest) {}
210
211   uint32_t size() override { return 16; }
212   void writeTo(uint8_t *Buf) override;
213   void addSymbols(ThunkSection &IS) override;
214   InputSection *getTargetInputSection() const override;
215 };
216
217 // microMIPS R2-R5 LA25 thunk
218 class MicroMipsThunk final : public Thunk {
219 public:
220   MicroMipsThunk(Symbol &Dest) : Thunk(Dest) {}
221
222   uint32_t size() override { return 14; }
223   void writeTo(uint8_t *Buf) override;
224   void addSymbols(ThunkSection &IS) override;
225   InputSection *getTargetInputSection() const override;
226 };
227
228 // microMIPS R6 LA25 thunk
229 class MicroMipsR6Thunk final : public Thunk {
230 public:
231   MicroMipsR6Thunk(Symbol &Dest) : Thunk(Dest) {}
232
233   uint32_t size() override { return 12; }
234   void writeTo(uint8_t *Buf) override;
235   void addSymbols(ThunkSection &IS) override;
236   InputSection *getTargetInputSection() const override;
237 };
238
239
240 // PPC64 Plt call stubs.
241 // Any call site that needs to call through a plt entry needs a call stub in
242 // the .text section. The call stub is responsible for:
243 // 1) Saving the toc-pointer to the stack.
244 // 2) Loading the target functions address from the procedure linkage table into
245 //    r12 for use by the target functions global entry point, and into the count
246 //    register.
247 // 3) Transfering control to the target function through an indirect branch.
248 class PPC64PltCallStub final : public Thunk {
249 public:
250   PPC64PltCallStub(Symbol &Dest) : Thunk(Dest) {}
251   uint32_t size() override { return 20; }
252   void writeTo(uint8_t *Buf) override;
253   void addSymbols(ThunkSection &IS) override;
254 };
255
256 // A bl instruction uses a signed 24 bit offset, with an implicit 4 byte
257 // alignment. This gives a possible 26 bits of 'reach'. If the call offset is
258 // larger then that we need to emit a long-branch thunk. The target address
259 // of the callee is stored in a table to be accessed TOC-relative. Since the
260 // call must be local (a non-local call will have a PltCallStub instead) the
261 // table stores the address of the callee's local entry point. For
262 // position-independent code a corresponding relative dynamic relocation is
263 // used.
264 class PPC64LongBranchThunk : public Thunk {
265 public:
266   uint32_t size() override { return 16; }
267   void writeTo(uint8_t *Buf) override;
268   void addSymbols(ThunkSection &IS) override;
269
270 protected:
271   PPC64LongBranchThunk(Symbol &Dest) : Thunk(Dest) {}
272 };
273
274 class PPC64PILongBranchThunk final : public PPC64LongBranchThunk {
275 public:
276   PPC64PILongBranchThunk(Symbol &Dest) : PPC64LongBranchThunk(Dest) {
277     assert(!Dest.IsPreemptible);
278     if (Dest.isInPPC64Branchlt())
279       return;
280
281     In.PPC64LongBranchTarget->addEntry(Dest);
282     In.RelaDyn->addReloc({Target->RelativeRel, In.PPC64LongBranchTarget,
283                           Dest.getPPC64LongBranchOffset(), true, &Dest,
284                           getPPC64GlobalEntryToLocalEntryOffset(Dest.StOther)});
285   }
286 };
287
288 class PPC64PDLongBranchThunk final : public PPC64LongBranchThunk {
289 public:
290   PPC64PDLongBranchThunk(Symbol &Dest) : PPC64LongBranchThunk(Dest) {
291     if (!Dest.isInPPC64Branchlt())
292       In.PPC64LongBranchTarget->addEntry(Dest);
293   }
294 };
295
296 } // end anonymous namespace
297
298 Defined *Thunk::addSymbol(StringRef Name, uint8_t Type, uint64_t Value,
299                           InputSectionBase &Section) {
300   Defined *D = addSyntheticLocal(Name, Type, Value, /*Size=*/0, Section);
301   Syms.push_back(D);
302   return D;
303 }
304
305 void Thunk::setOffset(uint64_t NewOffset) {
306   for (Defined *D : Syms)
307     D->Value = D->Value - Offset + NewOffset;
308   Offset = NewOffset;
309 }
310
311 // AArch64 long range Thunks
312
313 static uint64_t getAArch64ThunkDestVA(const Symbol &S) {
314   uint64_t V = S.isInPlt() ? S.getPltVA() : S.getVA();
315   return V;
316 }
317
318 void AArch64ABSLongThunk::writeTo(uint8_t *Buf) {
319   const uint8_t Data[] = {
320     0x50, 0x00, 0x00, 0x58, //     ldr x16, L0
321     0x00, 0x02, 0x1f, 0xd6, //     br  x16
322     0x00, 0x00, 0x00, 0x00, // L0: .xword S
323     0x00, 0x00, 0x00, 0x00,
324   };
325   uint64_t S = getAArch64ThunkDestVA(Destination);
326   memcpy(Buf, Data, sizeof(Data));
327   Target->relocateOne(Buf + 8, R_AARCH64_ABS64, S);
328 }
329
330 void AArch64ABSLongThunk::addSymbols(ThunkSection &IS) {
331   addSymbol(Saver.save("__AArch64AbsLongThunk_" + Destination.getName()),
332             STT_FUNC, 0, IS);
333   addSymbol("$x", STT_NOTYPE, 0, IS);
334   addSymbol("$d", STT_NOTYPE, 8, IS);
335 }
336
337 // This Thunk has a maximum range of 4Gb, this is sufficient for all programs
338 // using the small code model, including pc-relative ones. At time of writing
339 // clang and gcc do not support the large code model for position independent
340 // code so it is safe to use this for position independent thunks without
341 // worrying about the destination being more than 4Gb away.
342 void AArch64ADRPThunk::writeTo(uint8_t *Buf) {
343   const uint8_t Data[] = {
344       0x10, 0x00, 0x00, 0x90, // adrp x16, Dest R_AARCH64_ADR_PREL_PG_HI21(Dest)
345       0x10, 0x02, 0x00, 0x91, // add  x16, x16, R_AARCH64_ADD_ABS_LO12_NC(Dest)
346       0x00, 0x02, 0x1f, 0xd6, // br   x16
347   };
348   uint64_t S = getAArch64ThunkDestVA(Destination);
349   uint64_t P = getThunkTargetSym()->getVA();
350   memcpy(Buf, Data, sizeof(Data));
351   Target->relocateOne(Buf, R_AARCH64_ADR_PREL_PG_HI21,
352                       getAArch64Page(S) - getAArch64Page(P));
353   Target->relocateOne(Buf + 4, R_AARCH64_ADD_ABS_LO12_NC, S);
354 }
355
356 void AArch64ADRPThunk::addSymbols(ThunkSection &IS) {
357   addSymbol(Saver.save("__AArch64ADRPThunk_" + Destination.getName()), STT_FUNC,
358             0, IS);
359   addSymbol("$x", STT_NOTYPE, 0, IS);
360 }
361
362 // ARM Target Thunks
363 static uint64_t getARMThunkDestVA(const Symbol &S) {
364   uint64_t V = S.isInPlt() ? S.getPltVA() : S.getVA();
365   return SignExtend64<32>(V);
366 }
367
368 // This function returns true if the target is not Thumb and is within 2^26, and
369 // it has not previously returned false (see comment for MayUseShortThunk).
370 bool ARMThunk::mayUseShortThunk() {
371   if (!MayUseShortThunk)
372     return false;
373   uint64_t S = getARMThunkDestVA(Destination);
374   if (S & 1) {
375     MayUseShortThunk = false;
376     return false;
377   }
378   uint64_t P = getThunkTargetSym()->getVA();
379   int64_t Offset = S - P - 8;
380   MayUseShortThunk = llvm::isInt<26>(Offset);
381   return MayUseShortThunk;
382 }
383
384 void ARMThunk::writeTo(uint8_t *Buf) {
385   if (!mayUseShortThunk()) {
386     writeLong(Buf);
387     return;
388   }
389
390   uint64_t S = getARMThunkDestVA(Destination);
391   uint64_t P = getThunkTargetSym()->getVA();
392   int64_t Offset = S - P - 8;
393   const uint8_t Data[] = {
394     0x00, 0x00, 0x00, 0xea, // b S
395   };
396   memcpy(Buf, Data, sizeof(Data));
397   Target->relocateOne(Buf, R_ARM_JUMP24, Offset);
398 }
399
400 bool ARMThunk::isCompatibleWith(RelType Type) const {
401   // Thumb branch relocations can't use BLX
402   return Type != R_ARM_THM_JUMP19 && Type != R_ARM_THM_JUMP24;
403 }
404
405 // This function returns true if the target is Thumb and is within 2^25, and
406 // it has not previously returned false (see comment for MayUseShortThunk).
407 bool ThumbThunk::mayUseShortThunk() {
408   if (!MayUseShortThunk)
409     return false;
410   uint64_t S = getARMThunkDestVA(Destination);
411   if ((S & 1) == 0) {
412     MayUseShortThunk = false;
413     return false;
414   }
415   uint64_t P = getThunkTargetSym()->getVA() & ~1;
416   int64_t Offset = S - P - 4;
417   MayUseShortThunk = llvm::isInt<25>(Offset);
418   return MayUseShortThunk;
419 }
420
421 void ThumbThunk::writeTo(uint8_t *Buf) {
422   if (!mayUseShortThunk()) {
423     writeLong(Buf);
424     return;
425   }
426
427   uint64_t S = getARMThunkDestVA(Destination);
428   uint64_t P = getThunkTargetSym()->getVA();
429   int64_t Offset = S - P - 4;
430   const uint8_t Data[] = {
431       0x00, 0xf0, 0x00, 0xb0, // b.w S
432   };
433   memcpy(Buf, Data, sizeof(Data));
434   Target->relocateOne(Buf, R_ARM_THM_JUMP24, Offset);
435 }
436
437 bool ThumbThunk::isCompatibleWith(RelType Type) const {
438   // ARM branch relocations can't use BLX
439   return Type != R_ARM_JUMP24 && Type != R_ARM_PC24 && Type != R_ARM_PLT32;
440 }
441
442 void ARMV7ABSLongThunk::writeLong(uint8_t *Buf) {
443   const uint8_t Data[] = {
444       0x00, 0xc0, 0x00, 0xe3, // movw         ip,:lower16:S
445       0x00, 0xc0, 0x40, 0xe3, // movt         ip,:upper16:S
446       0x1c, 0xff, 0x2f, 0xe1, // bx   ip
447   };
448   uint64_t S = getARMThunkDestVA(Destination);
449   memcpy(Buf, Data, sizeof(Data));
450   Target->relocateOne(Buf, R_ARM_MOVW_ABS_NC, S);
451   Target->relocateOne(Buf + 4, R_ARM_MOVT_ABS, S);
452 }
453
454 void ARMV7ABSLongThunk::addSymbols(ThunkSection &IS) {
455   addSymbol(Saver.save("__ARMv7ABSLongThunk_" + Destination.getName()),
456             STT_FUNC, 0, IS);
457   addSymbol("$a", STT_NOTYPE, 0, IS);
458 }
459
460 void ThumbV7ABSLongThunk::writeLong(uint8_t *Buf) {
461   const uint8_t Data[] = {
462       0x40, 0xf2, 0x00, 0x0c, // movw         ip, :lower16:S
463       0xc0, 0xf2, 0x00, 0x0c, // movt         ip, :upper16:S
464       0x60, 0x47,             // bx   ip
465   };
466   uint64_t S = getARMThunkDestVA(Destination);
467   memcpy(Buf, Data, sizeof(Data));
468   Target->relocateOne(Buf, R_ARM_THM_MOVW_ABS_NC, S);
469   Target->relocateOne(Buf + 4, R_ARM_THM_MOVT_ABS, S);
470 }
471
472 void ThumbV7ABSLongThunk::addSymbols(ThunkSection &IS) {
473   addSymbol(Saver.save("__Thumbv7ABSLongThunk_" + Destination.getName()),
474             STT_FUNC, 1, IS);
475   addSymbol("$t", STT_NOTYPE, 0, IS);
476 }
477
478 void ARMV7PILongThunk::writeLong(uint8_t *Buf) {
479   const uint8_t Data[] = {
480       0xf0, 0xcf, 0x0f, 0xe3, // P:  movw ip,:lower16:S - (P + (L1-P) + 8)
481       0x00, 0xc0, 0x40, 0xe3, //     movt ip,:upper16:S - (P + (L1-P) + 8)
482       0x0f, 0xc0, 0x8c, 0xe0, // L1: add  ip, ip, pc
483       0x1c, 0xff, 0x2f, 0xe1, //     bx   ip
484   };
485   uint64_t S = getARMThunkDestVA(Destination);
486   uint64_t P = getThunkTargetSym()->getVA();
487   int64_t Offset = S - P - 16;
488   memcpy(Buf, Data, sizeof(Data));
489   Target->relocateOne(Buf, R_ARM_MOVW_PREL_NC, Offset);
490   Target->relocateOne(Buf + 4, R_ARM_MOVT_PREL, Offset);
491 }
492
493 void ARMV7PILongThunk::addSymbols(ThunkSection &IS) {
494   addSymbol(Saver.save("__ARMV7PILongThunk_" + Destination.getName()), STT_FUNC,
495             0, IS);
496   addSymbol("$a", STT_NOTYPE, 0, IS);
497 }
498
499 void ThumbV7PILongThunk::writeLong(uint8_t *Buf) {
500   const uint8_t Data[] = {
501       0x4f, 0xf6, 0xf4, 0x7c, // P:  movw ip,:lower16:S - (P + (L1-P) + 4)
502       0xc0, 0xf2, 0x00, 0x0c, //     movt ip,:upper16:S - (P + (L1-P) + 4)
503       0xfc, 0x44,             // L1: add  ip, pc
504       0x60, 0x47,             //     bx   ip
505   };
506   uint64_t S = getARMThunkDestVA(Destination);
507   uint64_t P = getThunkTargetSym()->getVA() & ~0x1;
508   int64_t Offset = S - P - 12;
509   memcpy(Buf, Data, sizeof(Data));
510   Target->relocateOne(Buf, R_ARM_THM_MOVW_PREL_NC, Offset);
511   Target->relocateOne(Buf + 4, R_ARM_THM_MOVT_PREL, Offset);
512 }
513
514 void ThumbV7PILongThunk::addSymbols(ThunkSection &IS) {
515   addSymbol(Saver.save("__ThumbV7PILongThunk_" + Destination.getName()),
516             STT_FUNC, 1, IS);
517   addSymbol("$t", STT_NOTYPE, 0, IS);
518 }
519
520 void ARMV5ABSLongThunk::writeLong(uint8_t *Buf) {
521   const uint8_t Data[] = {
522       0x04, 0xf0, 0x1f, 0xe5, //     ldr pc, [pc,#-4] ; L1
523       0x00, 0x00, 0x00, 0x00, // L1: .word S
524   };
525   memcpy(Buf, Data, sizeof(Data));
526   Target->relocateOne(Buf + 4, R_ARM_ABS32, getARMThunkDestVA(Destination));
527 }
528
529 void ARMV5ABSLongThunk::addSymbols(ThunkSection &IS) {
530   addSymbol(Saver.save("__ARMv5ABSLongThunk_" + Destination.getName()),
531             STT_FUNC, 0, IS);
532   addSymbol("$a", STT_NOTYPE, 0, IS);
533   addSymbol("$d", STT_NOTYPE, 4, IS);
534 }
535
536 bool ARMV5ABSLongThunk::isCompatibleWith(uint32_t RelocType) const {
537   // Thumb branch relocations can't use BLX
538   return RelocType != R_ARM_THM_JUMP19 && RelocType != R_ARM_THM_JUMP24;
539 }
540
541 void ARMV5PILongThunk::writeLong(uint8_t *Buf) {
542   const uint8_t Data[] = {
543       0x04, 0xc0, 0x9f, 0xe5, // P:  ldr ip, [pc,#4] ; L2
544       0x0c, 0xc0, 0x8f, 0xe0, // L1: add ip, pc, ip
545       0x1c, 0xff, 0x2f, 0xe1, //     bx ip
546       0x00, 0x00, 0x00, 0x00, // L2: .word S - (P + (L1 - P) + 8)
547   };
548   uint64_t S = getARMThunkDestVA(Destination);
549   uint64_t P = getThunkTargetSym()->getVA() & ~0x1;
550   memcpy(Buf, Data, sizeof(Data));
551   Target->relocateOne(Buf + 12, R_ARM_REL32, S - P - 12);
552 }
553
554 void ARMV5PILongThunk::addSymbols(ThunkSection &IS) {
555   addSymbol(Saver.save("__ARMV5PILongThunk_" + Destination.getName()), STT_FUNC,
556             0, IS);
557   addSymbol("$a", STT_NOTYPE, 0, IS);
558   addSymbol("$d", STT_NOTYPE, 12, IS);
559 }
560
561 bool ARMV5PILongThunk::isCompatibleWith(uint32_t RelocType) const {
562   // Thumb branch relocations can't use BLX
563   return RelocType != R_ARM_THM_JUMP19 && RelocType != R_ARM_THM_JUMP24;
564 }
565
566 void ThumbV6MABSLongThunk::writeLong(uint8_t *Buf) {
567   // Most Thumb instructions cannot access the high registers r8 - r15. As the
568   // only register we can corrupt is r12 we must instead spill a low register
569   // to the stack to use as a scratch register. We push r1 even though we
570   // don't need to get some space to use for the return address.
571   const uint8_t Data[] = {
572       0x03, 0xb4,            // push {r0, r1} ; Obtain scratch registers
573       0x01, 0x48,            // ldr r0, [pc, #4] ; L1
574       0x01, 0x90,            // str r0, [sp, #4] ; SP + 4 = S
575       0x01, 0xbd,            // pop {r0, pc} ; restore r0 and branch to dest
576       0x00, 0x00, 0x00, 0x00 // L1: .word S
577   };
578   uint64_t S = getARMThunkDestVA(Destination);
579   memcpy(Buf, Data, sizeof(Data));
580   Target->relocateOne(Buf + 8, R_ARM_ABS32, S);
581 }
582
583 void ThumbV6MABSLongThunk::addSymbols(ThunkSection &IS) {
584   addSymbol(Saver.save("__Thumbv6MABSLongThunk_" + Destination.getName()),
585             STT_FUNC, 1, IS);
586   addSymbol("$t", STT_NOTYPE, 0, IS);
587   addSymbol("$d", STT_NOTYPE, 8, IS);
588 }
589
590 void ThumbV6MPILongThunk::writeLong(uint8_t *Buf) {
591   // Most Thumb instructions cannot access the high registers r8 - r15. As the
592   // only register we can corrupt is ip (r12) we must instead spill a low
593   // register to the stack to use as a scratch register.
594   const uint8_t Data[] = {
595       0x01, 0xb4,             // P:  push {r0}        ; Obtain scratch register
596       0x02, 0x48,             //     ldr r0, [pc, #8] ; L2
597       0x84, 0x46,             //     mov ip, r0       ; high to low register
598       0x01, 0xbc,             //     pop {r0}         ; restore scratch register
599       0xe7, 0x44,             // L1: add pc, ip       ; transfer control
600       0xc0, 0x46,             //     nop              ; pad to 4-byte boundary
601       0x00, 0x00, 0x00, 0x00, // L2: .word S - (P + (L1 - P) + 4)
602   };
603   uint64_t S = getARMThunkDestVA(Destination);
604   uint64_t P = getThunkTargetSym()->getVA() & ~0x1;
605   memcpy(Buf, Data, sizeof(Data));
606   Target->relocateOne(Buf + 12, R_ARM_REL32, S - P - 12);
607 }
608
609 void ThumbV6MPILongThunk::addSymbols(ThunkSection &IS) {
610   addSymbol(Saver.save("__Thumbv6MPILongThunk_" + Destination.getName()),
611             STT_FUNC, 1, IS);
612   addSymbol("$t", STT_NOTYPE, 0, IS);
613   addSymbol("$d", STT_NOTYPE, 12, IS);
614 }
615
616 // Write MIPS LA25 thunk code to call PIC function from the non-PIC one.
617 void MipsThunk::writeTo(uint8_t *Buf) {
618   uint64_t S = Destination.getVA();
619   write32(Buf, 0x3c190000); // lui   $25, %hi(func)
620   write32(Buf + 4, 0x08000000 | (S >> 2)); // j     func
621   write32(Buf + 8, 0x27390000); // addiu $25, $25, %lo(func)
622   write32(Buf + 12, 0x00000000); // nop
623   Target->relocateOne(Buf, R_MIPS_HI16, S);
624   Target->relocateOne(Buf + 8, R_MIPS_LO16, S);
625 }
626
627 void MipsThunk::addSymbols(ThunkSection &IS) {
628   addSymbol(Saver.save("__LA25Thunk_" + Destination.getName()), STT_FUNC, 0,
629             IS);
630 }
631
632 InputSection *MipsThunk::getTargetInputSection() const {
633   auto &DR = cast<Defined>(Destination);
634   return dyn_cast<InputSection>(DR.Section);
635 }
636
637 // Write microMIPS R2-R5 LA25 thunk code
638 // to call PIC function from the non-PIC one.
639 void MicroMipsThunk::writeTo(uint8_t *Buf) {
640   uint64_t S = Destination.getVA() | 1;
641   write16(Buf, 0x41b9);       // lui   $25, %hi(func)
642   write16(Buf + 4, 0xd400);   // j     func
643   write16(Buf + 8, 0x3339);   // addiu $25, $25, %lo(func)
644   write16(Buf + 12, 0x0c00);  // nop
645   Target->relocateOne(Buf, R_MICROMIPS_HI16, S);
646   Target->relocateOne(Buf + 4, R_MICROMIPS_26_S1, S);
647   Target->relocateOne(Buf + 8, R_MICROMIPS_LO16, S);
648 }
649
650 void MicroMipsThunk::addSymbols(ThunkSection &IS) {
651   Defined *D = addSymbol(
652       Saver.save("__microLA25Thunk_" + Destination.getName()), STT_FUNC, 0, IS);
653   D->StOther |= STO_MIPS_MICROMIPS;
654 }
655
656 InputSection *MicroMipsThunk::getTargetInputSection() const {
657   auto &DR = cast<Defined>(Destination);
658   return dyn_cast<InputSection>(DR.Section);
659 }
660
661 // Write microMIPS R6 LA25 thunk code
662 // to call PIC function from the non-PIC one.
663 void MicroMipsR6Thunk::writeTo(uint8_t *Buf) {
664   uint64_t S = Destination.getVA() | 1;
665   uint64_t P = getThunkTargetSym()->getVA();
666   write16(Buf, 0x1320);       // lui   $25, %hi(func)
667   write16(Buf + 4, 0x3339);   // addiu $25, $25, %lo(func)
668   write16(Buf + 8, 0x9400);   // bc    func
669   Target->relocateOne(Buf, R_MICROMIPS_HI16, S);
670   Target->relocateOne(Buf + 4, R_MICROMIPS_LO16, S);
671   Target->relocateOne(Buf + 8, R_MICROMIPS_PC26_S1, S - P - 12);
672 }
673
674 void MicroMipsR6Thunk::addSymbols(ThunkSection &IS) {
675   Defined *D = addSymbol(
676       Saver.save("__microLA25Thunk_" + Destination.getName()), STT_FUNC, 0, IS);
677   D->StOther |= STO_MIPS_MICROMIPS;
678 }
679
680 InputSection *MicroMipsR6Thunk::getTargetInputSection() const {
681   auto &DR = cast<Defined>(Destination);
682   return dyn_cast<InputSection>(DR.Section);
683 }
684
685 static void writePPCLoadAndBranch(uint8_t *Buf, int64_t Offset) {
686   uint16_t OffHa = (Offset + 0x8000) >> 16;
687   uint16_t OffLo = Offset & 0xffff;
688
689   write32(Buf + 0, 0x3d820000 | OffHa); // addis r12, r2, OffHa
690   write32(Buf + 4, 0xe98c0000 | OffLo); // ld    r12, OffLo(r12)
691   write32(Buf + 8, 0x7d8903a6);         // mtctr r12
692   write32(Buf + 12, 0x4e800420);        // bctr
693 }
694
695 void PPC64PltCallStub::writeTo(uint8_t *Buf) {
696   int64_t Offset = Destination.getGotPltVA() - getPPC64TocBase();
697   // Save the TOC pointer to the save-slot reserved in the call frame.
698   write32(Buf + 0, 0xf8410018); // std     r2,24(r1)
699   writePPCLoadAndBranch(Buf + 4, Offset);
700 }
701
702 void PPC64PltCallStub::addSymbols(ThunkSection &IS) {
703   Defined *S = addSymbol(Saver.save("__plt_" + Destination.getName()), STT_FUNC,
704                          0, IS);
705   S->NeedsTocRestore = true;
706 }
707
708 void PPC64LongBranchThunk::writeTo(uint8_t *Buf) {
709   int64_t Offset = Destination.getPPC64LongBranchTableVA() - getPPC64TocBase();
710   writePPCLoadAndBranch(Buf, Offset);
711 }
712
713 void PPC64LongBranchThunk::addSymbols(ThunkSection &IS) {
714   addSymbol(Saver.save("__long_branch_" + Destination.getName()), STT_FUNC, 0,
715             IS);
716 }
717
718 Thunk::Thunk(Symbol &D) : Destination(D), Offset(0) {}
719
720 Thunk::~Thunk() = default;
721
722 static Thunk *addThunkAArch64(RelType Type, Symbol &S) {
723   if (Type != R_AARCH64_CALL26 && Type != R_AARCH64_JUMP26)
724     fatal("unrecognized relocation type");
725   if (Config->PicThunk)
726     return make<AArch64ADRPThunk>(S);
727   return make<AArch64ABSLongThunk>(S);
728 }
729
730 // Creates a thunk for Thumb-ARM interworking.
731 // Arm Architectures v5 and v6 do not support Thumb2 technology. This means
732 // - MOVT and MOVW instructions cannot be used
733 // - Only Thumb relocation that can generate a Thunk is a BL, this can always
734 //   be transformed into a BLX
735 static Thunk *addThunkPreArmv7(RelType Reloc, Symbol &S) {
736   switch (Reloc) {
737   case R_ARM_PC24:
738   case R_ARM_PLT32:
739   case R_ARM_JUMP24:
740   case R_ARM_CALL:
741   case R_ARM_THM_CALL:
742     if (Config->PicThunk)
743       return make<ARMV5PILongThunk>(S);
744     return make<ARMV5ABSLongThunk>(S);
745   }
746   fatal("relocation " + toString(Reloc) + " to " + toString(S) +
747         " not supported for Armv5 or Armv6 targets");
748 }
749
750 // Create a thunk for Thumb long branch on V6-M.
751 // Arm Architecture v6-M only supports Thumb instructions. This means
752 // - MOVT and MOVW instructions cannot be used.
753 // - Only a limited number of instructions can access registers r8 and above
754 // - No interworking support is needed (all Thumb).
755 static Thunk *addThunkV6M(RelType Reloc, Symbol &S) {
756   switch (Reloc) {
757   case R_ARM_THM_JUMP19:
758   case R_ARM_THM_JUMP24:
759   case R_ARM_THM_CALL:
760     if (Config->Pic)
761       return make<ThumbV6MPILongThunk>(S);
762     return make<ThumbV6MABSLongThunk>(S);
763   }
764   fatal("relocation " + toString(Reloc) + " to " + toString(S) +
765         " not supported for Armv6-M targets");
766 }
767
768 // Creates a thunk for Thumb-ARM interworking or branch range extension.
769 static Thunk *addThunkArm(RelType Reloc, Symbol &S) {
770   // Decide which Thunk is needed based on:
771   // Available instruction set
772   // - An Arm Thunk can only be used if Arm state is available.
773   // - A Thumb Thunk can only be used if Thumb state is available.
774   // - Can only use a Thunk if it uses instructions that the Target supports.
775   // Relocation is branch or branch and link
776   // - Branch instructions cannot change state, can only select Thunk that
777   //   starts in the same state as the caller.
778   // - Branch and link relocations can change state, can select Thunks from
779   //   either Arm or Thumb.
780   // Position independent Thunks if we require position independent code.
781
782   // Handle architectures that have restrictions on the instructions that they
783   // can use in Thunks. The flags below are set by reading the BuildAttributes
784   // of the input objects. InputFiles.cpp contains the mapping from ARM
785   // architecture to flag.
786   if (!Config->ARMHasMovtMovw) {
787     if (!Config->ARMJ1J2BranchEncoding)
788       return addThunkPreArmv7(Reloc, S);
789     return addThunkV6M(Reloc, S);
790   }
791
792   switch (Reloc) {
793   case R_ARM_PC24:
794   case R_ARM_PLT32:
795   case R_ARM_JUMP24:
796   case R_ARM_CALL:
797     if (Config->PicThunk)
798       return make<ARMV7PILongThunk>(S);
799     return make<ARMV7ABSLongThunk>(S);
800   case R_ARM_THM_JUMP19:
801   case R_ARM_THM_JUMP24:
802   case R_ARM_THM_CALL:
803     if (Config->PicThunk)
804       return make<ThumbV7PILongThunk>(S);
805     return make<ThumbV7ABSLongThunk>(S);
806   }
807   fatal("unrecognized relocation type");
808 }
809
810 static Thunk *addThunkMips(RelType Type, Symbol &S) {
811   if ((S.StOther & STO_MIPS_MICROMIPS) && isMipsR6())
812     return make<MicroMipsR6Thunk>(S);
813   if (S.StOther & STO_MIPS_MICROMIPS)
814     return make<MicroMipsThunk>(S);
815   return make<MipsThunk>(S);
816 }
817
818 static Thunk *addThunkPPC64(RelType Type, Symbol &S) {
819   assert(Type == R_PPC64_REL24 && "unexpected relocation type for thunk");
820   if (S.isInPlt())
821     return make<PPC64PltCallStub>(S);
822
823   if (Config->PicThunk)
824     return make<PPC64PILongBranchThunk>(S);
825
826   return make<PPC64PDLongBranchThunk>(S);
827 }
828
829 Thunk *addThunk(RelType Type, Symbol &S) {
830   if (Config->EMachine == EM_AARCH64)
831     return addThunkAArch64(Type, S);
832
833   if (Config->EMachine == EM_ARM)
834     return addThunkArm(Type, S);
835
836   if (Config->EMachine == EM_MIPS)
837     return addThunkMips(Type, S);
838
839   if (Config->EMachine == EM_PPC64)
840     return addThunkPPC64(Type, S);
841
842   llvm_unreachable("add Thunk only supported for ARM, Mips and PowerPC");
843 }
844
845 } // end namespace elf
846 } // end namespace lld