xref: /llvm-project-15.0.7/lld/ELF/Thunks.cpp (revision 2ea3c8a5)
1 //===- Thunks.cpp --------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===---------------------------------------------------------------------===//
8 //
9 // This file contains Thunk subclasses.
10 //
11 // A thunk is a small piece of code written after an input section
12 // which is used to jump between "incompatible" functions
13 // such as MIPS PIC and non-PIC or ARM non-Thumb and Thumb functions.
14 //
15 // If a jump target is too far and its address doesn't fit to a
16 // short jump instruction, we need to create a thunk too, but we
17 // haven't supported it yet.
18 //
19 // i386 and x86-64 don't need thunks.
20 //
21 //===---------------------------------------------------------------------===//
22 
23 #include "Thunks.h"
24 #include "Config.h"
25 #include "InputSection.h"
26 #include "OutputSections.h"
27 #include "Symbols.h"
28 #include "SyntheticSections.h"
29 #include "Target.h"
30 #include "lld/Common/ErrorHandler.h"
31 #include "lld/Common/Memory.h"
32 #include "llvm/BinaryFormat/ELF.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Support/Endian.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/MathExtras.h"
37 #include <cstdint>
38 #include <cstring>
39 
40 using namespace llvm;
41 using namespace llvm::object;
42 using namespace llvm::ELF;
43 using namespace lld;
44 using namespace lld::elf;
45 
46 namespace {
47 
48 // AArch64 long range Thunks
49 class AArch64ABSLongThunk final : public Thunk {
50 public:
51   AArch64ABSLongThunk(Symbol &dest, int64_t addend) : Thunk(dest, addend) {}
52   uint32_t size() override { return 16; }
53   void writeTo(uint8_t *buf) override;
54   void addSymbols(ThunkSection &isec) override;
55 };
56 
57 class AArch64ADRPThunk final : public Thunk {
58 public:
59   AArch64ADRPThunk(Symbol &dest, int64_t addend) : Thunk(dest, addend) {}
60   uint32_t size() override { return 12; }
61   void writeTo(uint8_t *buf) override;
62   void addSymbols(ThunkSection &isec) override;
63 };
64 
65 // Base class for ARM thunks.
66 //
67 // An ARM thunk may be either short or long. A short thunk is simply a branch
68 // (B) instruction, and it may be used to call ARM functions when the distance
69 // from the thunk to the target is less than 32MB. Long thunks can branch to any
70 // virtual address and can switch between ARM and Thumb, and they are
71 // implemented in the derived classes. This class tries to create a short thunk
72 // if the target is in range, otherwise it creates a long thunk.
73 class ARMThunk : public Thunk {
74 public:
75   ARMThunk(Symbol &dest, int64_t addend) : Thunk(dest, addend) {}
76 
77   bool getMayUseShortThunk();
78   uint32_t size() override { return getMayUseShortThunk() ? 4 : sizeLong(); }
79   void writeTo(uint8_t *buf) override;
80   bool isCompatibleWith(const InputSection &isec,
81                         const Relocation &rel) const override;
82 
83   // Returns the size of a long thunk.
84   virtual uint32_t sizeLong() = 0;
85 
86   // Writes a long thunk to Buf.
87   virtual void writeLong(uint8_t *buf) = 0;
88 
89 private:
90   // This field tracks whether all previously considered layouts would allow
91   // this thunk to be short. If we have ever needed a long thunk, we always
92   // create a long thunk, even if the thunk may be short given the current
93   // distance to the target. We do this because transitioning from long to short
94   // can create layout oscillations in certain corner cases which would prevent
95   // the layout from converging.
96   bool mayUseShortThunk = true;
97 };
98 
99 // Base class for Thumb-2 thunks.
100 //
101 // This class is similar to ARMThunk, but it uses the Thumb-2 B.W instruction
102 // which has a range of 16MB.
103 class ThumbThunk : public Thunk {
104 public:
105   ThumbThunk(Symbol &dest, int64_t addend) : Thunk(dest, addend) {
106     alignment = 2;
107   }
108 
109   bool getMayUseShortThunk();
110   uint32_t size() override { return getMayUseShortThunk() ? 4 : sizeLong(); }
111   void writeTo(uint8_t *buf) override;
112   bool isCompatibleWith(const InputSection &isec,
113                         const Relocation &rel) const override;
114 
115   // Returns the size of a long thunk.
116   virtual uint32_t sizeLong() = 0;
117 
118   // Writes a long thunk to Buf.
119   virtual void writeLong(uint8_t *buf) = 0;
120 
121 private:
122   // See comment in ARMThunk above.
123   bool mayUseShortThunk = true;
124 };
125 
126 // Specific ARM Thunk implementations. The naming convention is:
127 // Source State, TargetState, Target Requirement, ABS or PI, Range
128 class ARMV7ABSLongThunk final : public ARMThunk {
129 public:
130   ARMV7ABSLongThunk(Symbol &dest, int64_t addend) : ARMThunk(dest, addend) {}
131 
132   uint32_t sizeLong() override { return 12; }
133   void writeLong(uint8_t *buf) override;
134   void addSymbols(ThunkSection &isec) override;
135 };
136 
137 class ARMV7PILongThunk final : public ARMThunk {
138 public:
139   ARMV7PILongThunk(Symbol &dest, int64_t addend) : ARMThunk(dest, addend) {}
140 
141   uint32_t sizeLong() override { return 16; }
142   void writeLong(uint8_t *buf) override;
143   void addSymbols(ThunkSection &isec) override;
144 };
145 
146 class ThumbV7ABSLongThunk final : public ThumbThunk {
147 public:
148   ThumbV7ABSLongThunk(Symbol &dest, int64_t addend)
149       : ThumbThunk(dest, addend) {}
150 
151   uint32_t sizeLong() override { return 10; }
152   void writeLong(uint8_t *buf) override;
153   void addSymbols(ThunkSection &isec) override;
154 };
155 
156 class ThumbV7PILongThunk final : public ThumbThunk {
157 public:
158   ThumbV7PILongThunk(Symbol &dest, int64_t addend) : ThumbThunk(dest, addend) {}
159 
160   uint32_t sizeLong() override { return 12; }
161   void writeLong(uint8_t *buf) override;
162   void addSymbols(ThunkSection &isec) override;
163 };
164 
165 // Implementations of Thunks for older Arm architectures that do not support
166 // the movt/movw instructions. These thunks require at least Architecture v5
167 // as used on processors such as the Arm926ej-s. There are no Thumb entry
168 // points as there is no Thumb branch instruction on these architecture that
169 // can result in a thunk
170 class ARMV5ABSLongThunk final : public ARMThunk {
171 public:
172   ARMV5ABSLongThunk(Symbol &dest, int64_t addend) : ARMThunk(dest, addend) {}
173 
174   uint32_t sizeLong() override { return 8; }
175   void writeLong(uint8_t *buf) override;
176   void addSymbols(ThunkSection &isec) override;
177   bool isCompatibleWith(const InputSection &isec,
178                         const Relocation &rel) const override;
179 };
180 
181 class ARMV5PILongThunk final : public ARMThunk {
182 public:
183   ARMV5PILongThunk(Symbol &dest, int64_t addend) : ARMThunk(dest, addend) {}
184 
185   uint32_t sizeLong() override { return 16; }
186   void writeLong(uint8_t *buf) override;
187   void addSymbols(ThunkSection &isec) override;
188   bool isCompatibleWith(const InputSection &isec,
189                         const Relocation &rel) const override;
190 };
191 
192 // Implementations of Thunks for Arm v6-M. Only Thumb instructions are permitted
193 class ThumbV6MABSLongThunk final : public ThumbThunk {
194 public:
195   ThumbV6MABSLongThunk(Symbol &dest, int64_t addend)
196       : ThumbThunk(dest, addend) {}
197 
198   uint32_t sizeLong() override { return 12; }
199   void writeLong(uint8_t *buf) override;
200   void addSymbols(ThunkSection &isec) override;
201 };
202 
203 class ThumbV6MPILongThunk final : public ThumbThunk {
204 public:
205   ThumbV6MPILongThunk(Symbol &dest, int64_t addend)
206       : ThumbThunk(dest, addend) {}
207 
208   uint32_t sizeLong() override { return 16; }
209   void writeLong(uint8_t *buf) override;
210   void addSymbols(ThunkSection &isec) override;
211 };
212 
213 // MIPS LA25 thunk
214 class MipsThunk final : public Thunk {
215 public:
216   MipsThunk(Symbol &dest) : Thunk(dest, 0) {}
217 
218   uint32_t size() override { return 16; }
219   void writeTo(uint8_t *buf) override;
220   void addSymbols(ThunkSection &isec) override;
221   InputSection *getTargetInputSection() const override;
222 };
223 
224 // microMIPS R2-R5 LA25 thunk
225 class MicroMipsThunk final : public Thunk {
226 public:
227   MicroMipsThunk(Symbol &dest) : Thunk(dest, 0) {}
228 
229   uint32_t size() override { return 14; }
230   void writeTo(uint8_t *buf) override;
231   void addSymbols(ThunkSection &isec) override;
232   InputSection *getTargetInputSection() const override;
233 };
234 
235 // microMIPS R6 LA25 thunk
236 class MicroMipsR6Thunk final : public Thunk {
237 public:
238   MicroMipsR6Thunk(Symbol &dest) : Thunk(dest, 0) {}
239 
240   uint32_t size() override { return 12; }
241   void writeTo(uint8_t *buf) override;
242   void addSymbols(ThunkSection &isec) override;
243   InputSection *getTargetInputSection() const override;
244 };
245 
246 class PPC32PltCallStub final : public Thunk {
247 public:
248   // For R_PPC_PLTREL24, Thunk::addend records the addend which will be used to
249   // decide the offsets in the call stub.
250   PPC32PltCallStub(const InputSection &isec, const Relocation &rel,
251                    Symbol &dest)
252       : Thunk(dest, rel.addend), file(isec.file) {}
253   uint32_t size() override { return 16; }
254   void writeTo(uint8_t *buf) override;
255   void addSymbols(ThunkSection &isec) override;
256   bool isCompatibleWith(const InputSection &isec, const Relocation &rel) const override;
257 
258 private:
259   // Records the call site of the call stub.
260   const InputFile *file;
261 };
262 
263 class PPC32LongThunk final : public Thunk {
264 public:
265   PPC32LongThunk(Symbol &dest, int64_t addend) : Thunk(dest, addend) {}
266   uint32_t size() override { return config->isPic ? 32 : 16; }
267   void writeTo(uint8_t *buf) override;
268   void addSymbols(ThunkSection &isec) override;
269 };
270 
271 // PPC64 Plt call stubs.
272 // Any call site that needs to call through a plt entry needs a call stub in
273 // the .text section. The call stub is responsible for:
274 // 1) Saving the toc-pointer to the stack.
275 // 2) Loading the target functions address from the procedure linkage table into
276 //    r12 for use by the target functions global entry point, and into the count
277 //    register.
278 // 3) Transferring control to the target function through an indirect branch.
279 class PPC64PltCallStub final : public Thunk {
280 public:
281   PPC64PltCallStub(Symbol &dest) : Thunk(dest, 0) {}
282   uint32_t size() override { return 20; }
283   void writeTo(uint8_t *buf) override;
284   void addSymbols(ThunkSection &isec) override;
285   bool isCompatibleWith(const InputSection &isec,
286                         const Relocation &rel) const override;
287 };
288 
289 // PPC64 R2 Save Stub
290 // When the caller requires a valid R2 TOC pointer but the callee does not
291 // require a TOC pointer and the callee cannot guarantee that it doesn't
292 // clobber R2 then we need to save R2. This stub:
293 // 1) Saves the TOC pointer to the stack.
294 // 2) Tail calls the callee.
295 class PPC64R2SaveStub final : public Thunk {
296 public:
297   PPC64R2SaveStub(Symbol &dest, int64_t addend) : Thunk(dest, addend) {
298     alignment = 16;
299   }
300 
301   // To prevent oscillations in layout when moving from short to long thunks
302   // we make sure that once a thunk has been set to long it cannot go back.
303   bool getMayUseShortThunk() {
304     if (!mayUseShortThunk)
305       return false;
306     if (!isInt<26>(computeOffset())) {
307       mayUseShortThunk = false;
308       return false;
309     }
310     return true;
311   }
312   uint32_t size() override { return getMayUseShortThunk() ? 8 : 32; }
313   void writeTo(uint8_t *buf) override;
314   void addSymbols(ThunkSection &isec) override;
315   bool isCompatibleWith(const InputSection &isec,
316                         const Relocation &rel) const override;
317 
318 private:
319   // Transitioning from long to short can create layout oscillations in
320   // certain corner cases which would prevent the layout from converging.
321   // This is similar to the handling for ARMThunk.
322   bool mayUseShortThunk = true;
323   int64_t computeOffset() const {
324     return destination.getVA() - (getThunkTargetSym()->getVA() + 4);
325   }
326 };
327 
328 // PPC64 R12 Setup Stub
329 // When a caller that does not maintain a toc-pointer performs a local call to
330 // a callee which requires a toc-pointer then we need this stub to place the
331 // callee's global entry point into r12 without a save of R2.
332 class PPC64R12SetupStub final : public Thunk {
333 public:
334   PPC64R12SetupStub(Symbol &dest) : Thunk(dest, 0) { alignment = 16; }
335   uint32_t size() override { return 32; }
336   void writeTo(uint8_t *buf) override;
337   void addSymbols(ThunkSection &isec) override;
338   bool isCompatibleWith(const InputSection &isec,
339                         const Relocation &rel) const override;
340 };
341 
342 // PPC64 PC-relative PLT Stub
343 // When a caller that does not maintain a toc-pointer performs an extern call
344 // then this stub is needed for:
345 // 1) Loading the target functions address from the procedure linkage table into
346 //    r12 for use by the target functions global entry point, and into the count
347 //    register with pc-relative instructions.
348 // 2) Transferring control to the target function through an indirect branch.
349 class PPC64PCRelPLTStub final : public Thunk {
350 public:
351   PPC64PCRelPLTStub(Symbol &dest) : Thunk(dest, 0) { alignment = 16; }
352   uint32_t size() override { return 32; }
353   void writeTo(uint8_t *buf) override;
354   void addSymbols(ThunkSection &isec) override;
355   bool isCompatibleWith(const InputSection &isec,
356                         const Relocation &rel) const override;
357 };
358 
359 // A bl instruction uses a signed 24 bit offset, with an implicit 4 byte
360 // alignment. This gives a possible 26 bits of 'reach'. If the call offset is
361 // larger than that we need to emit a long-branch thunk. The target address
362 // of the callee is stored in a table to be accessed TOC-relative. Since the
363 // call must be local (a non-local call will have a PltCallStub instead) the
364 // table stores the address of the callee's local entry point. For
365 // position-independent code a corresponding relative dynamic relocation is
366 // used.
367 class PPC64LongBranchThunk : public Thunk {
368 public:
369   uint32_t size() override { return 32; }
370   void writeTo(uint8_t *buf) override;
371   void addSymbols(ThunkSection &isec) override;
372   bool isCompatibleWith(const InputSection &isec,
373                         const Relocation &rel) const override;
374 
375 protected:
376   PPC64LongBranchThunk(Symbol &dest, int64_t addend) : Thunk(dest, addend) {}
377 };
378 
379 class PPC64PILongBranchThunk final : public PPC64LongBranchThunk {
380 public:
381   PPC64PILongBranchThunk(Symbol &dest, int64_t addend)
382       : PPC64LongBranchThunk(dest, addend) {
383     assert(!dest.isPreemptible);
384     if (Optional<uint32_t> index =
385             in.ppc64LongBranchTarget->addEntry(&dest, addend)) {
386       mainPart->relaDyn->addRelativeReloc(
387           target->relativeRel, in.ppc64LongBranchTarget, *index * UINT64_C(8),
388           dest, addend + getPPC64GlobalEntryToLocalEntryOffset(dest.stOther),
389           target->symbolicRel, R_ABS);
390     }
391   }
392 };
393 
394 class PPC64PDLongBranchThunk final : public PPC64LongBranchThunk {
395 public:
396   PPC64PDLongBranchThunk(Symbol &dest, int64_t addend)
397       : PPC64LongBranchThunk(dest, addend) {
398     in.ppc64LongBranchTarget->addEntry(&dest, addend);
399   }
400 };
401 
402 } // end anonymous namespace
403 
404 Defined *Thunk::addSymbol(StringRef name, uint8_t type, uint64_t value,
405                           InputSectionBase &section) {
406   Defined *d = addSyntheticLocal(name, type, value, /*size=*/0, section);
407   syms.push_back(d);
408   return d;
409 }
410 
411 void Thunk::setOffset(uint64_t newOffset) {
412   for (Defined *d : syms)
413     d->value = d->value - offset + newOffset;
414   offset = newOffset;
415 }
416 
417 // AArch64 long range Thunks
418 
419 static uint64_t getAArch64ThunkDestVA(const Symbol &s, int64_t a) {
420   uint64_t v = s.isInPlt() ? s.getPltVA() : s.getVA(a);
421   return v;
422 }
423 
424 void AArch64ABSLongThunk::writeTo(uint8_t *buf) {
425   const uint8_t data[] = {
426     0x50, 0x00, 0x00, 0x58, //     ldr x16, L0
427     0x00, 0x02, 0x1f, 0xd6, //     br  x16
428     0x00, 0x00, 0x00, 0x00, // L0: .xword S
429     0x00, 0x00, 0x00, 0x00,
430   };
431   uint64_t s = getAArch64ThunkDestVA(destination, addend);
432   memcpy(buf, data, sizeof(data));
433   target->relocateNoSym(buf + 8, R_AARCH64_ABS64, s);
434 }
435 
436 void AArch64ABSLongThunk::addSymbols(ThunkSection &isec) {
437   addSymbol(saver.save("__AArch64AbsLongThunk_" + destination.getName()),
438             STT_FUNC, 0, isec);
439   addSymbol("$x", STT_NOTYPE, 0, isec);
440   addSymbol("$d", STT_NOTYPE, 8, isec);
441 }
442 
443 // This Thunk has a maximum range of 4Gb, this is sufficient for all programs
444 // using the small code model, including pc-relative ones. At time of writing
445 // clang and gcc do not support the large code model for position independent
446 // code so it is safe to use this for position independent thunks without
447 // worrying about the destination being more than 4Gb away.
448 void AArch64ADRPThunk::writeTo(uint8_t *buf) {
449   const uint8_t data[] = {
450       0x10, 0x00, 0x00, 0x90, // adrp x16, Dest R_AARCH64_ADR_PREL_PG_HI21(Dest)
451       0x10, 0x02, 0x00, 0x91, // add  x16, x16, R_AARCH64_ADD_ABS_LO12_NC(Dest)
452       0x00, 0x02, 0x1f, 0xd6, // br   x16
453   };
454   uint64_t s = getAArch64ThunkDestVA(destination, addend);
455   uint64_t p = getThunkTargetSym()->getVA();
456   memcpy(buf, data, sizeof(data));
457   target->relocateNoSym(buf, R_AARCH64_ADR_PREL_PG_HI21,
458                         getAArch64Page(s) - getAArch64Page(p));
459   target->relocateNoSym(buf + 4, R_AARCH64_ADD_ABS_LO12_NC, s);
460 }
461 
462 void AArch64ADRPThunk::addSymbols(ThunkSection &isec) {
463   addSymbol(saver.save("__AArch64ADRPThunk_" + destination.getName()), STT_FUNC,
464             0, isec);
465   addSymbol("$x", STT_NOTYPE, 0, isec);
466 }
467 
468 // ARM Target Thunks
469 static uint64_t getARMThunkDestVA(const Symbol &s) {
470   uint64_t v = s.isInPlt() ? s.getPltVA() : s.getVA();
471   return SignExtend64<32>(v);
472 }
473 
474 // This function returns true if the target is not Thumb and is within 2^26, and
475 // it has not previously returned false (see comment for mayUseShortThunk).
476 bool ARMThunk::getMayUseShortThunk() {
477   if (!mayUseShortThunk)
478     return false;
479   uint64_t s = getARMThunkDestVA(destination);
480   if (s & 1) {
481     mayUseShortThunk = false;
482     return false;
483   }
484   uint64_t p = getThunkTargetSym()->getVA();
485   int64_t offset = s - p - 8;
486   mayUseShortThunk = llvm::isInt<26>(offset);
487   return mayUseShortThunk;
488 }
489 
490 void ARMThunk::writeTo(uint8_t *buf) {
491   if (!getMayUseShortThunk()) {
492     writeLong(buf);
493     return;
494   }
495 
496   uint64_t s = getARMThunkDestVA(destination);
497   uint64_t p = getThunkTargetSym()->getVA();
498   int64_t offset = s - p - 8;
499   const uint8_t data[] = {
500     0x00, 0x00, 0x00, 0xea, // b S
501   };
502   memcpy(buf, data, sizeof(data));
503   target->relocateNoSym(buf, R_ARM_JUMP24, offset);
504 }
505 
506 bool ARMThunk::isCompatibleWith(const InputSection &isec,
507                                 const Relocation &rel) const {
508   // Thumb branch relocations can't use BLX
509   return rel.type != R_ARM_THM_JUMP19 && rel.type != R_ARM_THM_JUMP24;
510 }
511 
512 // This function returns true if the target is Thumb and is within 2^25, and
513 // it has not previously returned false (see comment for mayUseShortThunk).
514 bool ThumbThunk::getMayUseShortThunk() {
515   if (!mayUseShortThunk)
516     return false;
517   uint64_t s = getARMThunkDestVA(destination);
518   if ((s & 1) == 0) {
519     mayUseShortThunk = false;
520     return false;
521   }
522   uint64_t p = getThunkTargetSym()->getVA() & ~1;
523   int64_t offset = s - p - 4;
524   mayUseShortThunk = llvm::isInt<25>(offset);
525   return mayUseShortThunk;
526 }
527 
528 void ThumbThunk::writeTo(uint8_t *buf) {
529   if (!getMayUseShortThunk()) {
530     writeLong(buf);
531     return;
532   }
533 
534   uint64_t s = getARMThunkDestVA(destination);
535   uint64_t p = getThunkTargetSym()->getVA();
536   int64_t offset = s - p - 4;
537   const uint8_t data[] = {
538       0x00, 0xf0, 0x00, 0xb0, // b.w S
539   };
540   memcpy(buf, data, sizeof(data));
541   target->relocateNoSym(buf, R_ARM_THM_JUMP24, offset);
542 }
543 
544 bool ThumbThunk::isCompatibleWith(const InputSection &isec,
545                                   const Relocation &rel) const {
546   // ARM branch relocations can't use BLX
547   return rel.type != R_ARM_JUMP24 && rel.type != R_ARM_PC24 && rel.type != R_ARM_PLT32;
548 }
549 
550 void ARMV7ABSLongThunk::writeLong(uint8_t *buf) {
551   const uint8_t data[] = {
552       0x00, 0xc0, 0x00, 0xe3, // movw         ip,:lower16:S
553       0x00, 0xc0, 0x40, 0xe3, // movt         ip,:upper16:S
554       0x1c, 0xff, 0x2f, 0xe1, // bx   ip
555   };
556   uint64_t s = getARMThunkDestVA(destination);
557   memcpy(buf, data, sizeof(data));
558   target->relocateNoSym(buf, R_ARM_MOVW_ABS_NC, s);
559   target->relocateNoSym(buf + 4, R_ARM_MOVT_ABS, s);
560 }
561 
562 void ARMV7ABSLongThunk::addSymbols(ThunkSection &isec) {
563   addSymbol(saver.save("__ARMv7ABSLongThunk_" + destination.getName()),
564             STT_FUNC, 0, isec);
565   addSymbol("$a", STT_NOTYPE, 0, isec);
566 }
567 
568 void ThumbV7ABSLongThunk::writeLong(uint8_t *buf) {
569   const uint8_t data[] = {
570       0x40, 0xf2, 0x00, 0x0c, // movw         ip, :lower16:S
571       0xc0, 0xf2, 0x00, 0x0c, // movt         ip, :upper16:S
572       0x60, 0x47,             // bx   ip
573   };
574   uint64_t s = getARMThunkDestVA(destination);
575   memcpy(buf, data, sizeof(data));
576   target->relocateNoSym(buf, R_ARM_THM_MOVW_ABS_NC, s);
577   target->relocateNoSym(buf + 4, R_ARM_THM_MOVT_ABS, s);
578 }
579 
580 void ThumbV7ABSLongThunk::addSymbols(ThunkSection &isec) {
581   addSymbol(saver.save("__Thumbv7ABSLongThunk_" + destination.getName()),
582             STT_FUNC, 1, isec);
583   addSymbol("$t", STT_NOTYPE, 0, isec);
584 }
585 
586 void ARMV7PILongThunk::writeLong(uint8_t *buf) {
587   const uint8_t data[] = {
588       0xf0, 0xcf, 0x0f, 0xe3, // P:  movw ip,:lower16:S - (P + (L1-P) + 8)
589       0x00, 0xc0, 0x40, 0xe3, //     movt ip,:upper16:S - (P + (L1-P) + 8)
590       0x0f, 0xc0, 0x8c, 0xe0, // L1: add  ip, ip, pc
591       0x1c, 0xff, 0x2f, 0xe1, //     bx   ip
592   };
593   uint64_t s = getARMThunkDestVA(destination);
594   uint64_t p = getThunkTargetSym()->getVA();
595   int64_t offset = s - p - 16;
596   memcpy(buf, data, sizeof(data));
597   target->relocateNoSym(buf, R_ARM_MOVW_PREL_NC, offset);
598   target->relocateNoSym(buf + 4, R_ARM_MOVT_PREL, offset);
599 }
600 
601 void ARMV7PILongThunk::addSymbols(ThunkSection &isec) {
602   addSymbol(saver.save("__ARMV7PILongThunk_" + destination.getName()), STT_FUNC,
603             0, isec);
604   addSymbol("$a", STT_NOTYPE, 0, isec);
605 }
606 
607 void ThumbV7PILongThunk::writeLong(uint8_t *buf) {
608   const uint8_t data[] = {
609       0x4f, 0xf6, 0xf4, 0x7c, // P:  movw ip,:lower16:S - (P + (L1-P) + 4)
610       0xc0, 0xf2, 0x00, 0x0c, //     movt ip,:upper16:S - (P + (L1-P) + 4)
611       0xfc, 0x44,             // L1: add  ip, pc
612       0x60, 0x47,             //     bx   ip
613   };
614   uint64_t s = getARMThunkDestVA(destination);
615   uint64_t p = getThunkTargetSym()->getVA() & ~0x1;
616   int64_t offset = s - p - 12;
617   memcpy(buf, data, sizeof(data));
618   target->relocateNoSym(buf, R_ARM_THM_MOVW_PREL_NC, offset);
619   target->relocateNoSym(buf + 4, R_ARM_THM_MOVT_PREL, offset);
620 }
621 
622 void ThumbV7PILongThunk::addSymbols(ThunkSection &isec) {
623   addSymbol(saver.save("__ThumbV7PILongThunk_" + destination.getName()),
624             STT_FUNC, 1, isec);
625   addSymbol("$t", STT_NOTYPE, 0, isec);
626 }
627 
628 void ARMV5ABSLongThunk::writeLong(uint8_t *buf) {
629   const uint8_t data[] = {
630       0x04, 0xf0, 0x1f, 0xe5, //     ldr pc, [pc,#-4] ; L1
631       0x00, 0x00, 0x00, 0x00, // L1: .word S
632   };
633   memcpy(buf, data, sizeof(data));
634   target->relocateNoSym(buf + 4, R_ARM_ABS32, getARMThunkDestVA(destination));
635 }
636 
637 void ARMV5ABSLongThunk::addSymbols(ThunkSection &isec) {
638   addSymbol(saver.save("__ARMv5ABSLongThunk_" + destination.getName()),
639             STT_FUNC, 0, isec);
640   addSymbol("$a", STT_NOTYPE, 0, isec);
641   addSymbol("$d", STT_NOTYPE, 4, isec);
642 }
643 
644 bool ARMV5ABSLongThunk::isCompatibleWith(const InputSection &isec,
645                                          const Relocation &rel) const {
646   // Thumb branch relocations can't use BLX
647   return rel.type != R_ARM_THM_JUMP19 && rel.type != R_ARM_THM_JUMP24;
648 }
649 
650 void ARMV5PILongThunk::writeLong(uint8_t *buf) {
651   const uint8_t data[] = {
652       0x04, 0xc0, 0x9f, 0xe5, // P:  ldr ip, [pc,#4] ; L2
653       0x0c, 0xc0, 0x8f, 0xe0, // L1: add ip, pc, ip
654       0x1c, 0xff, 0x2f, 0xe1, //     bx ip
655       0x00, 0x00, 0x00, 0x00, // L2: .word S - (P + (L1 - P) + 8)
656   };
657   uint64_t s = getARMThunkDestVA(destination);
658   uint64_t p = getThunkTargetSym()->getVA() & ~0x1;
659   memcpy(buf, data, sizeof(data));
660   target->relocateNoSym(buf + 12, R_ARM_REL32, s - p - 12);
661 }
662 
663 void ARMV5PILongThunk::addSymbols(ThunkSection &isec) {
664   addSymbol(saver.save("__ARMV5PILongThunk_" + destination.getName()), STT_FUNC,
665             0, isec);
666   addSymbol("$a", STT_NOTYPE, 0, isec);
667   addSymbol("$d", STT_NOTYPE, 12, isec);
668 }
669 
670 bool ARMV5PILongThunk::isCompatibleWith(const InputSection &isec,
671                                         const Relocation &rel) const {
672   // Thumb branch relocations can't use BLX
673   return rel.type != R_ARM_THM_JUMP19 && rel.type != R_ARM_THM_JUMP24;
674 }
675 
676 void ThumbV6MABSLongThunk::writeLong(uint8_t *buf) {
677   // Most Thumb instructions cannot access the high registers r8 - r15. As the
678   // only register we can corrupt is r12 we must instead spill a low register
679   // to the stack to use as a scratch register. We push r1 even though we
680   // don't need to get some space to use for the return address.
681   const uint8_t data[] = {
682       0x03, 0xb4,            // push {r0, r1} ; Obtain scratch registers
683       0x01, 0x48,            // ldr r0, [pc, #4] ; L1
684       0x01, 0x90,            // str r0, [sp, #4] ; SP + 4 = S
685       0x01, 0xbd,            // pop {r0, pc} ; restore r0 and branch to dest
686       0x00, 0x00, 0x00, 0x00 // L1: .word S
687   };
688   uint64_t s = getARMThunkDestVA(destination);
689   memcpy(buf, data, sizeof(data));
690   target->relocateNoSym(buf + 8, R_ARM_ABS32, s);
691 }
692 
693 void ThumbV6MABSLongThunk::addSymbols(ThunkSection &isec) {
694   addSymbol(saver.save("__Thumbv6MABSLongThunk_" + destination.getName()),
695             STT_FUNC, 1, isec);
696   addSymbol("$t", STT_NOTYPE, 0, isec);
697   addSymbol("$d", STT_NOTYPE, 8, isec);
698 }
699 
700 void ThumbV6MPILongThunk::writeLong(uint8_t *buf) {
701   // Most Thumb instructions cannot access the high registers r8 - r15. As the
702   // only register we can corrupt is ip (r12) we must instead spill a low
703   // register to the stack to use as a scratch register.
704   const uint8_t data[] = {
705       0x01, 0xb4,             // P:  push {r0}        ; Obtain scratch register
706       0x02, 0x48,             //     ldr r0, [pc, #8] ; L2
707       0x84, 0x46,             //     mov ip, r0       ; high to low register
708       0x01, 0xbc,             //     pop {r0}         ; restore scratch register
709       0xe7, 0x44,             // L1: add pc, ip       ; transfer control
710       0xc0, 0x46,             //     nop              ; pad to 4-byte boundary
711       0x00, 0x00, 0x00, 0x00, // L2: .word S - (P + (L1 - P) + 4)
712   };
713   uint64_t s = getARMThunkDestVA(destination);
714   uint64_t p = getThunkTargetSym()->getVA() & ~0x1;
715   memcpy(buf, data, sizeof(data));
716   target->relocateNoSym(buf + 12, R_ARM_REL32, s - p - 12);
717 }
718 
719 void ThumbV6MPILongThunk::addSymbols(ThunkSection &isec) {
720   addSymbol(saver.save("__Thumbv6MPILongThunk_" + destination.getName()),
721             STT_FUNC, 1, isec);
722   addSymbol("$t", STT_NOTYPE, 0, isec);
723   addSymbol("$d", STT_NOTYPE, 12, isec);
724 }
725 
726 // Write MIPS LA25 thunk code to call PIC function from the non-PIC one.
727 void MipsThunk::writeTo(uint8_t *buf) {
728   uint64_t s = destination.getVA();
729   write32(buf, 0x3c190000); // lui   $25, %hi(func)
730   write32(buf + 4, 0x08000000 | (s >> 2)); // j     func
731   write32(buf + 8, 0x27390000); // addiu $25, $25, %lo(func)
732   write32(buf + 12, 0x00000000); // nop
733   target->relocateNoSym(buf, R_MIPS_HI16, s);
734   target->relocateNoSym(buf + 8, R_MIPS_LO16, s);
735 }
736 
737 void MipsThunk::addSymbols(ThunkSection &isec) {
738   addSymbol(saver.save("__LA25Thunk_" + destination.getName()), STT_FUNC, 0,
739             isec);
740 }
741 
742 InputSection *MipsThunk::getTargetInputSection() const {
743   auto &dr = cast<Defined>(destination);
744   return dyn_cast<InputSection>(dr.section);
745 }
746 
747 // Write microMIPS R2-R5 LA25 thunk code
748 // to call PIC function from the non-PIC one.
749 void MicroMipsThunk::writeTo(uint8_t *buf) {
750   uint64_t s = destination.getVA();
751   write16(buf, 0x41b9);       // lui   $25, %hi(func)
752   write16(buf + 4, 0xd400);   // j     func
753   write16(buf + 8, 0x3339);   // addiu $25, $25, %lo(func)
754   write16(buf + 12, 0x0c00);  // nop
755   target->relocateNoSym(buf, R_MICROMIPS_HI16, s);
756   target->relocateNoSym(buf + 4, R_MICROMIPS_26_S1, s);
757   target->relocateNoSym(buf + 8, R_MICROMIPS_LO16, s);
758 }
759 
760 void MicroMipsThunk::addSymbols(ThunkSection &isec) {
761   Defined *d = addSymbol(
762       saver.save("__microLA25Thunk_" + destination.getName()), STT_FUNC, 0, isec);
763   d->stOther |= STO_MIPS_MICROMIPS;
764 }
765 
766 InputSection *MicroMipsThunk::getTargetInputSection() const {
767   auto &dr = cast<Defined>(destination);
768   return dyn_cast<InputSection>(dr.section);
769 }
770 
771 // Write microMIPS R6 LA25 thunk code
772 // to call PIC function from the non-PIC one.
773 void MicroMipsR6Thunk::writeTo(uint8_t *buf) {
774   uint64_t s = destination.getVA();
775   uint64_t p = getThunkTargetSym()->getVA();
776   write16(buf, 0x1320);       // lui   $25, %hi(func)
777   write16(buf + 4, 0x3339);   // addiu $25, $25, %lo(func)
778   write16(buf + 8, 0x9400);   // bc    func
779   target->relocateNoSym(buf, R_MICROMIPS_HI16, s);
780   target->relocateNoSym(buf + 4, R_MICROMIPS_LO16, s);
781   target->relocateNoSym(buf + 8, R_MICROMIPS_PC26_S1, s - p - 12);
782 }
783 
784 void MicroMipsR6Thunk::addSymbols(ThunkSection &isec) {
785   Defined *d = addSymbol(
786       saver.save("__microLA25Thunk_" + destination.getName()), STT_FUNC, 0, isec);
787   d->stOther |= STO_MIPS_MICROMIPS;
788 }
789 
790 InputSection *MicroMipsR6Thunk::getTargetInputSection() const {
791   auto &dr = cast<Defined>(destination);
792   return dyn_cast<InputSection>(dr.section);
793 }
794 
795 void elf::writePPC32PltCallStub(uint8_t *buf, uint64_t gotPltVA,
796                                 const InputFile *file, int64_t addend) {
797   if (!config->isPic) {
798     write32(buf + 0, 0x3d600000 | (gotPltVA + 0x8000) >> 16); // lis r11,ha
799     write32(buf + 4, 0x816b0000 | (uint16_t)gotPltVA);        // lwz r11,l(r11)
800     write32(buf + 8, 0x7d6903a6);                             // mtctr r11
801     write32(buf + 12, 0x4e800420);                            // bctr
802     return;
803   }
804   uint32_t offset;
805   if (addend >= 0x8000) {
806     // The stub loads an address relative to r30 (.got2+Addend). Addend is
807     // almost always 0x8000. The address of .got2 is different in another object
808     // file, so a stub cannot be shared.
809     offset = gotPltVA - (in.ppc32Got2->getParent()->getVA() +
810                          file->ppc32Got2OutSecOff + addend);
811   } else {
812     // The stub loads an address relative to _GLOBAL_OFFSET_TABLE_ (which is
813     // currently the address of .got).
814     offset = gotPltVA - in.got->getVA();
815   }
816   uint16_t ha = (offset + 0x8000) >> 16, l = (uint16_t)offset;
817   if (ha == 0) {
818     write32(buf + 0, 0x817e0000 | l); // lwz r11,l(r30)
819     write32(buf + 4, 0x7d6903a6);     // mtctr r11
820     write32(buf + 8, 0x4e800420);     // bctr
821     write32(buf + 12, 0x60000000);    // nop
822   } else {
823     write32(buf + 0, 0x3d7e0000 | ha); // addis r11,r30,ha
824     write32(buf + 4, 0x816b0000 | l);  // lwz r11,l(r11)
825     write32(buf + 8, 0x7d6903a6);      // mtctr r11
826     write32(buf + 12, 0x4e800420);     // bctr
827   }
828 }
829 
830 void PPC32PltCallStub::writeTo(uint8_t *buf) {
831   writePPC32PltCallStub(buf, destination.getGotPltVA(), file, addend);
832 }
833 
834 void PPC32PltCallStub::addSymbols(ThunkSection &isec) {
835   std::string buf;
836   raw_string_ostream os(buf);
837   os << format_hex_no_prefix(addend, 8);
838   if (!config->isPic)
839     os << ".plt_call32.";
840   else if (addend >= 0x8000)
841     os << ".got2.plt_pic32.";
842   else
843     os << ".plt_pic32.";
844   os << destination.getName();
845   addSymbol(saver.save(os.str()), STT_FUNC, 0, isec);
846 }
847 
848 bool PPC32PltCallStub::isCompatibleWith(const InputSection &isec,
849                                         const Relocation &rel) const {
850   return !config->isPic || (isec.file == file && rel.addend == addend);
851 }
852 
853 void PPC32LongThunk::addSymbols(ThunkSection &isec) {
854   addSymbol(saver.save("__LongThunk_" + destination.getName()), STT_FUNC, 0,
855             isec);
856 }
857 
858 void PPC32LongThunk::writeTo(uint8_t *buf) {
859   auto ha = [](uint32_t v) -> uint16_t { return (v + 0x8000) >> 16; };
860   auto lo = [](uint32_t v) -> uint16_t { return v; };
861   uint32_t d = destination.getVA(addend);
862   if (config->isPic) {
863     uint32_t off = d - (getThunkTargetSym()->getVA() + 8);
864     write32(buf + 0, 0x7c0802a6);            // mflr r12,0
865     write32(buf + 4, 0x429f0005);            // bcl r20,r31,.+4
866     write32(buf + 8, 0x7d8802a6);            // mtctr r12
867     write32(buf + 12, 0x3d8c0000 | ha(off)); // addis r12,r12,off@ha
868     write32(buf + 16, 0x398c0000 | lo(off)); // addi r12,r12,off@l
869     write32(buf + 20, 0x7c0803a6);           // mtlr r0
870     buf += 24;
871   } else {
872     write32(buf + 0, 0x3d800000 | ha(d));    // lis r12,d@ha
873     write32(buf + 4, 0x398c0000 | lo(d));    // addi r12,r12,d@l
874     buf += 8;
875   }
876   write32(buf + 0, 0x7d8903a6);              // mtctr r12
877   write32(buf + 4, 0x4e800420);              // bctr
878 }
879 
880 void elf::writePPC64LoadAndBranch(uint8_t *buf, int64_t offset) {
881   uint16_t offHa = (offset + 0x8000) >> 16;
882   uint16_t offLo = offset & 0xffff;
883 
884   write32(buf + 0, 0x3d820000 | offHa); // addis r12, r2, OffHa
885   write32(buf + 4, 0xe98c0000 | offLo); // ld    r12, OffLo(r12)
886   write32(buf + 8, 0x7d8903a6);         // mtctr r12
887   write32(buf + 12, 0x4e800420);        // bctr
888 }
889 
890 void PPC64PltCallStub::writeTo(uint8_t *buf) {
891   int64_t offset = destination.getGotPltVA() - getPPC64TocBase();
892   // Save the TOC pointer to the save-slot reserved in the call frame.
893   write32(buf + 0, 0xf8410018); // std     r2,24(r1)
894   writePPC64LoadAndBranch(buf + 4, offset);
895 }
896 
897 void PPC64PltCallStub::addSymbols(ThunkSection &isec) {
898   Defined *s = addSymbol(saver.save("__plt_" + destination.getName()), STT_FUNC,
899                          0, isec);
900   s->needsTocRestore = true;
901   s->file = destination.file;
902 }
903 
904 bool PPC64PltCallStub::isCompatibleWith(const InputSection &isec,
905                                         const Relocation &rel) const {
906   return rel.type == R_PPC64_REL24 || rel.type == R_PPC64_REL14;
907 }
908 
909 void PPC64R2SaveStub::writeTo(uint8_t *buf) {
910   const int64_t offset = computeOffset();
911   write32(buf + 0, 0xf8410018); // std  r2,24(r1)
912   // The branch offset needs to fit in 26 bits.
913   if (getMayUseShortThunk()) {
914     write32(buf + 4, 0x48000000 | (offset & 0x03fffffc)); // b    <offset>
915   } else if (isInt<34>(offset)) {
916     int nextInstOffset;
917     if (!config->power10Stubs) {
918       uint64_t tocOffset = destination.getVA() - getPPC64TocBase();
919       if (tocOffset >> 16 > 0) {
920         const uint64_t addi = ADDI_R12_TO_R12_NO_DISP | (tocOffset & 0xffff);
921         const uint64_t addis = ADDIS_R12_TO_R2_NO_DISP | ((tocOffset >> 16) & 0xffff);
922         write32(buf + 4, addis); // addis r12, r2 , top of offset
923         write32(buf + 8, addi);  // addi  r12, r12, bottom of offset
924         nextInstOffset = 12;
925       } else {
926         const uint64_t addi = ADDI_R12_TO_R2_NO_DISP | (tocOffset & 0xffff);
927         write32(buf + 4, addi); // addi r12, r2, offset
928         nextInstOffset = 8;
929       }
930     } else {
931       const uint64_t paddi = PADDI_R12_NO_DISP |
932                              (((offset >> 16) & 0x3ffff) << 32) |
933                              (offset & 0xffff);
934       writePrefixedInstruction(buf + 4, paddi); // paddi r12, 0, func@pcrel, 1
935       nextInstOffset = 12;
936     }
937     write32(buf + nextInstOffset, MTCTR_R12); // mtctr r12
938     write32(buf + nextInstOffset + 4, BCTR);  // bctr
939   } else {
940     in.ppc64LongBranchTarget->addEntry(&destination, addend);
941     const int64_t offsetFromTOC =
942         in.ppc64LongBranchTarget->getEntryVA(&destination, addend) -
943         getPPC64TocBase();
944     writePPC64LoadAndBranch(buf + 4, offsetFromTOC);
945   }
946 }
947 
948 void PPC64R2SaveStub::addSymbols(ThunkSection &isec) {
949   Defined *s = addSymbol(saver.save("__toc_save_" + destination.getName()),
950                          STT_FUNC, 0, isec);
951   s->needsTocRestore = true;
952 }
953 
954 bool PPC64R2SaveStub::isCompatibleWith(const InputSection &isec,
955                                        const Relocation &rel) const {
956   return rel.type == R_PPC64_REL24 || rel.type == R_PPC64_REL14;
957 }
958 
959 void PPC64R12SetupStub::writeTo(uint8_t *buf) {
960   int64_t offset = destination.getVA() - getThunkTargetSym()->getVA();
961   if (!isInt<34>(offset))
962     reportRangeError(buf, offset, 34, destination, "R12 setup stub offset");
963 
964   int nextInstOffset;
965   if (!config->power10Stubs) {
966     uint32_t off = destination.getVA(addend) - getThunkTargetSym()->getVA() - 8;
967     write32(buf + 0, 0x7c0802a6);                      // mflr r12
968     write32(buf + 4, 0x429f0005);                      // bcl 20,31,.+4
969     write32(buf + 8, 0x7d6802a6);                      // mflr r11
970     write32(buf + 12, 0x7d8803a6);                     // mtlr r12
971     write32(buf + 16, 0x3d8b0000 | computeHiBits(off));// addis r12,r11,off@ha
972     write32(buf + 20, 0x398c0000 | (off & 0xffff));    // addi r12,r12,off@l
973     nextInstOffset = 24;
974   } else {
975     uint64_t paddi = PADDI_R12_NO_DISP | (((offset >> 16) & 0x3ffff) << 32) |
976                      (offset & 0xffff);
977     writePrefixedInstruction(buf + 0, paddi); // paddi r12, 0, func@pcrel, 1
978     nextInstOffset = 8;
979   }
980   write32(buf + nextInstOffset, MTCTR_R12); // mtctr r12
981   write32(buf + nextInstOffset + 4, BCTR);  // bctr
982 }
983 
984 void PPC64R12SetupStub::addSymbols(ThunkSection &isec) {
985   addSymbol(saver.save("__gep_setup_" + destination.getName()), STT_FUNC, 0,
986             isec);
987 }
988 
989 bool PPC64R12SetupStub::isCompatibleWith(const InputSection &isec,
990                                          const Relocation &rel) const {
991   return rel.type == R_PPC64_REL24_NOTOC;
992 }
993 
994 void PPC64PCRelPLTStub::writeTo(uint8_t *buf) {
995   int nextInstOffset = 0;
996   int64_t offset = destination.getGotPltVA() - getThunkTargetSym()->getVA();
997 
998   if (config->power10Stubs) {
999     if (!isInt<34>(offset))
1000       reportRangeError(buf, offset, 34, destination,
1001                        "PC-relative PLT stub offset");
1002     const uint64_t pld = PLD_R12_NO_DISP | (((offset >> 16) & 0x3ffff) << 32) |
1003                    (offset & 0xffff);
1004     writePrefixedInstruction(buf + 0, pld); // pld r12, func@plt@pcrel
1005     nextInstOffset = 8;
1006   } else {
1007     uint32_t off = destination.getVA(addend) - getThunkTargetSym()->getVA() - 8;
1008     write32(buf + 0, 0x7c0802a6);            // mflr r12
1009     write32(buf + 4, 0x429f0005);            // bcl 20,31,.+4
1010     write32(buf + 8, 0x7d6802a6);            // mflr r11
1011     write32(buf + 12, 0x7d8803a6);           // mtlr r12
1012     write32(buf + 16, 0x3d8b0000 | computeHiBits(off)); // addis r12,r11,off@ha
1013     write32(buf + 20, 0x398c0000 | (off & 0xffff)); // addi r12,r12,off@l
1014     nextInstOffset = 24;
1015   }
1016   write32(buf + nextInstOffset, MTCTR_R12); // mtctr r12
1017   write32(buf + nextInstOffset + 4, BCTR);  // bctr
1018 }
1019 
1020 void PPC64PCRelPLTStub::addSymbols(ThunkSection &isec) {
1021   addSymbol(saver.save("__plt_pcrel_" + destination.getName()), STT_FUNC, 0,
1022             isec);
1023 }
1024 
1025 bool PPC64PCRelPLTStub::isCompatibleWith(const InputSection &isec,
1026                                          const Relocation &rel) const {
1027   return rel.type == R_PPC64_REL24_NOTOC;
1028 }
1029 
1030 void PPC64LongBranchThunk::writeTo(uint8_t *buf) {
1031   int64_t offset = in.ppc64LongBranchTarget->getEntryVA(&destination, addend) -
1032                    getPPC64TocBase();
1033   writePPC64LoadAndBranch(buf, offset);
1034 }
1035 
1036 void PPC64LongBranchThunk::addSymbols(ThunkSection &isec) {
1037   addSymbol(saver.save("__long_branch_" + destination.getName()), STT_FUNC, 0,
1038             isec);
1039 }
1040 
1041 bool PPC64LongBranchThunk::isCompatibleWith(const InputSection &isec,
1042                                             const Relocation &rel) const {
1043   return rel.type == R_PPC64_REL24 || rel.type == R_PPC64_REL14;
1044 }
1045 
1046 Thunk::Thunk(Symbol &d, int64_t a) : destination(d), addend(a), offset(0) {}
1047 
1048 Thunk::~Thunk() = default;
1049 
1050 static Thunk *addThunkAArch64(RelType type, Symbol &s, int64_t a) {
1051   if (type != R_AARCH64_CALL26 && type != R_AARCH64_JUMP26 &&
1052       type != R_AARCH64_PLT32)
1053     fatal("unrecognized relocation type");
1054   if (config->picThunk)
1055     return make<AArch64ADRPThunk>(s, a);
1056   return make<AArch64ABSLongThunk>(s, a);
1057 }
1058 
1059 // Creates a thunk for Thumb-ARM interworking.
1060 // Arm Architectures v5 and v6 do not support Thumb2 technology. This means
1061 // - MOVT and MOVW instructions cannot be used
1062 // - Only Thumb relocation that can generate a Thunk is a BL, this can always
1063 //   be transformed into a BLX
1064 static Thunk *addThunkPreArmv7(RelType reloc, Symbol &s, int64_t a) {
1065   switch (reloc) {
1066   case R_ARM_PC24:
1067   case R_ARM_PLT32:
1068   case R_ARM_JUMP24:
1069   case R_ARM_CALL:
1070   case R_ARM_THM_CALL:
1071     if (config->picThunk)
1072       return make<ARMV5PILongThunk>(s, a);
1073     return make<ARMV5ABSLongThunk>(s, a);
1074   }
1075   fatal("relocation " + toString(reloc) + " to " + toString(s) +
1076         " not supported for Armv5 or Armv6 targets");
1077 }
1078 
1079 // Create a thunk for Thumb long branch on V6-M.
1080 // Arm Architecture v6-M only supports Thumb instructions. This means
1081 // - MOVT and MOVW instructions cannot be used.
1082 // - Only a limited number of instructions can access registers r8 and above
1083 // - No interworking support is needed (all Thumb).
1084 static Thunk *addThunkV6M(RelType reloc, Symbol &s, int64_t a) {
1085   switch (reloc) {
1086   case R_ARM_THM_JUMP19:
1087   case R_ARM_THM_JUMP24:
1088   case R_ARM_THM_CALL:
1089     if (config->isPic)
1090       return make<ThumbV6MPILongThunk>(s, a);
1091     return make<ThumbV6MABSLongThunk>(s, a);
1092   }
1093   fatal("relocation " + toString(reloc) + " to " + toString(s) +
1094         " not supported for Armv6-M targets");
1095 }
1096 
1097 // Creates a thunk for Thumb-ARM interworking or branch range extension.
1098 static Thunk *addThunkArm(RelType reloc, Symbol &s, int64_t a) {
1099   // Decide which Thunk is needed based on:
1100   // Available instruction set
1101   // - An Arm Thunk can only be used if Arm state is available.
1102   // - A Thumb Thunk can only be used if Thumb state is available.
1103   // - Can only use a Thunk if it uses instructions that the Target supports.
1104   // Relocation is branch or branch and link
1105   // - Branch instructions cannot change state, can only select Thunk that
1106   //   starts in the same state as the caller.
1107   // - Branch and link relocations can change state, can select Thunks from
1108   //   either Arm or Thumb.
1109   // Position independent Thunks if we require position independent code.
1110 
1111   // Handle architectures that have restrictions on the instructions that they
1112   // can use in Thunks. The flags below are set by reading the BuildAttributes
1113   // of the input objects. InputFiles.cpp contains the mapping from ARM
1114   // architecture to flag.
1115   if (!config->armHasMovtMovw) {
1116     if (!config->armJ1J2BranchEncoding)
1117       return addThunkPreArmv7(reloc, s, a);
1118     return addThunkV6M(reloc, s, a);
1119   }
1120 
1121   switch (reloc) {
1122   case R_ARM_PC24:
1123   case R_ARM_PLT32:
1124   case R_ARM_JUMP24:
1125   case R_ARM_CALL:
1126     if (config->picThunk)
1127       return make<ARMV7PILongThunk>(s, a);
1128     return make<ARMV7ABSLongThunk>(s, a);
1129   case R_ARM_THM_JUMP19:
1130   case R_ARM_THM_JUMP24:
1131   case R_ARM_THM_CALL:
1132     if (config->picThunk)
1133       return make<ThumbV7PILongThunk>(s, a);
1134     return make<ThumbV7ABSLongThunk>(s, a);
1135   }
1136   fatal("unrecognized relocation type");
1137 }
1138 
1139 static Thunk *addThunkMips(RelType type, Symbol &s) {
1140   if ((s.stOther & STO_MIPS_MICROMIPS) && isMipsR6())
1141     return make<MicroMipsR6Thunk>(s);
1142   if (s.stOther & STO_MIPS_MICROMIPS)
1143     return make<MicroMipsThunk>(s);
1144   return make<MipsThunk>(s);
1145 }
1146 
1147 static Thunk *addThunkPPC32(const InputSection &isec, const Relocation &rel,
1148                             Symbol &s) {
1149   assert((rel.type == R_PPC_LOCAL24PC || rel.type == R_PPC_REL24 ||
1150           rel.type == R_PPC_PLTREL24) &&
1151          "unexpected relocation type for thunk");
1152   if (s.isInPlt())
1153     return make<PPC32PltCallStub>(isec, rel, s);
1154   return make<PPC32LongThunk>(s, rel.addend);
1155 }
1156 
1157 static Thunk *addThunkPPC64(RelType type, Symbol &s, int64_t a) {
1158   assert((type == R_PPC64_REL14 || type == R_PPC64_REL24 ||
1159           type == R_PPC64_REL24_NOTOC) &&
1160          "unexpected relocation type for thunk");
1161   if (s.isInPlt())
1162     return type == R_PPC64_REL24_NOTOC ? (Thunk *)make<PPC64PCRelPLTStub>(s)
1163                                        : (Thunk *)make<PPC64PltCallStub>(s);
1164 
1165   // This check looks at the st_other bits of the callee. If the value is 1
1166   // then the callee clobbers the TOC and we need an R2 save stub when RelType
1167   // is R_PPC64_REL14 or R_PPC64_REL24.
1168   if ((type == R_PPC64_REL14 || type == R_PPC64_REL24) && (s.stOther >> 5) == 1)
1169     return make<PPC64R2SaveStub>(s, a);
1170 
1171   if (type == R_PPC64_REL24_NOTOC)
1172     return make<PPC64R12SetupStub>(s);
1173 
1174   if (config->picThunk)
1175     return make<PPC64PILongBranchThunk>(s, a);
1176 
1177   return make<PPC64PDLongBranchThunk>(s, a);
1178 }
1179 
1180 Thunk *elf::addThunk(const InputSection &isec, Relocation &rel) {
1181   Symbol &s = *rel.sym;
1182   int64_t a = rel.addend;
1183 
1184   if (config->emachine == EM_AARCH64)
1185     return addThunkAArch64(rel.type, s, a);
1186 
1187   if (config->emachine == EM_ARM)
1188     return addThunkArm(rel.type, s, a);
1189 
1190   if (config->emachine == EM_MIPS)
1191     return addThunkMips(rel.type, s);
1192 
1193   if (config->emachine == EM_PPC)
1194     return addThunkPPC32(isec, rel, s);
1195 
1196   if (config->emachine == EM_PPC64)
1197     return addThunkPPC64(rel.type, s, a);
1198 
1199   llvm_unreachable("add Thunk only supported for ARM, Mips and PowerPC");
1200 }
1201