xref: /llvm-project-15.0.7/lld/ELF/Arch/ARM.cpp (revision 57a2eaf3)
1 //===- ARM.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 #include "InputFiles.h"
10 #include "Symbols.h"
11 #include "SyntheticSections.h"
12 #include "Target.h"
13 #include "Thunks.h"
14 #include "lld/Common/ErrorHandler.h"
15 #include "llvm/Object/ELF.h"
16 #include "llvm/Support/Endian.h"
17 
18 using namespace llvm;
19 using namespace llvm::support::endian;
20 using namespace llvm::ELF;
21 
22 namespace lld {
23 namespace elf {
24 
25 namespace {
26 class ARM final : public TargetInfo {
27 public:
28   ARM();
29   uint32_t calcEFlags() const override;
30   RelExpr getRelExpr(RelType type, const Symbol &s,
31                      const uint8_t *loc) const override;
32   RelType getDynRel(RelType type) const override;
33   int64_t getImplicitAddend(const uint8_t *buf, RelType type) const override;
34   void writeGotPlt(uint8_t *buf, const Symbol &s) const override;
35   void writeIgotPlt(uint8_t *buf, const Symbol &s) const override;
36   void writePltHeader(uint8_t *buf) const override;
37   void writePlt(uint8_t *buf, const Symbol &sym,
38                 uint64_t pltEntryAddr) const override;
39   void addPltSymbols(InputSection &isec, uint64_t off) const override;
40   void addPltHeaderSymbols(InputSection &isd) const override;
41   bool needsThunk(RelExpr expr, RelType type, const InputFile *file,
42                   uint64_t branchAddr, const Symbol &s,
43                   int64_t a) const override;
44   uint32_t getThunkSectionSpacing() const override;
45   bool inBranchRange(RelType type, uint64_t src, uint64_t dst) const override;
46   void relocate(uint8_t *loc, const Relocation &rel,
47                 uint64_t val) const override;
48 };
49 } // namespace
50 
51 ARM::ARM() {
52   copyRel = R_ARM_COPY;
53   relativeRel = R_ARM_RELATIVE;
54   iRelativeRel = R_ARM_IRELATIVE;
55   gotRel = R_ARM_GLOB_DAT;
56   noneRel = R_ARM_NONE;
57   pltRel = R_ARM_JUMP_SLOT;
58   symbolicRel = R_ARM_ABS32;
59   tlsGotRel = R_ARM_TLS_TPOFF32;
60   tlsModuleIndexRel = R_ARM_TLS_DTPMOD32;
61   tlsOffsetRel = R_ARM_TLS_DTPOFF32;
62   gotBaseSymInGotPlt = false;
63   pltHeaderSize = 32;
64   pltEntrySize = 16;
65   ipltEntrySize = 16;
66   trapInstr = {0xd4, 0xd4, 0xd4, 0xd4};
67   needsThunks = true;
68 }
69 
70 uint32_t ARM::calcEFlags() const {
71   // The ABIFloatType is used by loaders to detect the floating point calling
72   // convention.
73   uint32_t abiFloatType = 0;
74   if (config->armVFPArgs == ARMVFPArgKind::Base ||
75       config->armVFPArgs == ARMVFPArgKind::Default)
76     abiFloatType = EF_ARM_ABI_FLOAT_SOFT;
77   else if (config->armVFPArgs == ARMVFPArgKind::VFP)
78     abiFloatType = EF_ARM_ABI_FLOAT_HARD;
79 
80   // We don't currently use any features incompatible with EF_ARM_EABI_VER5,
81   // but we don't have any firm guarantees of conformance. Linux AArch64
82   // kernels (as of 2016) require an EABI version to be set.
83   return EF_ARM_EABI_VER5 | abiFloatType;
84 }
85 
86 RelExpr ARM::getRelExpr(RelType type, const Symbol &s,
87                         const uint8_t *loc) const {
88   switch (type) {
89   case R_ARM_THM_JUMP11:
90     return R_PC;
91   case R_ARM_CALL:
92   case R_ARM_JUMP24:
93   case R_ARM_PC24:
94   case R_ARM_PLT32:
95   case R_ARM_PREL31:
96   case R_ARM_THM_JUMP19:
97   case R_ARM_THM_JUMP24:
98   case R_ARM_THM_CALL:
99     return R_PLT_PC;
100   case R_ARM_GOTOFF32:
101     // (S + A) - GOT_ORG
102     return R_GOTREL;
103   case R_ARM_GOT_BREL:
104     // GOT(S) + A - GOT_ORG
105     return R_GOT_OFF;
106   case R_ARM_GOT_PREL:
107   case R_ARM_TLS_IE32:
108     // GOT(S) + A - P
109     return R_GOT_PC;
110   case R_ARM_SBREL32:
111     return R_ARM_SBREL;
112   case R_ARM_TARGET1:
113     return config->target1Rel ? R_PC : R_ABS;
114   case R_ARM_TARGET2:
115     if (config->target2 == Target2Policy::Rel)
116       return R_PC;
117     if (config->target2 == Target2Policy::Abs)
118       return R_ABS;
119     return R_GOT_PC;
120   case R_ARM_TLS_GD32:
121     return R_TLSGD_PC;
122   case R_ARM_TLS_LDM32:
123     return R_TLSLD_PC;
124   case R_ARM_BASE_PREL:
125     // B(S) + A - P
126     // FIXME: currently B(S) assumed to be .got, this may not hold for all
127     // platforms.
128     return R_GOTONLY_PC;
129   case R_ARM_MOVW_PREL_NC:
130   case R_ARM_MOVT_PREL:
131   case R_ARM_REL32:
132   case R_ARM_THM_MOVW_PREL_NC:
133   case R_ARM_THM_MOVT_PREL:
134     return R_PC;
135   case R_ARM_THM_ALU_PREL_11_0:
136   case R_ARM_THM_PC8:
137   case R_ARM_THM_PC12:
138     return R_ARM_PCA;
139   case R_ARM_MOVW_BREL_NC:
140   case R_ARM_MOVW_BREL:
141   case R_ARM_MOVT_BREL:
142   case R_ARM_THM_MOVW_BREL_NC:
143   case R_ARM_THM_MOVW_BREL:
144   case R_ARM_THM_MOVT_BREL:
145     return R_ARM_SBREL;
146   case R_ARM_NONE:
147     return R_NONE;
148   case R_ARM_TLS_LE32:
149     return R_TLS;
150   case R_ARM_V4BX:
151     // V4BX is just a marker to indicate there's a "bx rN" instruction at the
152     // given address. It can be used to implement a special linker mode which
153     // rewrites ARMv4T inputs to ARMv4. Since we support only ARMv4 input and
154     // not ARMv4 output, we can just ignore it.
155     return R_NONE;
156   default:
157     return R_ABS;
158   }
159 }
160 
161 RelType ARM::getDynRel(RelType type) const {
162   if ((type == R_ARM_ABS32) || (type == R_ARM_TARGET1 && !config->target1Rel))
163     return R_ARM_ABS32;
164   return R_ARM_NONE;
165 }
166 
167 void ARM::writeGotPlt(uint8_t *buf, const Symbol &) const {
168   write32le(buf, in.plt->getVA());
169 }
170 
171 void ARM::writeIgotPlt(uint8_t *buf, const Symbol &s) const {
172   // An ARM entry is the address of the ifunc resolver function.
173   write32le(buf, s.getVA());
174 }
175 
176 // Long form PLT Header that does not have any restrictions on the displacement
177 // of the .plt from the .plt.got.
178 static void writePltHeaderLong(uint8_t *buf) {
179   const uint8_t pltData[] = {
180       0x04, 0xe0, 0x2d, 0xe5, //     str lr, [sp,#-4]!
181       0x04, 0xe0, 0x9f, 0xe5, //     ldr lr, L2
182       0x0e, 0xe0, 0x8f, 0xe0, // L1: add lr, pc, lr
183       0x08, 0xf0, 0xbe, 0xe5, //     ldr pc, [lr, #8]
184       0x00, 0x00, 0x00, 0x00, // L2: .word   &(.got.plt) - L1 - 8
185       0xd4, 0xd4, 0xd4, 0xd4, //     Pad to 32-byte boundary
186       0xd4, 0xd4, 0xd4, 0xd4, //     Pad to 32-byte boundary
187       0xd4, 0xd4, 0xd4, 0xd4};
188   memcpy(buf, pltData, sizeof(pltData));
189   uint64_t gotPlt = in.gotPlt->getVA();
190   uint64_t l1 = in.plt->getVA() + 8;
191   write32le(buf + 16, gotPlt - l1 - 8);
192 }
193 
194 // The default PLT header requires the .plt.got to be within 128 Mb of the
195 // .plt in the positive direction.
196 void ARM::writePltHeader(uint8_t *buf) const {
197   // Use a similar sequence to that in writePlt(), the difference is the calling
198   // conventions mean we use lr instead of ip. The PLT entry is responsible for
199   // saving lr on the stack, the dynamic loader is responsible for reloading
200   // it.
201   const uint32_t pltData[] = {
202       0xe52de004, // L1: str lr, [sp,#-4]!
203       0xe28fe600, //     add lr, pc,  #0x0NN00000 &(.got.plt - L1 - 4)
204       0xe28eea00, //     add lr, lr,  #0x000NN000 &(.got.plt - L1 - 4)
205       0xe5bef000, //     ldr pc, [lr, #0x00000NNN] &(.got.plt -L1 - 4)
206   };
207 
208   uint64_t offset = in.gotPlt->getVA() - in.plt->getVA() - 4;
209   if (!llvm::isUInt<27>(offset)) {
210     // We cannot encode the Offset, use the long form.
211     writePltHeaderLong(buf);
212     return;
213   }
214   write32le(buf + 0, pltData[0]);
215   write32le(buf + 4, pltData[1] | ((offset >> 20) & 0xff));
216   write32le(buf + 8, pltData[2] | ((offset >> 12) & 0xff));
217   write32le(buf + 12, pltData[3] | (offset & 0xfff));
218   memcpy(buf + 16, trapInstr.data(), 4); // Pad to 32-byte boundary
219   memcpy(buf + 20, trapInstr.data(), 4);
220   memcpy(buf + 24, trapInstr.data(), 4);
221   memcpy(buf + 28, trapInstr.data(), 4);
222 }
223 
224 void ARM::addPltHeaderSymbols(InputSection &isec) const {
225   addSyntheticLocal("$a", STT_NOTYPE, 0, 0, isec);
226   addSyntheticLocal("$d", STT_NOTYPE, 16, 0, isec);
227 }
228 
229 // Long form PLT entries that do not have any restrictions on the displacement
230 // of the .plt from the .plt.got.
231 static void writePltLong(uint8_t *buf, uint64_t gotPltEntryAddr,
232                          uint64_t pltEntryAddr) {
233   const uint8_t pltData[] = {
234       0x04, 0xc0, 0x9f, 0xe5, //     ldr ip, L2
235       0x0f, 0xc0, 0x8c, 0xe0, // L1: add ip, ip, pc
236       0x00, 0xf0, 0x9c, 0xe5, //     ldr pc, [ip]
237       0x00, 0x00, 0x00, 0x00, // L2: .word   Offset(&(.plt.got) - L1 - 8
238   };
239   memcpy(buf, pltData, sizeof(pltData));
240   uint64_t l1 = pltEntryAddr + 4;
241   write32le(buf + 12, gotPltEntryAddr - l1 - 8);
242 }
243 
244 // The default PLT entries require the .plt.got to be within 128 Mb of the
245 // .plt in the positive direction.
246 void ARM::writePlt(uint8_t *buf, const Symbol &sym,
247                    uint64_t pltEntryAddr) const {
248   // The PLT entry is similar to the example given in Appendix A of ELF for
249   // the Arm Architecture. Instead of using the Group Relocations to find the
250   // optimal rotation for the 8-bit immediate used in the add instructions we
251   // hard code the most compact rotations for simplicity. This saves a load
252   // instruction over the long plt sequences.
253   const uint32_t pltData[] = {
254       0xe28fc600, // L1: add ip, pc,  #0x0NN00000  Offset(&(.plt.got) - L1 - 8
255       0xe28cca00, //     add ip, ip,  #0x000NN000  Offset(&(.plt.got) - L1 - 8
256       0xe5bcf000, //     ldr pc, [ip, #0x00000NNN] Offset(&(.plt.got) - L1 - 8
257   };
258 
259   uint64_t offset = sym.getGotPltVA() - pltEntryAddr - 8;
260   if (!llvm::isUInt<27>(offset)) {
261     // We cannot encode the Offset, use the long form.
262     writePltLong(buf, sym.getGotPltVA(), pltEntryAddr);
263     return;
264   }
265   write32le(buf + 0, pltData[0] | ((offset >> 20) & 0xff));
266   write32le(buf + 4, pltData[1] | ((offset >> 12) & 0xff));
267   write32le(buf + 8, pltData[2] | (offset & 0xfff));
268   memcpy(buf + 12, trapInstr.data(), 4); // Pad to 16-byte boundary
269 }
270 
271 void ARM::addPltSymbols(InputSection &isec, uint64_t off) const {
272   addSyntheticLocal("$a", STT_NOTYPE, off, 0, isec);
273   addSyntheticLocal("$d", STT_NOTYPE, off + 12, 0, isec);
274 }
275 
276 bool ARM::needsThunk(RelExpr expr, RelType type, const InputFile *file,
277                      uint64_t branchAddr, const Symbol &s,
278                      int64_t /*a*/) const {
279   // If S is an undefined weak symbol and does not have a PLT entry then it
280   // will be resolved as a branch to the next instruction.
281   if (s.isUndefWeak() && !s.isInPlt())
282     return false;
283   // A state change from ARM to Thumb and vice versa must go through an
284   // interworking thunk if the relocation type is not R_ARM_CALL or
285   // R_ARM_THM_CALL.
286   switch (type) {
287   case R_ARM_PC24:
288   case R_ARM_PLT32:
289   case R_ARM_JUMP24:
290     // Source is ARM, all PLT entries are ARM so no interworking required.
291     // Otherwise we need to interwork if STT_FUNC Symbol has bit 0 set (Thumb).
292     if (s.isFunc() && expr == R_PC && (s.getVA() & 1))
293       return true;
294     LLVM_FALLTHROUGH;
295   case R_ARM_CALL: {
296     uint64_t dst = (expr == R_PLT_PC) ? s.getPltVA() : s.getVA();
297     return !inBranchRange(type, branchAddr, dst);
298   }
299   case R_ARM_THM_JUMP19:
300   case R_ARM_THM_JUMP24:
301     // Source is Thumb, all PLT entries are ARM so interworking is required.
302     // Otherwise we need to interwork if STT_FUNC Symbol has bit 0 clear (ARM).
303     if (expr == R_PLT_PC || (s.isFunc() && (s.getVA() & 1) == 0))
304       return true;
305     LLVM_FALLTHROUGH;
306   case R_ARM_THM_CALL: {
307     uint64_t dst = (expr == R_PLT_PC) ? s.getPltVA() : s.getVA();
308     return !inBranchRange(type, branchAddr, dst);
309   }
310   }
311   return false;
312 }
313 
314 uint32_t ARM::getThunkSectionSpacing() const {
315   // The placing of pre-created ThunkSections is controlled by the value
316   // thunkSectionSpacing returned by getThunkSectionSpacing(). The aim is to
317   // place the ThunkSection such that all branches from the InputSections
318   // prior to the ThunkSection can reach a Thunk placed at the end of the
319   // ThunkSection. Graphically:
320   // | up to thunkSectionSpacing .text input sections |
321   // | ThunkSection                                   |
322   // | up to thunkSectionSpacing .text input sections |
323   // | ThunkSection                                   |
324 
325   // Pre-created ThunkSections are spaced roughly 16MiB apart on ARMv7. This
326   // is to match the most common expected case of a Thumb 2 encoded BL, BLX or
327   // B.W:
328   // ARM B, BL, BLX range +/- 32MiB
329   // Thumb B.W, BL, BLX range +/- 16MiB
330   // Thumb B<cc>.W range +/- 1MiB
331   // If a branch cannot reach a pre-created ThunkSection a new one will be
332   // created so we can handle the rare cases of a Thumb 2 conditional branch.
333   // We intentionally use a lower size for thunkSectionSpacing than the maximum
334   // branch range so the end of the ThunkSection is more likely to be within
335   // range of the branch instruction that is furthest away. The value we shorten
336   // thunkSectionSpacing by is set conservatively to allow us to create 16,384
337   // 12 byte Thunks at any offset in a ThunkSection without risk of a branch to
338   // one of the Thunks going out of range.
339 
340   // On Arm the thunkSectionSpacing depends on the range of the Thumb Branch
341   // range. On earlier Architectures such as ARMv4, ARMv5 and ARMv6 (except
342   // ARMv6T2) the range is +/- 4MiB.
343 
344   return (config->armJ1J2BranchEncoding) ? 0x1000000 - 0x30000
345                                          : 0x400000 - 0x7500;
346 }
347 
348 bool ARM::inBranchRange(RelType type, uint64_t src, uint64_t dst) const {
349   uint64_t range;
350   uint64_t instrSize;
351 
352   switch (type) {
353   case R_ARM_PC24:
354   case R_ARM_PLT32:
355   case R_ARM_JUMP24:
356   case R_ARM_CALL:
357     range = 0x2000000;
358     instrSize = 4;
359     break;
360   case R_ARM_THM_JUMP19:
361     range = 0x100000;
362     instrSize = 2;
363     break;
364   case R_ARM_THM_JUMP24:
365   case R_ARM_THM_CALL:
366     range = config->armJ1J2BranchEncoding ? 0x1000000 : 0x400000;
367     instrSize = 2;
368     break;
369   default:
370     return true;
371   }
372   // PC at Src is 2 instructions ahead, immediate of branch is signed
373   if (src > dst)
374     range -= 2 * instrSize;
375   else
376     range += instrSize;
377 
378   if ((dst & 0x1) == 0)
379     // Destination is ARM, if ARM caller then Src is already 4-byte aligned.
380     // If Thumb Caller (BLX) the Src address has bottom 2 bits cleared to ensure
381     // destination will be 4 byte aligned.
382     src &= ~0x3;
383   else
384     // Bit 0 == 1 denotes Thumb state, it is not part of the range
385     dst &= ~0x1;
386 
387   uint64_t distance = (src > dst) ? src - dst : dst - src;
388   return distance <= range;
389 }
390 
391 // Helper to produce message text when LLD detects that a CALL relocation to
392 // a non STT_FUNC symbol that may result in incorrect interworking between ARM
393 // or Thumb.
394 static void stateChangeWarning(uint8_t *loc, RelType relt, const Symbol &s) {
395   assert(!s.isFunc());
396   if (s.isSection()) {
397     // Section symbols must be defined and in a section. Users cannot change
398     // the type. Use the section name as getName() returns an empty string.
399     warn(getErrorLocation(loc) + "branch and link relocation: " +
400          toString(relt) + " to STT_SECTION symbol " +
401          cast<Defined>(s).section->name + " ; interworking not performed");
402   } else {
403     // Warn with hint on how to alter the symbol type.
404     warn(getErrorLocation(loc) + "branch and link relocation: " +
405          toString(relt) + " to non STT_FUNC symbol: " + s.getName() +
406          " interworking not performed; consider using directive '.type " +
407          s.getName() +
408          ", %function' to give symbol type STT_FUNC if"
409          " interworking between ARM and Thumb is required");
410   }
411 }
412 
413 void ARM::relocate(uint8_t *loc, const Relocation &rel, uint64_t val) const {
414   switch (rel.type) {
415   case R_ARM_ABS32:
416   case R_ARM_BASE_PREL:
417   case R_ARM_GOTOFF32:
418   case R_ARM_GOT_BREL:
419   case R_ARM_GOT_PREL:
420   case R_ARM_REL32:
421   case R_ARM_RELATIVE:
422   case R_ARM_SBREL32:
423   case R_ARM_TARGET1:
424   case R_ARM_TARGET2:
425   case R_ARM_TLS_GD32:
426   case R_ARM_TLS_IE32:
427   case R_ARM_TLS_LDM32:
428   case R_ARM_TLS_LDO32:
429   case R_ARM_TLS_LE32:
430   case R_ARM_TLS_TPOFF32:
431   case R_ARM_TLS_DTPOFF32:
432     write32le(loc, val);
433     break;
434   case R_ARM_PREL31:
435     checkInt(loc, val, 31, rel);
436     write32le(loc, (read32le(loc) & 0x80000000) | (val & ~0x80000000));
437     break;
438   case R_ARM_CALL: {
439     // R_ARM_CALL is used for BL and BLX instructions, for symbols of type
440     // STT_FUNC we choose whether to write a BL or BLX depending on the
441     // value of bit 0 of Val. With bit 0 == 1 denoting Thumb. If the symbol is
442     // not of type STT_FUNC then we must preserve the original instruction.
443     // PLT entries are always ARM state so we know we don't need to interwork.
444     assert(rel.sym); // R_ARM_CALL is always reached via relocate().
445     bool bit0Thumb = val & 1;
446     bool isBlx = (read32le(loc) & 0xfe000000) == 0xfa000000;
447     // lld 10.0 and before always used bit0Thumb when deciding to write a BLX
448     // even when type not STT_FUNC.
449     if (!rel.sym->isFunc() && isBlx != bit0Thumb)
450       stateChangeWarning(loc, rel.type, *rel.sym);
451     if (rel.sym->isFunc() ? bit0Thumb : isBlx) {
452       // The BLX encoding is 0xfa:H:imm24 where Val = imm24:H:'1'
453       checkInt(loc, val, 26, rel);
454       write32le(loc, 0xfa000000 |                    // opcode
455                          ((val & 2) << 23) |         // H
456                          ((val >> 2) & 0x00ffffff)); // imm24
457       break;
458     }
459     // BLX (always unconditional) instruction to an ARM Target, select an
460     // unconditional BL.
461     write32le(loc, 0xeb000000 | (read32le(loc) & 0x00ffffff));
462     // fall through as BL encoding is shared with B
463   }
464     LLVM_FALLTHROUGH;
465   case R_ARM_JUMP24:
466   case R_ARM_PC24:
467   case R_ARM_PLT32:
468     checkInt(loc, val, 26, rel);
469     write32le(loc, (read32le(loc) & ~0x00ffffff) | ((val >> 2) & 0x00ffffff));
470     break;
471   case R_ARM_THM_JUMP11:
472     checkInt(loc, val, 12, rel);
473     write16le(loc, (read32le(loc) & 0xf800) | ((val >> 1) & 0x07ff));
474     break;
475   case R_ARM_THM_JUMP19:
476     // Encoding T3: Val = S:J2:J1:imm6:imm11:0
477     checkInt(loc, val, 21, rel);
478     write16le(loc,
479               (read16le(loc) & 0xfbc0) |   // opcode cond
480                   ((val >> 10) & 0x0400) | // S
481                   ((val >> 12) & 0x003f)); // imm6
482     write16le(loc + 2,
483               0x8000 |                    // opcode
484                   ((val >> 8) & 0x0800) | // J2
485                   ((val >> 5) & 0x2000) | // J1
486                   ((val >> 1) & 0x07ff)); // imm11
487     break;
488   case R_ARM_THM_CALL: {
489     // R_ARM_THM_CALL is used for BL and BLX instructions, for symbols of type
490     // STT_FUNC we choose whether to write a BL or BLX depending on the
491     // value of bit 0 of Val. With bit 0 == 0 denoting ARM, if the symbol is
492     // not of type STT_FUNC then we must preserve the original instruction.
493     // PLT entries are always ARM state so we know we need to interwork.
494     assert(rel.sym); // R_ARM_THM_CALL is always reached via relocate().
495     bool bit0Thumb = val & 1;
496     bool isBlx = (read16le(loc + 2) & 0x1000) == 0;
497     // lld 10.0 and before always used bit0Thumb when deciding to write a BLX
498     // even when type not STT_FUNC. PLT entries generated by LLD are always ARM.
499     if (!rel.sym->isFunc() && !rel.sym->isInPlt() && isBlx == bit0Thumb)
500       stateChangeWarning(loc, rel.type, *rel.sym);
501     if (rel.sym->isFunc() || rel.sym->isInPlt() ? !bit0Thumb : isBlx) {
502       // We are writing a BLX. Ensure BLX destination is 4-byte aligned. As
503       // the BLX instruction may only be two byte aligned. This must be done
504       // before overflow check.
505       val = alignTo(val, 4);
506       write16le(loc + 2, read16le(loc + 2) & ~0x1000);
507     } else {
508       write16le(loc + 2, (read16le(loc + 2) & ~0x1000) | 1 << 12);
509     }
510     if (!config->armJ1J2BranchEncoding) {
511       // Older Arm architectures do not support R_ARM_THM_JUMP24 and have
512       // different encoding rules and range due to J1 and J2 always being 1.
513       checkInt(loc, val, 23, rel);
514       write16le(loc,
515                 0xf000 |                     // opcode
516                     ((val >> 12) & 0x07ff)); // imm11
517       write16le(loc + 2,
518                 (read16le(loc + 2) & 0xd000) | // opcode
519                     0x2800 |                   // J1 == J2 == 1
520                     ((val >> 1) & 0x07ff));    // imm11
521       break;
522     }
523   }
524     // Fall through as rest of encoding is the same as B.W
525     LLVM_FALLTHROUGH;
526   case R_ARM_THM_JUMP24:
527     // Encoding B  T4, BL T1, BLX T2: Val = S:I1:I2:imm10:imm11:0
528     checkInt(loc, val, 25, rel);
529     write16le(loc,
530               0xf000 |                     // opcode
531                   ((val >> 14) & 0x0400) | // S
532                   ((val >> 12) & 0x03ff)); // imm10
533     write16le(loc + 2,
534               (read16le(loc + 2) & 0xd000) |                  // opcode
535                   (((~(val >> 10)) ^ (val >> 11)) & 0x2000) | // J1
536                   (((~(val >> 11)) ^ (val >> 13)) & 0x0800) | // J2
537                   ((val >> 1) & 0x07ff));                     // imm11
538     break;
539   case R_ARM_MOVW_ABS_NC:
540   case R_ARM_MOVW_PREL_NC:
541   case R_ARM_MOVW_BREL_NC:
542     write32le(loc, (read32le(loc) & ~0x000f0fff) | ((val & 0xf000) << 4) |
543                        (val & 0x0fff));
544     break;
545   case R_ARM_MOVT_ABS:
546   case R_ARM_MOVT_PREL:
547   case R_ARM_MOVT_BREL:
548     write32le(loc, (read32le(loc) & ~0x000f0fff) |
549                        (((val >> 16) & 0xf000) << 4) | ((val >> 16) & 0xfff));
550     break;
551   case R_ARM_THM_MOVT_ABS:
552   case R_ARM_THM_MOVT_PREL:
553   case R_ARM_THM_MOVT_BREL:
554     // Encoding T1: A = imm4:i:imm3:imm8
555     write16le(loc,
556               0xf2c0 |                     // opcode
557                   ((val >> 17) & 0x0400) | // i
558                   ((val >> 28) & 0x000f)); // imm4
559     write16le(loc + 2,
560               (read16le(loc + 2) & 0x8f00) | // opcode
561                   ((val >> 12) & 0x7000) |   // imm3
562                   ((val >> 16) & 0x00ff));   // imm8
563     break;
564   case R_ARM_THM_MOVW_ABS_NC:
565   case R_ARM_THM_MOVW_PREL_NC:
566   case R_ARM_THM_MOVW_BREL_NC:
567     // Encoding T3: A = imm4:i:imm3:imm8
568     write16le(loc,
569               0xf240 |                     // opcode
570                   ((val >> 1) & 0x0400) |  // i
571                   ((val >> 12) & 0x000f)); // imm4
572     write16le(loc + 2,
573               (read16le(loc + 2) & 0x8f00) | // opcode
574                   ((val << 4) & 0x7000) |    // imm3
575                   (val & 0x00ff));           // imm8
576     break;
577   case R_ARM_THM_ALU_PREL_11_0: {
578     // ADR encoding T2 (sub), T3 (add) i:imm3:imm8
579     int64_t imm = val;
580     uint16_t sub = 0;
581     if (imm < 0) {
582       imm = -imm;
583       sub = 0x00a0;
584     }
585     checkUInt(loc, imm, 12, rel);
586     write16le(loc, (read16le(loc) & 0xfb0f) | sub | (imm & 0x800) >> 1);
587     write16le(loc + 2,
588               (read16le(loc + 2) & 0x8f00) | (imm & 0x700) << 4 | (imm & 0xff));
589     break;
590   }
591   case R_ARM_THM_PC8:
592     // ADR and LDR literal encoding T1 positive offset only imm8:00
593     // R_ARM_THM_PC8 is S + A - Pa, we have ((S + A) | T) - Pa, if S is a
594     // function then addr is 0 (modulo 2) and Pa is 0 (modulo 4) so we can clear
595     // bottom bit to recover S + A - Pa.
596     if (rel.sym->isFunc())
597       val &= ~0x1;
598     checkUInt(loc, val, 10, rel);
599     checkAlignment(loc, val, 4, rel);
600     write16le(loc, (read16le(loc) & 0xff00) | (val & 0x3fc) >> 2);
601     break;
602   case R_ARM_THM_PC12: {
603     // LDR (literal) encoding T2, add = (U == '1') imm12
604     // imm12 is unsigned
605     // R_ARM_THM_PC12 is S + A - Pa, we have ((S + A) | T) - Pa, if S is a
606     // function then addr is 0 (modulo 2) and Pa is 0 (modulo 4) so we can clear
607     // bottom bit to recover S + A - Pa.
608     if (rel.sym->isFunc())
609       val &= ~0x1;
610     int64_t imm12 = val;
611     uint16_t u = 0x0080;
612     if (imm12 < 0) {
613       imm12 = -imm12;
614       u = 0;
615     }
616     checkUInt(loc, imm12, 12, rel);
617     write16le(loc, read16le(loc) | u);
618     write16le(loc + 2, (read16le(loc + 2) & 0xf000) | imm12);
619     break;
620   }
621   default:
622     error(getErrorLocation(loc) + "unrecognized relocation " +
623           toString(rel.type));
624   }
625 }
626 
627 int64_t ARM::getImplicitAddend(const uint8_t *buf, RelType type) const {
628   switch (type) {
629   default:
630     return 0;
631   case R_ARM_ABS32:
632   case R_ARM_BASE_PREL:
633   case R_ARM_GOTOFF32:
634   case R_ARM_GOT_BREL:
635   case R_ARM_GOT_PREL:
636   case R_ARM_REL32:
637   case R_ARM_TARGET1:
638   case R_ARM_TARGET2:
639   case R_ARM_TLS_GD32:
640   case R_ARM_TLS_LDM32:
641   case R_ARM_TLS_LDO32:
642   case R_ARM_TLS_IE32:
643   case R_ARM_TLS_LE32:
644     return SignExtend64<32>(read32le(buf));
645   case R_ARM_PREL31:
646     return SignExtend64<31>(read32le(buf));
647   case R_ARM_CALL:
648   case R_ARM_JUMP24:
649   case R_ARM_PC24:
650   case R_ARM_PLT32:
651     return SignExtend64<26>(read32le(buf) << 2);
652   case R_ARM_THM_JUMP11:
653     return SignExtend64<12>(read16le(buf) << 1);
654   case R_ARM_THM_JUMP19: {
655     // Encoding T3: A = S:J2:J1:imm10:imm6:0
656     uint16_t hi = read16le(buf);
657     uint16_t lo = read16le(buf + 2);
658     return SignExtend64<20>(((hi & 0x0400) << 10) | // S
659                             ((lo & 0x0800) << 8) |  // J2
660                             ((lo & 0x2000) << 5) |  // J1
661                             ((hi & 0x003f) << 12) | // imm6
662                             ((lo & 0x07ff) << 1));  // imm11:0
663   }
664   case R_ARM_THM_CALL:
665     if (!config->armJ1J2BranchEncoding) {
666       // Older Arm architectures do not support R_ARM_THM_JUMP24 and have
667       // different encoding rules and range due to J1 and J2 always being 1.
668       uint16_t hi = read16le(buf);
669       uint16_t lo = read16le(buf + 2);
670       return SignExtend64<22>(((hi & 0x7ff) << 12) | // imm11
671                               ((lo & 0x7ff) << 1));  // imm11:0
672       break;
673     }
674     LLVM_FALLTHROUGH;
675   case R_ARM_THM_JUMP24: {
676     // Encoding B T4, BL T1, BLX T2: A = S:I1:I2:imm10:imm11:0
677     // I1 = NOT(J1 EOR S), I2 = NOT(J2 EOR S)
678     uint16_t hi = read16le(buf);
679     uint16_t lo = read16le(buf + 2);
680     return SignExtend64<24>(((hi & 0x0400) << 14) |                    // S
681                             (~((lo ^ (hi << 3)) << 10) & 0x00800000) | // I1
682                             (~((lo ^ (hi << 1)) << 11) & 0x00400000) | // I2
683                             ((hi & 0x003ff) << 12) |                   // imm0
684                             ((lo & 0x007ff) << 1)); // imm11:0
685   }
686   // ELF for the ARM Architecture 4.6.1.1 the implicit addend for MOVW and
687   // MOVT is in the range -32768 <= A < 32768
688   case R_ARM_MOVW_ABS_NC:
689   case R_ARM_MOVT_ABS:
690   case R_ARM_MOVW_PREL_NC:
691   case R_ARM_MOVT_PREL:
692   case R_ARM_MOVW_BREL_NC:
693   case R_ARM_MOVT_BREL: {
694     uint64_t val = read32le(buf) & 0x000f0fff;
695     return SignExtend64<16>(((val & 0x000f0000) >> 4) | (val & 0x00fff));
696   }
697   case R_ARM_THM_MOVW_ABS_NC:
698   case R_ARM_THM_MOVT_ABS:
699   case R_ARM_THM_MOVW_PREL_NC:
700   case R_ARM_THM_MOVT_PREL:
701   case R_ARM_THM_MOVW_BREL_NC:
702   case R_ARM_THM_MOVT_BREL: {
703     // Encoding T3: A = imm4:i:imm3:imm8
704     uint16_t hi = read16le(buf);
705     uint16_t lo = read16le(buf + 2);
706     return SignExtend64<16>(((hi & 0x000f) << 12) | // imm4
707                             ((hi & 0x0400) << 1) |  // i
708                             ((lo & 0x7000) >> 4) |  // imm3
709                             (lo & 0x00ff));         // imm8
710   }
711   case R_ARM_THM_ALU_PREL_11_0: {
712     // Thumb2 ADR, which is an alias for a sub or add instruction with an
713     // unsigned immediate.
714     // ADR encoding T2 (sub), T3 (add) i:imm3:imm8
715     uint16_t hi = read16le(buf);
716     uint16_t lo = read16le(buf + 2);
717     uint64_t imm = (hi & 0x0400) << 1 | // i
718                    (lo & 0x7000) >> 4 | // imm3
719                    (lo & 0x00ff);       // imm8
720     // For sub, addend is negative, add is positive.
721     return (hi & 0x00f0) ? -imm : imm;
722   }
723   case R_ARM_THM_PC8:
724     // ADR and LDR (literal) encoding T1
725     // From ELF for the ARM Architecture the initial signed addend is formed
726     // from an unsigned field using expression (((imm8:00 + 4) & 0x3ff) – 4)
727     // this trick permits the PC bias of -4 to be encoded using imm8 = 0xff
728     return ((((read16le(buf) & 0xff) << 2) + 4) & 0x3ff) - 4;
729   case R_ARM_THM_PC12: {
730     // LDR (literal) encoding T2, add = (U == '1') imm12
731     bool u = read16le(buf) & 0x0080;
732     uint64_t imm12 = read16le(buf + 2) & 0x0fff;
733     return u ? imm12 : -imm12;
734   }
735   }
736 }
737 
738 TargetInfo *getARMTargetInfo() {
739   static ARM target;
740   return &target;
741 }
742 
743 } // namespace elf
744 } // namespace lld
745