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