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