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