1 //===-- ARMAsmBackend.cpp - ARM Assembler Backend -------------------------===//
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 "MCTargetDesc/ARMAsmBackend.h"
10 #include "MCTargetDesc/ARMAddressingModes.h"
11 #include "MCTargetDesc/ARMAsmBackendDarwin.h"
12 #include "MCTargetDesc/ARMAsmBackendELF.h"
13 #include "MCTargetDesc/ARMAsmBackendWinCOFF.h"
14 #include "MCTargetDesc/ARMFixupKinds.h"
15 #include "MCTargetDesc/ARMMCTargetDesc.h"
16 #include "llvm/ADT/StringSwitch.h"
17 #include "llvm/BinaryFormat/ELF.h"
18 #include "llvm/BinaryFormat/MachO.h"
19 #include "llvm/MC/MCAsmBackend.h"
20 #include "llvm/MC/MCAssembler.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCDirectives.h"
23 #include "llvm/MC/MCELFObjectWriter.h"
24 #include "llvm/MC/MCExpr.h"
25 #include "llvm/MC/MCFixupKindInfo.h"
26 #include "llvm/MC/MCObjectWriter.h"
27 #include "llvm/MC/MCRegisterInfo.h"
28 #include "llvm/MC/MCSectionELF.h"
29 #include "llvm/MC/MCSectionMachO.h"
30 #include "llvm/MC/MCSubtargetInfo.h"
31 #include "llvm/MC/MCValue.h"
32 #include "llvm/MC/MCAsmLayout.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/EndianStream.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/Format.h"
37 #include "llvm/Support/TargetParser.h"
38 #include "llvm/Support/raw_ostream.h"
39 using namespace llvm;
40
41 namespace {
42 class ARMELFObjectWriter : public MCELFObjectTargetWriter {
43 public:
ARMELFObjectWriter(uint8_t OSABI)44 ARMELFObjectWriter(uint8_t OSABI)
45 : MCELFObjectTargetWriter(/*Is64Bit*/ false, OSABI, ELF::EM_ARM,
46 /*HasRelocationAddend*/ false) {}
47 };
48 } // end anonymous namespace
49
getFixupKind(StringRef Name) const50 Optional<MCFixupKind> ARMAsmBackend::getFixupKind(StringRef Name) const {
51 if (STI.getTargetTriple().isOSBinFormatELF() && Name == "R_ARM_NONE")
52 return FK_NONE;
53
54 return MCAsmBackend::getFixupKind(Name);
55 }
56
getFixupKindInfo(MCFixupKind Kind) const57 const MCFixupKindInfo &ARMAsmBackend::getFixupKindInfo(MCFixupKind Kind) const {
58 unsigned IsPCRelConstant =
59 MCFixupKindInfo::FKF_IsPCRel | MCFixupKindInfo::FKF_Constant;
60 const static MCFixupKindInfo InfosLE[ARM::NumTargetFixupKinds] = {
61 // This table *must* be in the order that the fixup_* kinds are defined in
62 // ARMFixupKinds.h.
63 //
64 // Name Offset (bits) Size (bits) Flags
65 {"fixup_arm_ldst_pcrel_12", 0, 32, IsPCRelConstant},
66 {"fixup_t2_ldst_pcrel_12", 0, 32,
67 IsPCRelConstant | MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
68 {"fixup_arm_pcrel_10_unscaled", 0, 32, IsPCRelConstant},
69 {"fixup_arm_pcrel_10", 0, 32, IsPCRelConstant},
70 {"fixup_t2_pcrel_10", 0, 32,
71 MCFixupKindInfo::FKF_IsPCRel |
72 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
73 {"fixup_arm_pcrel_9", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
74 {"fixup_t2_pcrel_9", 0, 32,
75 IsPCRelConstant | MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
76 {"fixup_thumb_adr_pcrel_10", 0, 8,
77 IsPCRelConstant | MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
78 {"fixup_arm_adr_pcrel_12", 0, 32, IsPCRelConstant},
79 {"fixup_t2_adr_pcrel_12", 0, 32,
80 IsPCRelConstant | MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
81 {"fixup_arm_condbranch", 0, 24, MCFixupKindInfo::FKF_IsPCRel},
82 {"fixup_arm_uncondbranch", 0, 24, MCFixupKindInfo::FKF_IsPCRel},
83 {"fixup_t2_condbranch", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
84 {"fixup_t2_uncondbranch", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
85 {"fixup_arm_thumb_br", 0, 16, MCFixupKindInfo::FKF_IsPCRel},
86 {"fixup_arm_uncondbl", 0, 24, MCFixupKindInfo::FKF_IsPCRel},
87 {"fixup_arm_condbl", 0, 24, MCFixupKindInfo::FKF_IsPCRel},
88 {"fixup_arm_blx", 0, 24, MCFixupKindInfo::FKF_IsPCRel},
89 {"fixup_arm_thumb_bl", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
90 {"fixup_arm_thumb_blx", 0, 32,
91 MCFixupKindInfo::FKF_IsPCRel |
92 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
93 {"fixup_arm_thumb_cb", 0, 16, MCFixupKindInfo::FKF_IsPCRel},
94 {"fixup_arm_thumb_cp", 0, 8,
95 MCFixupKindInfo::FKF_IsPCRel |
96 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
97 {"fixup_arm_thumb_bcc", 0, 8, MCFixupKindInfo::FKF_IsPCRel},
98 // movw / movt: 16-bits immediate but scattered into two chunks 0 - 12, 16
99 // - 19.
100 {"fixup_arm_movt_hi16", 0, 20, 0},
101 {"fixup_arm_movw_lo16", 0, 20, 0},
102 {"fixup_t2_movt_hi16", 0, 20, 0},
103 {"fixup_t2_movw_lo16", 0, 20, 0},
104 {"fixup_arm_mod_imm", 0, 12, 0},
105 {"fixup_t2_so_imm", 0, 26, 0},
106 {"fixup_bf_branch", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
107 {"fixup_bf_target", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
108 {"fixup_bfl_target", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
109 {"fixup_bfc_target", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
110 {"fixup_bfcsel_else_target", 0, 32, 0},
111 {"fixup_wls", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
112 {"fixup_le", 0, 32, MCFixupKindInfo::FKF_IsPCRel}
113 };
114 const static MCFixupKindInfo InfosBE[ARM::NumTargetFixupKinds] = {
115 // This table *must* be in the order that the fixup_* kinds are defined in
116 // ARMFixupKinds.h.
117 //
118 // Name Offset (bits) Size (bits) Flags
119 {"fixup_arm_ldst_pcrel_12", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
120 {"fixup_t2_ldst_pcrel_12", 0, 32,
121 MCFixupKindInfo::FKF_IsPCRel |
122 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
123 {"fixup_arm_pcrel_10_unscaled", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
124 {"fixup_arm_pcrel_10", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
125 {"fixup_t2_pcrel_10", 0, 32,
126 MCFixupKindInfo::FKF_IsPCRel |
127 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
128 {"fixup_arm_pcrel_9", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
129 {"fixup_t2_pcrel_9", 0, 32,
130 MCFixupKindInfo::FKF_IsPCRel |
131 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
132 {"fixup_thumb_adr_pcrel_10", 8, 8,
133 MCFixupKindInfo::FKF_IsPCRel |
134 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
135 {"fixup_arm_adr_pcrel_12", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
136 {"fixup_t2_adr_pcrel_12", 0, 32,
137 MCFixupKindInfo::FKF_IsPCRel |
138 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
139 {"fixup_arm_condbranch", 8, 24, MCFixupKindInfo::FKF_IsPCRel},
140 {"fixup_arm_uncondbranch", 8, 24, MCFixupKindInfo::FKF_IsPCRel},
141 {"fixup_t2_condbranch", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
142 {"fixup_t2_uncondbranch", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
143 {"fixup_arm_thumb_br", 0, 16, MCFixupKindInfo::FKF_IsPCRel},
144 {"fixup_arm_uncondbl", 8, 24, MCFixupKindInfo::FKF_IsPCRel},
145 {"fixup_arm_condbl", 8, 24, MCFixupKindInfo::FKF_IsPCRel},
146 {"fixup_arm_blx", 8, 24, MCFixupKindInfo::FKF_IsPCRel},
147 {"fixup_arm_thumb_bl", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
148 {"fixup_arm_thumb_blx", 0, 32,
149 MCFixupKindInfo::FKF_IsPCRel |
150 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
151 {"fixup_arm_thumb_cb", 0, 16, MCFixupKindInfo::FKF_IsPCRel},
152 {"fixup_arm_thumb_cp", 8, 8,
153 MCFixupKindInfo::FKF_IsPCRel |
154 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
155 {"fixup_arm_thumb_bcc", 8, 8, MCFixupKindInfo::FKF_IsPCRel},
156 // movw / movt: 16-bits immediate but scattered into two chunks 0 - 12, 16
157 // - 19.
158 {"fixup_arm_movt_hi16", 12, 20, 0},
159 {"fixup_arm_movw_lo16", 12, 20, 0},
160 {"fixup_t2_movt_hi16", 12, 20, 0},
161 {"fixup_t2_movw_lo16", 12, 20, 0},
162 {"fixup_arm_mod_imm", 20, 12, 0},
163 {"fixup_t2_so_imm", 26, 6, 0},
164 {"fixup_bf_branch", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
165 {"fixup_bf_target", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
166 {"fixup_bfl_target", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
167 {"fixup_bfc_target", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
168 {"fixup_bfcsel_else_target", 0, 32, 0},
169 {"fixup_wls", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
170 {"fixup_le", 0, 32, MCFixupKindInfo::FKF_IsPCRel}
171 };
172
173 if (Kind < FirstTargetFixupKind)
174 return MCAsmBackend::getFixupKindInfo(Kind);
175
176 assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
177 "Invalid kind!");
178 return (Endian == support::little ? InfosLE
179 : InfosBE)[Kind - FirstTargetFixupKind];
180 }
181
handleAssemblerFlag(MCAssemblerFlag Flag)182 void ARMAsmBackend::handleAssemblerFlag(MCAssemblerFlag Flag) {
183 switch (Flag) {
184 default:
185 break;
186 case MCAF_Code16:
187 setIsThumb(true);
188 break;
189 case MCAF_Code32:
190 setIsThumb(false);
191 break;
192 }
193 }
194
getRelaxedOpcode(unsigned Op,const MCSubtargetInfo & STI) const195 unsigned ARMAsmBackend::getRelaxedOpcode(unsigned Op,
196 const MCSubtargetInfo &STI) const {
197 bool HasThumb2 = STI.getFeatureBits()[ARM::FeatureThumb2];
198 bool HasV8MBaselineOps = STI.getFeatureBits()[ARM::HasV8MBaselineOps];
199
200 switch (Op) {
201 default:
202 return Op;
203 case ARM::tBcc:
204 return HasThumb2 ? (unsigned)ARM::t2Bcc : Op;
205 case ARM::tLDRpci:
206 return HasThumb2 ? (unsigned)ARM::t2LDRpci : Op;
207 case ARM::tADR:
208 return HasThumb2 ? (unsigned)ARM::t2ADR : Op;
209 case ARM::tB:
210 return HasV8MBaselineOps ? (unsigned)ARM::t2B : Op;
211 case ARM::tCBZ:
212 return ARM::tHINT;
213 case ARM::tCBNZ:
214 return ARM::tHINT;
215 }
216 }
217
mayNeedRelaxation(const MCInst & Inst,const MCSubtargetInfo & STI) const218 bool ARMAsmBackend::mayNeedRelaxation(const MCInst &Inst,
219 const MCSubtargetInfo &STI) const {
220 if (getRelaxedOpcode(Inst.getOpcode(), STI) != Inst.getOpcode())
221 return true;
222 return false;
223 }
224
checkPCRelOffset(uint64_t Value,int64_t Min,int64_t Max)225 static const char *checkPCRelOffset(uint64_t Value, int64_t Min, int64_t Max) {
226 int64_t Offset = int64_t(Value) - 4;
227 if (Offset < Min || Offset > Max)
228 return "out of range pc-relative fixup value";
229 return nullptr;
230 }
231
reasonForFixupRelaxation(const MCFixup & Fixup,uint64_t Value) const232 const char *ARMAsmBackend::reasonForFixupRelaxation(const MCFixup &Fixup,
233 uint64_t Value) const {
234 switch (Fixup.getTargetKind()) {
235 case ARM::fixup_arm_thumb_br: {
236 // Relaxing tB to t2B. tB has a signed 12-bit displacement with the
237 // low bit being an implied zero. There's an implied +4 offset for the
238 // branch, so we adjust the other way here to determine what's
239 // encodable.
240 //
241 // Relax if the value is too big for a (signed) i8.
242 int64_t Offset = int64_t(Value) - 4;
243 if (Offset > 2046 || Offset < -2048)
244 return "out of range pc-relative fixup value";
245 break;
246 }
247 case ARM::fixup_arm_thumb_bcc: {
248 // Relaxing tBcc to t2Bcc. tBcc has a signed 9-bit displacement with the
249 // low bit being an implied zero. There's an implied +4 offset for the
250 // branch, so we adjust the other way here to determine what's
251 // encodable.
252 //
253 // Relax if the value is too big for a (signed) i8.
254 int64_t Offset = int64_t(Value) - 4;
255 if (Offset > 254 || Offset < -256)
256 return "out of range pc-relative fixup value";
257 break;
258 }
259 case ARM::fixup_thumb_adr_pcrel_10:
260 case ARM::fixup_arm_thumb_cp: {
261 // If the immediate is negative, greater than 1020, or not a multiple
262 // of four, the wide version of the instruction must be used.
263 int64_t Offset = int64_t(Value) - 4;
264 if (Offset & 3)
265 return "misaligned pc-relative fixup value";
266 else if (Offset > 1020 || Offset < 0)
267 return "out of range pc-relative fixup value";
268 break;
269 }
270 case ARM::fixup_arm_thumb_cb: {
271 // If we have a Thumb CBZ or CBNZ instruction and its target is the next
272 // instruction it is actually out of range for the instruction.
273 // It will be changed to a NOP.
274 int64_t Offset = (Value & ~1);
275 if (Offset == 2)
276 return "will be converted to nop";
277 break;
278 }
279 case ARM::fixup_bf_branch:
280 return checkPCRelOffset(Value, 0, 30);
281 case ARM::fixup_bf_target:
282 return checkPCRelOffset(Value, -0x10000, +0xfffe);
283 case ARM::fixup_bfl_target:
284 return checkPCRelOffset(Value, -0x40000, +0x3fffe);
285 case ARM::fixup_bfc_target:
286 return checkPCRelOffset(Value, -0x1000, +0xffe);
287 case ARM::fixup_wls:
288 return checkPCRelOffset(Value, 0, +0xffe);
289 case ARM::fixup_le:
290 // The offset field in the LE and LETP instructions is an 11-bit
291 // value shifted left by 2 (i.e. 0,2,4,...,4094), and it is
292 // interpreted as a negative offset from the value read from pc,
293 // i.e. from instruction_address+4.
294 //
295 // So an LE instruction can in principle address the instruction
296 // immediately after itself, or (not very usefully) the address
297 // half way through the 4-byte LE.
298 return checkPCRelOffset(Value, -0xffe, 0);
299 case ARM::fixup_bfcsel_else_target: {
300 if (Value != 2 && Value != 4)
301 return "out of range label-relative fixup value";
302 break;
303 }
304
305 default:
306 llvm_unreachable("Unexpected fixup kind in reasonForFixupRelaxation()!");
307 }
308 return nullptr;
309 }
310
fixupNeedsRelaxation(const MCFixup & Fixup,uint64_t Value,const MCRelaxableFragment * DF,const MCAsmLayout & Layout) const311 bool ARMAsmBackend::fixupNeedsRelaxation(const MCFixup &Fixup, uint64_t Value,
312 const MCRelaxableFragment *DF,
313 const MCAsmLayout &Layout) const {
314 return reasonForFixupRelaxation(Fixup, Value);
315 }
316
relaxInstruction(const MCInst & Inst,const MCSubtargetInfo & STI,MCInst & Res) const317 void ARMAsmBackend::relaxInstruction(const MCInst &Inst,
318 const MCSubtargetInfo &STI,
319 MCInst &Res) const {
320 unsigned RelaxedOp = getRelaxedOpcode(Inst.getOpcode(), STI);
321
322 // Sanity check w/ diagnostic if we get here w/ a bogus instruction.
323 if (RelaxedOp == Inst.getOpcode()) {
324 SmallString<256> Tmp;
325 raw_svector_ostream OS(Tmp);
326 Inst.dump_pretty(OS);
327 OS << "\n";
328 report_fatal_error("unexpected instruction to relax: " + OS.str());
329 }
330
331 // If we are changing Thumb CBZ or CBNZ instruction to a NOP, aka tHINT, we
332 // have to change the operands too.
333 if ((Inst.getOpcode() == ARM::tCBZ || Inst.getOpcode() == ARM::tCBNZ) &&
334 RelaxedOp == ARM::tHINT) {
335 Res.setOpcode(RelaxedOp);
336 Res.addOperand(MCOperand::createImm(0));
337 Res.addOperand(MCOperand::createImm(14));
338 Res.addOperand(MCOperand::createReg(0));
339 return;
340 }
341
342 // The rest of instructions we're relaxing have the same operands.
343 // We just need to update to the proper opcode.
344 Res = Inst;
345 Res.setOpcode(RelaxedOp);
346 }
347
writeNopData(raw_ostream & OS,uint64_t Count) const348 bool ARMAsmBackend::writeNopData(raw_ostream &OS, uint64_t Count) const {
349 const uint16_t Thumb1_16bitNopEncoding = 0x46c0; // using MOV r8,r8
350 const uint16_t Thumb2_16bitNopEncoding = 0xbf00; // NOP
351 const uint32_t ARMv4_NopEncoding = 0xe1a00000; // using MOV r0,r0
352 const uint32_t ARMv6T2_NopEncoding = 0xe320f000; // NOP
353 if (isThumb()) {
354 const uint16_t nopEncoding =
355 hasNOP() ? Thumb2_16bitNopEncoding : Thumb1_16bitNopEncoding;
356 uint64_t NumNops = Count / 2;
357 for (uint64_t i = 0; i != NumNops; ++i)
358 support::endian::write(OS, nopEncoding, Endian);
359 if (Count & 1)
360 OS << '\0';
361 return true;
362 }
363 // ARM mode
364 const uint32_t nopEncoding =
365 hasNOP() ? ARMv6T2_NopEncoding : ARMv4_NopEncoding;
366 uint64_t NumNops = Count / 4;
367 for (uint64_t i = 0; i != NumNops; ++i)
368 support::endian::write(OS, nopEncoding, Endian);
369 // FIXME: should this function return false when unable to write exactly
370 // 'Count' bytes with NOP encodings?
371 switch (Count % 4) {
372 default:
373 break; // No leftover bytes to write
374 case 1:
375 OS << '\0';
376 break;
377 case 2:
378 OS.write("\0\0", 2);
379 break;
380 case 3:
381 OS.write("\0\0\xa0", 3);
382 break;
383 }
384
385 return true;
386 }
387
swapHalfWords(uint32_t Value,bool IsLittleEndian)388 static uint32_t swapHalfWords(uint32_t Value, bool IsLittleEndian) {
389 if (IsLittleEndian) {
390 // Note that the halfwords are stored high first and low second in thumb;
391 // so we need to swap the fixup value here to map properly.
392 uint32_t Swapped = (Value & 0xFFFF0000) >> 16;
393 Swapped |= (Value & 0x0000FFFF) << 16;
394 return Swapped;
395 } else
396 return Value;
397 }
398
joinHalfWords(uint32_t FirstHalf,uint32_t SecondHalf,bool IsLittleEndian)399 static uint32_t joinHalfWords(uint32_t FirstHalf, uint32_t SecondHalf,
400 bool IsLittleEndian) {
401 uint32_t Value;
402
403 if (IsLittleEndian) {
404 Value = (SecondHalf & 0xFFFF) << 16;
405 Value |= (FirstHalf & 0xFFFF);
406 } else {
407 Value = (SecondHalf & 0xFFFF);
408 Value |= (FirstHalf & 0xFFFF) << 16;
409 }
410
411 return Value;
412 }
413
adjustFixupValue(const MCAssembler & Asm,const MCFixup & Fixup,const MCValue & Target,uint64_t Value,bool IsResolved,MCContext & Ctx,const MCSubtargetInfo * STI) const414 unsigned ARMAsmBackend::adjustFixupValue(const MCAssembler &Asm,
415 const MCFixup &Fixup,
416 const MCValue &Target, uint64_t Value,
417 bool IsResolved, MCContext &Ctx,
418 const MCSubtargetInfo* STI) const {
419 unsigned Kind = Fixup.getKind();
420
421 // MachO tries to make .o files that look vaguely pre-linked, so for MOVW/MOVT
422 // and .word relocations they put the Thumb bit into the addend if possible.
423 // Other relocation types don't want this bit though (branches couldn't encode
424 // it if it *was* present, and no other relocations exist) and it can
425 // interfere with checking valid expressions.
426 if (const MCSymbolRefExpr *A = Target.getSymA()) {
427 if (A->hasSubsectionsViaSymbols() && Asm.isThumbFunc(&A->getSymbol()) &&
428 A->getSymbol().isExternal() &&
429 (Kind == FK_Data_4 || Kind == ARM::fixup_arm_movw_lo16 ||
430 Kind == ARM::fixup_arm_movt_hi16 || Kind == ARM::fixup_t2_movw_lo16 ||
431 Kind == ARM::fixup_t2_movt_hi16))
432 Value |= 1;
433 }
434
435 switch (Kind) {
436 default:
437 Ctx.reportError(Fixup.getLoc(), "bad relocation fixup type");
438 return 0;
439 case FK_NONE:
440 case FK_Data_1:
441 case FK_Data_2:
442 case FK_Data_4:
443 return Value;
444 case FK_SecRel_2:
445 return Value;
446 case FK_SecRel_4:
447 return Value;
448 case ARM::fixup_arm_movt_hi16:
449 assert(STI != nullptr);
450 if (IsResolved || !STI->getTargetTriple().isOSBinFormatELF())
451 Value >>= 16;
452 LLVM_FALLTHROUGH;
453 case ARM::fixup_arm_movw_lo16: {
454 unsigned Hi4 = (Value & 0xF000) >> 12;
455 unsigned Lo12 = Value & 0x0FFF;
456 // inst{19-16} = Hi4;
457 // inst{11-0} = Lo12;
458 Value = (Hi4 << 16) | (Lo12);
459 return Value;
460 }
461 case ARM::fixup_t2_movt_hi16:
462 assert(STI != nullptr);
463 if (IsResolved || !STI->getTargetTriple().isOSBinFormatELF())
464 Value >>= 16;
465 LLVM_FALLTHROUGH;
466 case ARM::fixup_t2_movw_lo16: {
467 unsigned Hi4 = (Value & 0xF000) >> 12;
468 unsigned i = (Value & 0x800) >> 11;
469 unsigned Mid3 = (Value & 0x700) >> 8;
470 unsigned Lo8 = Value & 0x0FF;
471 // inst{19-16} = Hi4;
472 // inst{26} = i;
473 // inst{14-12} = Mid3;
474 // inst{7-0} = Lo8;
475 Value = (Hi4 << 16) | (i << 26) | (Mid3 << 12) | (Lo8);
476 return swapHalfWords(Value, Endian == support::little);
477 }
478 case ARM::fixup_arm_ldst_pcrel_12:
479 // ARM PC-relative values are offset by 8.
480 Value -= 4;
481 LLVM_FALLTHROUGH;
482 case ARM::fixup_t2_ldst_pcrel_12: {
483 // Offset by 4, adjusted by two due to the half-word ordering of thumb.
484 Value -= 4;
485 bool isAdd = true;
486 if ((int64_t)Value < 0) {
487 Value = -Value;
488 isAdd = false;
489 }
490 if (Value >= 4096) {
491 Ctx.reportError(Fixup.getLoc(), "out of range pc-relative fixup value");
492 return 0;
493 }
494 Value |= isAdd << 23;
495
496 // Same addressing mode as fixup_arm_pcrel_10,
497 // but with 16-bit halfwords swapped.
498 if (Kind == ARM::fixup_t2_ldst_pcrel_12)
499 return swapHalfWords(Value, Endian == support::little);
500
501 return Value;
502 }
503 case ARM::fixup_arm_adr_pcrel_12: {
504 // ARM PC-relative values are offset by 8.
505 Value -= 8;
506 unsigned opc = 4; // bits {24-21}. Default to add: 0b0100
507 if ((int64_t)Value < 0) {
508 Value = -Value;
509 opc = 2; // 0b0010
510 }
511 if (ARM_AM::getSOImmVal(Value) == -1) {
512 Ctx.reportError(Fixup.getLoc(), "out of range pc-relative fixup value");
513 return 0;
514 }
515 // Encode the immediate and shift the opcode into place.
516 return ARM_AM::getSOImmVal(Value) | (opc << 21);
517 }
518
519 case ARM::fixup_t2_adr_pcrel_12: {
520 Value -= 4;
521 unsigned opc = 0;
522 if ((int64_t)Value < 0) {
523 Value = -Value;
524 opc = 5;
525 }
526
527 uint32_t out = (opc << 21);
528 out |= (Value & 0x800) << 15;
529 out |= (Value & 0x700) << 4;
530 out |= (Value & 0x0FF);
531
532 return swapHalfWords(out, Endian == support::little);
533 }
534
535 case ARM::fixup_arm_condbranch:
536 case ARM::fixup_arm_uncondbranch:
537 case ARM::fixup_arm_uncondbl:
538 case ARM::fixup_arm_condbl:
539 case ARM::fixup_arm_blx:
540 // These values don't encode the low two bits since they're always zero.
541 // Offset by 8 just as above.
542 if (const MCSymbolRefExpr *SRE =
543 dyn_cast<MCSymbolRefExpr>(Fixup.getValue()))
544 if (SRE->getKind() == MCSymbolRefExpr::VK_TLSCALL)
545 return 0;
546 return 0xffffff & ((Value - 8) >> 2);
547 case ARM::fixup_t2_uncondbranch: {
548 Value = Value - 4;
549 if (!isInt<25>(Value)) {
550 Ctx.reportError(Fixup.getLoc(), "Relocation out of range");
551 return 0;
552 }
553
554 Value >>= 1; // Low bit is not encoded.
555
556 uint32_t out = 0;
557 bool I = Value & 0x800000;
558 bool J1 = Value & 0x400000;
559 bool J2 = Value & 0x200000;
560 J1 ^= I;
561 J2 ^= I;
562
563 out |= I << 26; // S bit
564 out |= !J1 << 13; // J1 bit
565 out |= !J2 << 11; // J2 bit
566 out |= (Value & 0x1FF800) << 5; // imm6 field
567 out |= (Value & 0x0007FF); // imm11 field
568
569 return swapHalfWords(out, Endian == support::little);
570 }
571 case ARM::fixup_t2_condbranch: {
572 Value = Value - 4;
573 if (!isInt<21>(Value)) {
574 Ctx.reportError(Fixup.getLoc(), "Relocation out of range");
575 return 0;
576 }
577
578 Value >>= 1; // Low bit is not encoded.
579
580 uint64_t out = 0;
581 out |= (Value & 0x80000) << 7; // S bit
582 out |= (Value & 0x40000) >> 7; // J2 bit
583 out |= (Value & 0x20000) >> 4; // J1 bit
584 out |= (Value & 0x1F800) << 5; // imm6 field
585 out |= (Value & 0x007FF); // imm11 field
586
587 return swapHalfWords(out, Endian == support::little);
588 }
589 case ARM::fixup_arm_thumb_bl: {
590 if (!isInt<25>(Value - 4) ||
591 (!STI->getFeatureBits()[ARM::FeatureThumb2] &&
592 !STI->getFeatureBits()[ARM::HasV8MBaselineOps] &&
593 !STI->getFeatureBits()[ARM::HasV6MOps] &&
594 !isInt<23>(Value - 4))) {
595 Ctx.reportError(Fixup.getLoc(), "Relocation out of range");
596 return 0;
597 }
598
599 // The value doesn't encode the low bit (always zero) and is offset by
600 // four. The 32-bit immediate value is encoded as
601 // imm32 = SignExtend(S:I1:I2:imm10:imm11:0)
602 // where I1 = NOT(J1 ^ S) and I2 = NOT(J2 ^ S).
603 // The value is encoded into disjoint bit positions in the destination
604 // opcode. x = unchanged, I = immediate value bit, S = sign extension bit,
605 // J = either J1 or J2 bit
606 //
607 // BL: xxxxxSIIIIIIIIII xxJxJIIIIIIIIIII
608 //
609 // Note that the halfwords are stored high first, low second; so we need
610 // to transpose the fixup value here to map properly.
611 uint32_t offset = (Value - 4) >> 1;
612 uint32_t signBit = (offset & 0x800000) >> 23;
613 uint32_t I1Bit = (offset & 0x400000) >> 22;
614 uint32_t J1Bit = (I1Bit ^ 0x1) ^ signBit;
615 uint32_t I2Bit = (offset & 0x200000) >> 21;
616 uint32_t J2Bit = (I2Bit ^ 0x1) ^ signBit;
617 uint32_t imm10Bits = (offset & 0x1FF800) >> 11;
618 uint32_t imm11Bits = (offset & 0x000007FF);
619
620 uint32_t FirstHalf = (((uint16_t)signBit << 10) | (uint16_t)imm10Bits);
621 uint32_t SecondHalf = (((uint16_t)J1Bit << 13) | ((uint16_t)J2Bit << 11) |
622 (uint16_t)imm11Bits);
623 return joinHalfWords(FirstHalf, SecondHalf, Endian == support::little);
624 }
625 case ARM::fixup_arm_thumb_blx: {
626 // The value doesn't encode the low two bits (always zero) and is offset by
627 // four (see fixup_arm_thumb_cp). The 32-bit immediate value is encoded as
628 // imm32 = SignExtend(S:I1:I2:imm10H:imm10L:00)
629 // where I1 = NOT(J1 ^ S) and I2 = NOT(J2 ^ S).
630 // The value is encoded into disjoint bit positions in the destination
631 // opcode. x = unchanged, I = immediate value bit, S = sign extension bit,
632 // J = either J1 or J2 bit, 0 = zero.
633 //
634 // BLX: xxxxxSIIIIIIIIII xxJxJIIIIIIIIII0
635 //
636 // Note that the halfwords are stored high first, low second; so we need
637 // to transpose the fixup value here to map properly.
638 if (Value % 4 != 0) {
639 Ctx.reportError(Fixup.getLoc(), "misaligned ARM call destination");
640 return 0;
641 }
642
643 uint32_t offset = (Value - 4) >> 2;
644 if (const MCSymbolRefExpr *SRE =
645 dyn_cast<MCSymbolRefExpr>(Fixup.getValue()))
646 if (SRE->getKind() == MCSymbolRefExpr::VK_TLSCALL)
647 offset = 0;
648 uint32_t signBit = (offset & 0x400000) >> 22;
649 uint32_t I1Bit = (offset & 0x200000) >> 21;
650 uint32_t J1Bit = (I1Bit ^ 0x1) ^ signBit;
651 uint32_t I2Bit = (offset & 0x100000) >> 20;
652 uint32_t J2Bit = (I2Bit ^ 0x1) ^ signBit;
653 uint32_t imm10HBits = (offset & 0xFFC00) >> 10;
654 uint32_t imm10LBits = (offset & 0x3FF);
655
656 uint32_t FirstHalf = (((uint16_t)signBit << 10) | (uint16_t)imm10HBits);
657 uint32_t SecondHalf = (((uint16_t)J1Bit << 13) | ((uint16_t)J2Bit << 11) |
658 ((uint16_t)imm10LBits) << 1);
659 return joinHalfWords(FirstHalf, SecondHalf, Endian == support::little);
660 }
661 case ARM::fixup_thumb_adr_pcrel_10:
662 case ARM::fixup_arm_thumb_cp:
663 // On CPUs supporting Thumb2, this will be relaxed to an ldr.w, otherwise we
664 // could have an error on our hands.
665 assert(STI != nullptr);
666 if (!STI->getFeatureBits()[ARM::FeatureThumb2] && IsResolved) {
667 const char *FixupDiagnostic = reasonForFixupRelaxation(Fixup, Value);
668 if (FixupDiagnostic) {
669 Ctx.reportError(Fixup.getLoc(), FixupDiagnostic);
670 return 0;
671 }
672 }
673 // Offset by 4, and don't encode the low two bits.
674 return ((Value - 4) >> 2) & 0xff;
675 case ARM::fixup_arm_thumb_cb: {
676 // CB instructions can only branch to offsets in [4, 126] in multiples of 2
677 // so ensure that the raw value LSB is zero and it lies in [2, 130].
678 // An offset of 2 will be relaxed to a NOP.
679 if ((int64_t)Value < 2 || Value > 0x82 || Value & 1) {
680 Ctx.reportError(Fixup.getLoc(), "out of range pc-relative fixup value");
681 return 0;
682 }
683 // Offset by 4 and don't encode the lower bit, which is always 0.
684 // FIXME: diagnose if no Thumb2
685 uint32_t Binary = (Value - 4) >> 1;
686 return ((Binary & 0x20) << 4) | ((Binary & 0x1f) << 3);
687 }
688 case ARM::fixup_arm_thumb_br:
689 // Offset by 4 and don't encode the lower bit, which is always 0.
690 assert(STI != nullptr);
691 if (!STI->getFeatureBits()[ARM::FeatureThumb2] &&
692 !STI->getFeatureBits()[ARM::HasV8MBaselineOps]) {
693 const char *FixupDiagnostic = reasonForFixupRelaxation(Fixup, Value);
694 if (FixupDiagnostic) {
695 Ctx.reportError(Fixup.getLoc(), FixupDiagnostic);
696 return 0;
697 }
698 }
699 return ((Value - 4) >> 1) & 0x7ff;
700 case ARM::fixup_arm_thumb_bcc:
701 // Offset by 4 and don't encode the lower bit, which is always 0.
702 assert(STI != nullptr);
703 if (!STI->getFeatureBits()[ARM::FeatureThumb2]) {
704 const char *FixupDiagnostic = reasonForFixupRelaxation(Fixup, Value);
705 if (FixupDiagnostic) {
706 Ctx.reportError(Fixup.getLoc(), FixupDiagnostic);
707 return 0;
708 }
709 }
710 return ((Value - 4) >> 1) & 0xff;
711 case ARM::fixup_arm_pcrel_10_unscaled: {
712 Value = Value - 8; // ARM fixups offset by an additional word and don't
713 // need to adjust for the half-word ordering.
714 bool isAdd = true;
715 if ((int64_t)Value < 0) {
716 Value = -Value;
717 isAdd = false;
718 }
719 // The value has the low 4 bits encoded in [3:0] and the high 4 in [11:8].
720 if (Value >= 256) {
721 Ctx.reportError(Fixup.getLoc(), "out of range pc-relative fixup value");
722 return 0;
723 }
724 Value = (Value & 0xf) | ((Value & 0xf0) << 4);
725 return Value | (isAdd << 23);
726 }
727 case ARM::fixup_arm_pcrel_10:
728 Value = Value - 4; // ARM fixups offset by an additional word and don't
729 // need to adjust for the half-word ordering.
730 LLVM_FALLTHROUGH;
731 case ARM::fixup_t2_pcrel_10: {
732 // Offset by 4, adjusted by two due to the half-word ordering of thumb.
733 Value = Value - 4;
734 bool isAdd = true;
735 if ((int64_t)Value < 0) {
736 Value = -Value;
737 isAdd = false;
738 }
739 // These values don't encode the low two bits since they're always zero.
740 Value >>= 2;
741 if (Value >= 256) {
742 Ctx.reportError(Fixup.getLoc(), "out of range pc-relative fixup value");
743 return 0;
744 }
745 Value |= isAdd << 23;
746
747 // Same addressing mode as fixup_arm_pcrel_10, but with 16-bit halfwords
748 // swapped.
749 if (Kind == ARM::fixup_t2_pcrel_10)
750 return swapHalfWords(Value, Endian == support::little);
751
752 return Value;
753 }
754 case ARM::fixup_arm_pcrel_9:
755 Value = Value - 4; // ARM fixups offset by an additional word and don't
756 // need to adjust for the half-word ordering.
757 LLVM_FALLTHROUGH;
758 case ARM::fixup_t2_pcrel_9: {
759 // Offset by 4, adjusted by two due to the half-word ordering of thumb.
760 Value = Value - 4;
761 bool isAdd = true;
762 if ((int64_t)Value < 0) {
763 Value = -Value;
764 isAdd = false;
765 }
766 // These values don't encode the low bit since it's always zero.
767 if (Value & 1) {
768 Ctx.reportError(Fixup.getLoc(), "invalid value for this fixup");
769 return 0;
770 }
771 Value >>= 1;
772 if (Value >= 256) {
773 Ctx.reportError(Fixup.getLoc(), "out of range pc-relative fixup value");
774 return 0;
775 }
776 Value |= isAdd << 23;
777
778 // Same addressing mode as fixup_arm_pcrel_9, but with 16-bit halfwords
779 // swapped.
780 if (Kind == ARM::fixup_t2_pcrel_9)
781 return swapHalfWords(Value, Endian == support::little);
782
783 return Value;
784 }
785 case ARM::fixup_arm_mod_imm:
786 Value = ARM_AM::getSOImmVal(Value);
787 if (Value >> 12) {
788 Ctx.reportError(Fixup.getLoc(), "out of range immediate fixup value");
789 return 0;
790 }
791 return Value;
792 case ARM::fixup_t2_so_imm: {
793 Value = ARM_AM::getT2SOImmVal(Value);
794 if ((int64_t)Value < 0) {
795 Ctx.reportError(Fixup.getLoc(), "out of range immediate fixup value");
796 return 0;
797 }
798 // Value will contain a 12-bit value broken up into a 4-bit shift in bits
799 // 11:8 and the 8-bit immediate in 0:7. The instruction has the immediate
800 // in 0:7. The 4-bit shift is split up into i:imm3 where i is placed at bit
801 // 10 of the upper half-word and imm3 is placed at 14:12 of the lower
802 // half-word.
803 uint64_t EncValue = 0;
804 EncValue |= (Value & 0x800) << 15;
805 EncValue |= (Value & 0x700) << 4;
806 EncValue |= (Value & 0xff);
807 return swapHalfWords(EncValue, Endian == support::little);
808 }
809 case ARM::fixup_bf_branch: {
810 const char *FixupDiagnostic = reasonForFixupRelaxation(Fixup, Value);
811 if (FixupDiagnostic) {
812 Ctx.reportError(Fixup.getLoc(), FixupDiagnostic);
813 return 0;
814 }
815 uint32_t out = (((Value - 4) >> 1) & 0xf) << 23;
816 return swapHalfWords(out, Endian == support::little);
817 }
818 case ARM::fixup_bf_target:
819 case ARM::fixup_bfl_target:
820 case ARM::fixup_bfc_target: {
821 const char *FixupDiagnostic = reasonForFixupRelaxation(Fixup, Value);
822 if (FixupDiagnostic) {
823 Ctx.reportError(Fixup.getLoc(), FixupDiagnostic);
824 return 0;
825 }
826 uint32_t out = 0;
827 uint32_t HighBitMask = (Kind == ARM::fixup_bf_target ? 0xf800 :
828 Kind == ARM::fixup_bfl_target ? 0x3f800 : 0x800);
829 out |= (((Value - 4) >> 1) & 0x1) << 11;
830 out |= (((Value - 4) >> 1) & 0x7fe);
831 out |= (((Value - 4) >> 1) & HighBitMask) << 5;
832 return swapHalfWords(out, Endian == support::little);
833 }
834 case ARM::fixup_bfcsel_else_target: {
835 // If this is a fixup of a branch future's else target then it should be a
836 // constant MCExpr representing the distance between the branch targetted
837 // and the instruction after that same branch.
838 Value = Target.getConstant();
839
840 const char *FixupDiagnostic = reasonForFixupRelaxation(Fixup, Value);
841 if (FixupDiagnostic) {
842 Ctx.reportError(Fixup.getLoc(), FixupDiagnostic);
843 return 0;
844 }
845 uint32_t out = ((Value >> 2) & 1) << 17;
846 return swapHalfWords(out, Endian == support::little);
847 }
848 case ARM::fixup_wls:
849 case ARM::fixup_le: {
850 const char *FixupDiagnostic = reasonForFixupRelaxation(Fixup, Value);
851 if (FixupDiagnostic) {
852 Ctx.reportError(Fixup.getLoc(), FixupDiagnostic);
853 return 0;
854 }
855 uint64_t real_value = Value - 4;
856 uint32_t out = 0;
857 if (Kind == ARM::fixup_le)
858 real_value = -real_value;
859 out |= ((real_value >> 1) & 0x1) << 11;
860 out |= ((real_value >> 1) & 0x7fe);
861 return swapHalfWords(out, Endian == support::little);
862 }
863 }
864 }
865
shouldForceRelocation(const MCAssembler & Asm,const MCFixup & Fixup,const MCValue & Target)866 bool ARMAsmBackend::shouldForceRelocation(const MCAssembler &Asm,
867 const MCFixup &Fixup,
868 const MCValue &Target) {
869 const MCSymbolRefExpr *A = Target.getSymA();
870 const MCSymbol *Sym = A ? &A->getSymbol() : nullptr;
871 const unsigned FixupKind = Fixup.getKind();
872 if (FixupKind == FK_NONE)
873 return true;
874 if (FixupKind == ARM::fixup_arm_thumb_bl) {
875 assert(Sym && "How did we resolve this?");
876
877 // If the symbol is external the linker will handle it.
878 // FIXME: Should we handle it as an optimization?
879
880 // If the symbol is out of range, produce a relocation and hope the
881 // linker can handle it. GNU AS produces an error in this case.
882 if (Sym->isExternal())
883 return true;
884 }
885 // Create relocations for unconditional branches to function symbols with
886 // different execution mode in ELF binaries.
887 if (Sym && Sym->isELF()) {
888 unsigned Type = cast<MCSymbolELF>(Sym)->getType();
889 if ((Type == ELF::STT_FUNC || Type == ELF::STT_GNU_IFUNC)) {
890 if (Asm.isThumbFunc(Sym) && (FixupKind == ARM::fixup_arm_uncondbranch))
891 return true;
892 if (!Asm.isThumbFunc(Sym) && (FixupKind == ARM::fixup_arm_thumb_br ||
893 FixupKind == ARM::fixup_arm_thumb_bl ||
894 FixupKind == ARM::fixup_t2_condbranch ||
895 FixupKind == ARM::fixup_t2_uncondbranch))
896 return true;
897 }
898 }
899 // We must always generate a relocation for BL/BLX instructions if we have
900 // a symbol to reference, as the linker relies on knowing the destination
901 // symbol's thumb-ness to get interworking right.
902 if (A && (FixupKind == ARM::fixup_arm_thumb_blx ||
903 FixupKind == ARM::fixup_arm_blx ||
904 FixupKind == ARM::fixup_arm_uncondbl ||
905 FixupKind == ARM::fixup_arm_condbl))
906 return true;
907 return false;
908 }
909
910 /// getFixupKindNumBytes - The number of bytes the fixup may change.
getFixupKindNumBytes(unsigned Kind)911 static unsigned getFixupKindNumBytes(unsigned Kind) {
912 switch (Kind) {
913 default:
914 llvm_unreachable("Unknown fixup kind!");
915
916 case FK_NONE:
917 return 0;
918
919 case FK_Data_1:
920 case ARM::fixup_arm_thumb_bcc:
921 case ARM::fixup_arm_thumb_cp:
922 case ARM::fixup_thumb_adr_pcrel_10:
923 return 1;
924
925 case FK_Data_2:
926 case ARM::fixup_arm_thumb_br:
927 case ARM::fixup_arm_thumb_cb:
928 case ARM::fixup_arm_mod_imm:
929 return 2;
930
931 case ARM::fixup_arm_pcrel_10_unscaled:
932 case ARM::fixup_arm_ldst_pcrel_12:
933 case ARM::fixup_arm_pcrel_10:
934 case ARM::fixup_arm_pcrel_9:
935 case ARM::fixup_arm_adr_pcrel_12:
936 case ARM::fixup_arm_uncondbl:
937 case ARM::fixup_arm_condbl:
938 case ARM::fixup_arm_blx:
939 case ARM::fixup_arm_condbranch:
940 case ARM::fixup_arm_uncondbranch:
941 return 3;
942
943 case FK_Data_4:
944 case ARM::fixup_t2_ldst_pcrel_12:
945 case ARM::fixup_t2_condbranch:
946 case ARM::fixup_t2_uncondbranch:
947 case ARM::fixup_t2_pcrel_10:
948 case ARM::fixup_t2_pcrel_9:
949 case ARM::fixup_t2_adr_pcrel_12:
950 case ARM::fixup_arm_thumb_bl:
951 case ARM::fixup_arm_thumb_blx:
952 case ARM::fixup_arm_movt_hi16:
953 case ARM::fixup_arm_movw_lo16:
954 case ARM::fixup_t2_movt_hi16:
955 case ARM::fixup_t2_movw_lo16:
956 case ARM::fixup_t2_so_imm:
957 case ARM::fixup_bf_branch:
958 case ARM::fixup_bf_target:
959 case ARM::fixup_bfl_target:
960 case ARM::fixup_bfc_target:
961 case ARM::fixup_bfcsel_else_target:
962 case ARM::fixup_wls:
963 case ARM::fixup_le:
964 return 4;
965
966 case FK_SecRel_2:
967 return 2;
968 case FK_SecRel_4:
969 return 4;
970 }
971 }
972
973 /// getFixupKindContainerSizeBytes - The number of bytes of the
974 /// container involved in big endian.
getFixupKindContainerSizeBytes(unsigned Kind)975 static unsigned getFixupKindContainerSizeBytes(unsigned Kind) {
976 switch (Kind) {
977 default:
978 llvm_unreachable("Unknown fixup kind!");
979
980 case FK_NONE:
981 return 0;
982
983 case FK_Data_1:
984 return 1;
985 case FK_Data_2:
986 return 2;
987 case FK_Data_4:
988 return 4;
989
990 case ARM::fixup_arm_thumb_bcc:
991 case ARM::fixup_arm_thumb_cp:
992 case ARM::fixup_thumb_adr_pcrel_10:
993 case ARM::fixup_arm_thumb_br:
994 case ARM::fixup_arm_thumb_cb:
995 // Instruction size is 2 bytes.
996 return 2;
997
998 case ARM::fixup_arm_pcrel_10_unscaled:
999 case ARM::fixup_arm_ldst_pcrel_12:
1000 case ARM::fixup_arm_pcrel_10:
1001 case ARM::fixup_arm_pcrel_9:
1002 case ARM::fixup_arm_adr_pcrel_12:
1003 case ARM::fixup_arm_uncondbl:
1004 case ARM::fixup_arm_condbl:
1005 case ARM::fixup_arm_blx:
1006 case ARM::fixup_arm_condbranch:
1007 case ARM::fixup_arm_uncondbranch:
1008 case ARM::fixup_t2_ldst_pcrel_12:
1009 case ARM::fixup_t2_condbranch:
1010 case ARM::fixup_t2_uncondbranch:
1011 case ARM::fixup_t2_pcrel_10:
1012 case ARM::fixup_t2_adr_pcrel_12:
1013 case ARM::fixup_arm_thumb_bl:
1014 case ARM::fixup_arm_thumb_blx:
1015 case ARM::fixup_arm_movt_hi16:
1016 case ARM::fixup_arm_movw_lo16:
1017 case ARM::fixup_t2_movt_hi16:
1018 case ARM::fixup_t2_movw_lo16:
1019 case ARM::fixup_arm_mod_imm:
1020 case ARM::fixup_t2_so_imm:
1021 case ARM::fixup_bf_branch:
1022 case ARM::fixup_bf_target:
1023 case ARM::fixup_bfl_target:
1024 case ARM::fixup_bfc_target:
1025 case ARM::fixup_bfcsel_else_target:
1026 case ARM::fixup_wls:
1027 case ARM::fixup_le:
1028 // Instruction size is 4 bytes.
1029 return 4;
1030 }
1031 }
1032
applyFixup(const MCAssembler & Asm,const MCFixup & Fixup,const MCValue & Target,MutableArrayRef<char> Data,uint64_t Value,bool IsResolved,const MCSubtargetInfo * STI) const1033 void ARMAsmBackend::applyFixup(const MCAssembler &Asm, const MCFixup &Fixup,
1034 const MCValue &Target,
1035 MutableArrayRef<char> Data, uint64_t Value,
1036 bool IsResolved,
1037 const MCSubtargetInfo* STI) const {
1038 unsigned NumBytes = getFixupKindNumBytes(Fixup.getKind());
1039 MCContext &Ctx = Asm.getContext();
1040 Value = adjustFixupValue(Asm, Fixup, Target, Value, IsResolved, Ctx, STI);
1041 if (!Value)
1042 return; // Doesn't change encoding.
1043
1044 unsigned Offset = Fixup.getOffset();
1045 assert(Offset + NumBytes <= Data.size() && "Invalid fixup offset!");
1046
1047 // Used to point to big endian bytes.
1048 unsigned FullSizeBytes;
1049 if (Endian == support::big) {
1050 FullSizeBytes = getFixupKindContainerSizeBytes(Fixup.getKind());
1051 assert((Offset + FullSizeBytes) <= Data.size() && "Invalid fixup size!");
1052 assert(NumBytes <= FullSizeBytes && "Invalid fixup size!");
1053 }
1054
1055 // For each byte of the fragment that the fixup touches, mask in the bits from
1056 // the fixup value. The Value has been "split up" into the appropriate
1057 // bitfields above.
1058 for (unsigned i = 0; i != NumBytes; ++i) {
1059 unsigned Idx = Endian == support::little ? i : (FullSizeBytes - 1 - i);
1060 Data[Offset + Idx] |= uint8_t((Value >> (i * 8)) & 0xff);
1061 }
1062 }
1063
1064 namespace CU {
1065
1066 /// Compact unwind encoding values.
1067 enum CompactUnwindEncodings {
1068 UNWIND_ARM_MODE_MASK = 0x0F000000,
1069 UNWIND_ARM_MODE_FRAME = 0x01000000,
1070 UNWIND_ARM_MODE_FRAME_D = 0x02000000,
1071 UNWIND_ARM_MODE_DWARF = 0x04000000,
1072
1073 UNWIND_ARM_FRAME_STACK_ADJUST_MASK = 0x00C00000,
1074
1075 UNWIND_ARM_FRAME_FIRST_PUSH_R4 = 0x00000001,
1076 UNWIND_ARM_FRAME_FIRST_PUSH_R5 = 0x00000002,
1077 UNWIND_ARM_FRAME_FIRST_PUSH_R6 = 0x00000004,
1078
1079 UNWIND_ARM_FRAME_SECOND_PUSH_R8 = 0x00000008,
1080 UNWIND_ARM_FRAME_SECOND_PUSH_R9 = 0x00000010,
1081 UNWIND_ARM_FRAME_SECOND_PUSH_R10 = 0x00000020,
1082 UNWIND_ARM_FRAME_SECOND_PUSH_R11 = 0x00000040,
1083 UNWIND_ARM_FRAME_SECOND_PUSH_R12 = 0x00000080,
1084
1085 UNWIND_ARM_FRAME_D_REG_COUNT_MASK = 0x00000F00,
1086
1087 UNWIND_ARM_DWARF_SECTION_OFFSET = 0x00FFFFFF
1088 };
1089
1090 } // end CU namespace
1091
1092 /// Generate compact unwind encoding for the function based on the CFI
1093 /// instructions. If the CFI instructions describe a frame that cannot be
1094 /// encoded in compact unwind, the method returns UNWIND_ARM_MODE_DWARF which
1095 /// tells the runtime to fallback and unwind using dwarf.
generateCompactUnwindEncoding(ArrayRef<MCCFIInstruction> Instrs) const1096 uint32_t ARMAsmBackendDarwin::generateCompactUnwindEncoding(
1097 ArrayRef<MCCFIInstruction> Instrs) const {
1098 DEBUG_WITH_TYPE("compact-unwind", llvm::dbgs() << "generateCU()\n");
1099 // Only armv7k uses CFI based unwinding.
1100 if (Subtype != MachO::CPU_SUBTYPE_ARM_V7K)
1101 return 0;
1102 // No .cfi directives means no frame.
1103 if (Instrs.empty())
1104 return 0;
1105 // Start off assuming CFA is at SP+0.
1106 unsigned CFARegister = ARM::SP;
1107 int CFARegisterOffset = 0;
1108 // Mark savable registers as initially unsaved
1109 DenseMap<unsigned, int> RegOffsets;
1110 int FloatRegCount = 0;
1111 // Process each .cfi directive and build up compact unwind info.
1112 for (size_t i = 0, e = Instrs.size(); i != e; ++i) {
1113 unsigned Reg;
1114 const MCCFIInstruction &Inst = Instrs[i];
1115 switch (Inst.getOperation()) {
1116 case MCCFIInstruction::OpDefCfa: // DW_CFA_def_cfa
1117 CFARegisterOffset = -Inst.getOffset();
1118 CFARegister = *MRI.getLLVMRegNum(Inst.getRegister(), true);
1119 break;
1120 case MCCFIInstruction::OpDefCfaOffset: // DW_CFA_def_cfa_offset
1121 CFARegisterOffset = -Inst.getOffset();
1122 break;
1123 case MCCFIInstruction::OpDefCfaRegister: // DW_CFA_def_cfa_register
1124 CFARegister = *MRI.getLLVMRegNum(Inst.getRegister(), true);
1125 break;
1126 case MCCFIInstruction::OpOffset: // DW_CFA_offset
1127 Reg = *MRI.getLLVMRegNum(Inst.getRegister(), true);
1128 if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
1129 RegOffsets[Reg] = Inst.getOffset();
1130 else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg)) {
1131 RegOffsets[Reg] = Inst.getOffset();
1132 ++FloatRegCount;
1133 } else {
1134 DEBUG_WITH_TYPE("compact-unwind",
1135 llvm::dbgs() << ".cfi_offset on unknown register="
1136 << Inst.getRegister() << "\n");
1137 return CU::UNWIND_ARM_MODE_DWARF;
1138 }
1139 break;
1140 case MCCFIInstruction::OpRelOffset: // DW_CFA_advance_loc
1141 // Ignore
1142 break;
1143 default:
1144 // Directive not convertable to compact unwind, bail out.
1145 DEBUG_WITH_TYPE("compact-unwind",
1146 llvm::dbgs()
1147 << "CFI directive not compatiable with comact "
1148 "unwind encoding, opcode=" << Inst.getOperation()
1149 << "\n");
1150 return CU::UNWIND_ARM_MODE_DWARF;
1151 break;
1152 }
1153 }
1154
1155 // If no frame set up, return no unwind info.
1156 if ((CFARegister == ARM::SP) && (CFARegisterOffset == 0))
1157 return 0;
1158
1159 // Verify standard frame (lr/r7) was used.
1160 if (CFARegister != ARM::R7) {
1161 DEBUG_WITH_TYPE("compact-unwind", llvm::dbgs() << "frame register is "
1162 << CFARegister
1163 << " instead of r7\n");
1164 return CU::UNWIND_ARM_MODE_DWARF;
1165 }
1166 int StackAdjust = CFARegisterOffset - 8;
1167 if (RegOffsets.lookup(ARM::LR) != (-4 - StackAdjust)) {
1168 DEBUG_WITH_TYPE("compact-unwind",
1169 llvm::dbgs()
1170 << "LR not saved as standard frame, StackAdjust="
1171 << StackAdjust
1172 << ", CFARegisterOffset=" << CFARegisterOffset
1173 << ", lr save at offset=" << RegOffsets[14] << "\n");
1174 return CU::UNWIND_ARM_MODE_DWARF;
1175 }
1176 if (RegOffsets.lookup(ARM::R7) != (-8 - StackAdjust)) {
1177 DEBUG_WITH_TYPE("compact-unwind",
1178 llvm::dbgs() << "r7 not saved as standard frame\n");
1179 return CU::UNWIND_ARM_MODE_DWARF;
1180 }
1181 uint32_t CompactUnwindEncoding = CU::UNWIND_ARM_MODE_FRAME;
1182
1183 // If var-args are used, there may be a stack adjust required.
1184 switch (StackAdjust) {
1185 case 0:
1186 break;
1187 case 4:
1188 CompactUnwindEncoding |= 0x00400000;
1189 break;
1190 case 8:
1191 CompactUnwindEncoding |= 0x00800000;
1192 break;
1193 case 12:
1194 CompactUnwindEncoding |= 0x00C00000;
1195 break;
1196 default:
1197 DEBUG_WITH_TYPE("compact-unwind", llvm::dbgs()
1198 << ".cfi_def_cfa stack adjust ("
1199 << StackAdjust << ") out of range\n");
1200 return CU::UNWIND_ARM_MODE_DWARF;
1201 }
1202
1203 // If r6 is saved, it must be right below r7.
1204 static struct {
1205 unsigned Reg;
1206 unsigned Encoding;
1207 } GPRCSRegs[] = {{ARM::R6, CU::UNWIND_ARM_FRAME_FIRST_PUSH_R6},
1208 {ARM::R5, CU::UNWIND_ARM_FRAME_FIRST_PUSH_R5},
1209 {ARM::R4, CU::UNWIND_ARM_FRAME_FIRST_PUSH_R4},
1210 {ARM::R12, CU::UNWIND_ARM_FRAME_SECOND_PUSH_R12},
1211 {ARM::R11, CU::UNWIND_ARM_FRAME_SECOND_PUSH_R11},
1212 {ARM::R10, CU::UNWIND_ARM_FRAME_SECOND_PUSH_R10},
1213 {ARM::R9, CU::UNWIND_ARM_FRAME_SECOND_PUSH_R9},
1214 {ARM::R8, CU::UNWIND_ARM_FRAME_SECOND_PUSH_R8}};
1215
1216 int CurOffset = -8 - StackAdjust;
1217 for (auto CSReg : GPRCSRegs) {
1218 auto Offset = RegOffsets.find(CSReg.Reg);
1219 if (Offset == RegOffsets.end())
1220 continue;
1221
1222 int RegOffset = Offset->second;
1223 if (RegOffset != CurOffset - 4) {
1224 DEBUG_WITH_TYPE("compact-unwind",
1225 llvm::dbgs() << MRI.getName(CSReg.Reg) << " saved at "
1226 << RegOffset << " but only supported at "
1227 << CurOffset << "\n");
1228 return CU::UNWIND_ARM_MODE_DWARF;
1229 }
1230 CompactUnwindEncoding |= CSReg.Encoding;
1231 CurOffset -= 4;
1232 }
1233
1234 // If no floats saved, we are done.
1235 if (FloatRegCount == 0)
1236 return CompactUnwindEncoding;
1237
1238 // Switch mode to include D register saving.
1239 CompactUnwindEncoding &= ~CU::UNWIND_ARM_MODE_MASK;
1240 CompactUnwindEncoding |= CU::UNWIND_ARM_MODE_FRAME_D;
1241
1242 // FIXME: supporting more than 4 saved D-registers compactly would be trivial,
1243 // but needs coordination with the linker and libunwind.
1244 if (FloatRegCount > 4) {
1245 DEBUG_WITH_TYPE("compact-unwind",
1246 llvm::dbgs() << "unsupported number of D registers saved ("
1247 << FloatRegCount << ")\n");
1248 return CU::UNWIND_ARM_MODE_DWARF;
1249 }
1250
1251 // Floating point registers must either be saved sequentially, or we defer to
1252 // DWARF. No gaps allowed here so check that each saved d-register is
1253 // precisely where it should be.
1254 static unsigned FPRCSRegs[] = { ARM::D8, ARM::D10, ARM::D12, ARM::D14 };
1255 for (int Idx = FloatRegCount - 1; Idx >= 0; --Idx) {
1256 auto Offset = RegOffsets.find(FPRCSRegs[Idx]);
1257 if (Offset == RegOffsets.end()) {
1258 DEBUG_WITH_TYPE("compact-unwind",
1259 llvm::dbgs() << FloatRegCount << " D-regs saved, but "
1260 << MRI.getName(FPRCSRegs[Idx])
1261 << " not saved\n");
1262 return CU::UNWIND_ARM_MODE_DWARF;
1263 } else if (Offset->second != CurOffset - 8) {
1264 DEBUG_WITH_TYPE("compact-unwind",
1265 llvm::dbgs() << FloatRegCount << " D-regs saved, but "
1266 << MRI.getName(FPRCSRegs[Idx])
1267 << " saved at " << Offset->second
1268 << ", expected at " << CurOffset - 8
1269 << "\n");
1270 return CU::UNWIND_ARM_MODE_DWARF;
1271 }
1272 CurOffset -= 8;
1273 }
1274
1275 return CompactUnwindEncoding | ((FloatRegCount - 1) << 8);
1276 }
1277
getMachOSubTypeFromArch(StringRef Arch)1278 static MachO::CPUSubTypeARM getMachOSubTypeFromArch(StringRef Arch) {
1279 ARM::ArchKind AK = ARM::parseArch(Arch);
1280 switch (AK) {
1281 default:
1282 return MachO::CPU_SUBTYPE_ARM_V7;
1283 case ARM::ArchKind::ARMV4T:
1284 return MachO::CPU_SUBTYPE_ARM_V4T;
1285 case ARM::ArchKind::ARMV5T:
1286 case ARM::ArchKind::ARMV5TE:
1287 case ARM::ArchKind::ARMV5TEJ:
1288 return MachO::CPU_SUBTYPE_ARM_V5;
1289 case ARM::ArchKind::ARMV6:
1290 case ARM::ArchKind::ARMV6K:
1291 return MachO::CPU_SUBTYPE_ARM_V6;
1292 case ARM::ArchKind::ARMV7A:
1293 return MachO::CPU_SUBTYPE_ARM_V7;
1294 case ARM::ArchKind::ARMV7S:
1295 return MachO::CPU_SUBTYPE_ARM_V7S;
1296 case ARM::ArchKind::ARMV7K:
1297 return MachO::CPU_SUBTYPE_ARM_V7K;
1298 case ARM::ArchKind::ARMV6M:
1299 return MachO::CPU_SUBTYPE_ARM_V6M;
1300 case ARM::ArchKind::ARMV7M:
1301 return MachO::CPU_SUBTYPE_ARM_V7M;
1302 case ARM::ArchKind::ARMV7EM:
1303 return MachO::CPU_SUBTYPE_ARM_V7EM;
1304 }
1305 }
1306
createARMAsmBackend(const Target & T,const MCSubtargetInfo & STI,const MCRegisterInfo & MRI,const MCTargetOptions & Options,support::endianness Endian)1307 static MCAsmBackend *createARMAsmBackend(const Target &T,
1308 const MCSubtargetInfo &STI,
1309 const MCRegisterInfo &MRI,
1310 const MCTargetOptions &Options,
1311 support::endianness Endian) {
1312 const Triple &TheTriple = STI.getTargetTriple();
1313 switch (TheTriple.getObjectFormat()) {
1314 default:
1315 llvm_unreachable("unsupported object format");
1316 case Triple::MachO: {
1317 MachO::CPUSubTypeARM CS = getMachOSubTypeFromArch(TheTriple.getArchName());
1318 return new ARMAsmBackendDarwin(T, STI, MRI, CS);
1319 }
1320 case Triple::COFF:
1321 assert(TheTriple.isOSWindows() && "non-Windows ARM COFF is not supported");
1322 return new ARMAsmBackendWinCOFF(T, STI);
1323 case Triple::ELF:
1324 assert(TheTriple.isOSBinFormatELF() && "using ELF for non-ELF target");
1325 uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
1326 return new ARMAsmBackendELF(T, STI, OSABI, Endian);
1327 }
1328 }
1329
createARMLEAsmBackend(const Target & T,const MCSubtargetInfo & STI,const MCRegisterInfo & MRI,const MCTargetOptions & Options)1330 MCAsmBackend *llvm::createARMLEAsmBackend(const Target &T,
1331 const MCSubtargetInfo &STI,
1332 const MCRegisterInfo &MRI,
1333 const MCTargetOptions &Options) {
1334 return createARMAsmBackend(T, STI, MRI, Options, support::little);
1335 }
1336
createARMBEAsmBackend(const Target & T,const MCSubtargetInfo & STI,const MCRegisterInfo & MRI,const MCTargetOptions & Options)1337 MCAsmBackend *llvm::createARMBEAsmBackend(const Target &T,
1338 const MCSubtargetInfo &STI,
1339 const MCRegisterInfo &MRI,
1340 const MCTargetOptions &Options) {
1341 return createARMAsmBackend(T, STI, MRI, Options, support::big);
1342 }
1343