1 //===-- ARMAsmBackend.cpp - ARM Assembler Backend -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "MCTargetDesc/ARMMCTargetDesc.h"
11 #include "MCTargetDesc/ARMAddressingModes.h"
12 #include "MCTargetDesc/ARMAsmBackend.h"
13 #include "MCTargetDesc/ARMAsmBackendDarwin.h"
14 #include "MCTargetDesc/ARMAsmBackendELF.h"
15 #include "MCTargetDesc/ARMAsmBackendWinCOFF.h"
16 #include "MCTargetDesc/ARMBaseInfo.h"
17 #include "MCTargetDesc/ARMFixupKinds.h"
18 #include "llvm/ADT/StringSwitch.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/MCMachObjectWriter.h"
27 #include "llvm/MC/MCObjectWriter.h"
28 #include "llvm/MC/MCRegisterInfo.h"
29 #include "llvm/MC/MCSectionELF.h"
30 #include "llvm/MC/MCSectionMachO.h"
31 #include "llvm/MC/MCSubtargetInfo.h"
32 #include "llvm/MC/MCValue.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ELF.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/Format.h"
37 #include "llvm/Support/MachO.h"
38 #include "llvm/Support/TargetParser.h"
39 #include "llvm/Support/raw_ostream.h"
43 class ARMELFObjectWriter : public MCELFObjectTargetWriter {
45 ARMELFObjectWriter(uint8_t OSABI)
46 : MCELFObjectTargetWriter(/*Is64Bit*/ false, OSABI, ELF::EM_ARM,
47 /*HasRelocationAddend*/ false) {}
50 const MCFixupKindInfo &ARMAsmBackend::getFixupKindInfo(MCFixupKind Kind) const {
51 const static MCFixupKindInfo InfosLE[ARM::NumTargetFixupKinds] = {
52 // This table *must* be in the order that the fixup_* kinds are defined in
55 // Name Offset (bits) Size (bits) Flags
56 {"fixup_arm_ldst_pcrel_12", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
57 {"fixup_t2_ldst_pcrel_12", 0, 32,
58 MCFixupKindInfo::FKF_IsPCRel |
59 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
60 {"fixup_arm_pcrel_10_unscaled", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
61 {"fixup_arm_pcrel_10", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
62 {"fixup_t2_pcrel_10", 0, 32,
63 MCFixupKindInfo::FKF_IsPCRel |
64 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
65 {"fixup_arm_pcrel_9", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
66 {"fixup_t2_pcrel_9", 0, 32,
67 MCFixupKindInfo::FKF_IsPCRel |
68 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
69 {"fixup_thumb_adr_pcrel_10", 0, 8,
70 MCFixupKindInfo::FKF_IsPCRel |
71 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
72 {"fixup_arm_adr_pcrel_12", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
73 {"fixup_t2_adr_pcrel_12", 0, 32,
74 MCFixupKindInfo::FKF_IsPCRel |
75 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
76 {"fixup_arm_condbranch", 0, 24, MCFixupKindInfo::FKF_IsPCRel},
77 {"fixup_arm_uncondbranch", 0, 24, MCFixupKindInfo::FKF_IsPCRel},
78 {"fixup_t2_condbranch", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
79 {"fixup_t2_uncondbranch", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
80 {"fixup_arm_thumb_br", 0, 16, MCFixupKindInfo::FKF_IsPCRel},
81 {"fixup_arm_uncondbl", 0, 24, MCFixupKindInfo::FKF_IsPCRel},
82 {"fixup_arm_condbl", 0, 24, MCFixupKindInfo::FKF_IsPCRel},
83 {"fixup_arm_blx", 0, 24, MCFixupKindInfo::FKF_IsPCRel},
84 {"fixup_arm_thumb_bl", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
85 {"fixup_arm_thumb_blx", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
86 {"fixup_arm_thumb_cb", 0, 16, MCFixupKindInfo::FKF_IsPCRel},
87 {"fixup_arm_thumb_cp", 0, 8,
88 MCFixupKindInfo::FKF_IsPCRel |
89 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
90 {"fixup_arm_thumb_bcc", 0, 8, MCFixupKindInfo::FKF_IsPCRel},
91 // movw / movt: 16-bits immediate but scattered into two chunks 0 - 12, 16
93 {"fixup_arm_movt_hi16", 0, 20, 0},
94 {"fixup_arm_movw_lo16", 0, 20, 0},
95 {"fixup_t2_movt_hi16", 0, 20, 0},
96 {"fixup_t2_movw_lo16", 0, 20, 0},
98 const static MCFixupKindInfo InfosBE[ARM::NumTargetFixupKinds] = {
99 // This table *must* be in the order that the fixup_* kinds are defined in
102 // Name Offset (bits) Size (bits) Flags
103 {"fixup_arm_ldst_pcrel_12", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
104 {"fixup_t2_ldst_pcrel_12", 0, 32,
105 MCFixupKindInfo::FKF_IsPCRel |
106 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
107 {"fixup_arm_pcrel_10_unscaled", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
108 {"fixup_arm_pcrel_10", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
109 {"fixup_t2_pcrel_10", 0, 32,
110 MCFixupKindInfo::FKF_IsPCRel |
111 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
112 {"fixup_arm_pcrel_9", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
113 {"fixup_t2_pcrel_9", 0, 32,
114 MCFixupKindInfo::FKF_IsPCRel |
115 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
116 {"fixup_thumb_adr_pcrel_10", 8, 8,
117 MCFixupKindInfo::FKF_IsPCRel |
118 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
119 {"fixup_arm_adr_pcrel_12", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
120 {"fixup_t2_adr_pcrel_12", 0, 32,
121 MCFixupKindInfo::FKF_IsPCRel |
122 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
123 {"fixup_arm_condbranch", 8, 24, MCFixupKindInfo::FKF_IsPCRel},
124 {"fixup_arm_uncondbranch", 8, 24, MCFixupKindInfo::FKF_IsPCRel},
125 {"fixup_t2_condbranch", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
126 {"fixup_t2_uncondbranch", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
127 {"fixup_arm_thumb_br", 0, 16, MCFixupKindInfo::FKF_IsPCRel},
128 {"fixup_arm_uncondbl", 8, 24, MCFixupKindInfo::FKF_IsPCRel},
129 {"fixup_arm_condbl", 8, 24, MCFixupKindInfo::FKF_IsPCRel},
130 {"fixup_arm_blx", 8, 24, MCFixupKindInfo::FKF_IsPCRel},
131 {"fixup_arm_thumb_bl", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
132 {"fixup_arm_thumb_blx", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
133 {"fixup_arm_thumb_cb", 0, 16, MCFixupKindInfo::FKF_IsPCRel},
134 {"fixup_arm_thumb_cp", 8, 8,
135 MCFixupKindInfo::FKF_IsPCRel |
136 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
137 {"fixup_arm_thumb_bcc", 8, 8, MCFixupKindInfo::FKF_IsPCRel},
138 // movw / movt: 16-bits immediate but scattered into two chunks 0 - 12, 16
140 {"fixup_arm_movt_hi16", 12, 20, 0},
141 {"fixup_arm_movw_lo16", 12, 20, 0},
142 {"fixup_t2_movt_hi16", 12, 20, 0},
143 {"fixup_t2_movw_lo16", 12, 20, 0},
146 if (Kind < FirstTargetFixupKind)
147 return MCAsmBackend::getFixupKindInfo(Kind);
149 assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
151 return (IsLittleEndian ? InfosLE : InfosBE)[Kind - FirstTargetFixupKind];
154 void ARMAsmBackend::handleAssemblerFlag(MCAssemblerFlag Flag) {
166 } // end anonymous namespace
168 unsigned ARMAsmBackend::getRelaxedOpcode(unsigned Op) const {
169 bool HasThumb2 = STI->getFeatureBits()[ARM::FeatureThumb2];
175 return HasThumb2 ? (unsigned)ARM::t2Bcc : Op;
177 return HasThumb2 ? (unsigned)ARM::t2LDRpci : Op;
179 return HasThumb2 ? (unsigned)ARM::t2ADR : Op;
181 return HasThumb2 ? (unsigned)ARM::t2B : Op;
189 bool ARMAsmBackend::mayNeedRelaxation(const MCInst &Inst) const {
190 if (getRelaxedOpcode(Inst.getOpcode()) != Inst.getOpcode())
195 const char *ARMAsmBackend::reasonForFixupRelaxation(const MCFixup &Fixup,
196 uint64_t Value) const {
197 switch ((unsigned)Fixup.getKind()) {
198 case ARM::fixup_arm_thumb_br: {
199 // Relaxing tB to t2B. tB has a signed 12-bit displacement with the
200 // low bit being an implied zero. There's an implied +4 offset for the
201 // branch, so we adjust the other way here to determine what's
204 // Relax if the value is too big for a (signed) i8.
205 int64_t Offset = int64_t(Value) - 4;
206 if (Offset > 2046 || Offset < -2048)
207 return "out of range pc-relative fixup value";
210 case ARM::fixup_arm_thumb_bcc: {
211 // Relaxing tBcc to t2Bcc. tBcc has a signed 9-bit displacement with the
212 // low bit being an implied zero. There's an implied +4 offset for the
213 // branch, so we adjust the other way here to determine what's
216 // Relax if the value is too big for a (signed) i8.
217 int64_t Offset = int64_t(Value) - 4;
218 if (Offset > 254 || Offset < -256)
219 return "out of range pc-relative fixup value";
222 case ARM::fixup_thumb_adr_pcrel_10:
223 case ARM::fixup_arm_thumb_cp: {
224 // If the immediate is negative, greater than 1020, or not a multiple
225 // of four, the wide version of the instruction must be used.
226 int64_t Offset = int64_t(Value) - 4;
228 return "misaligned pc-relative fixup value";
229 else if (Offset > 1020 || Offset < 0)
230 return "out of range pc-relative fixup value";
233 case ARM::fixup_arm_thumb_cb: {
234 // If we have a Thumb CBZ or CBNZ instruction and its target is the next
235 // instruction it is is actually out of range for the instruction.
236 // It will be changed to a NOP.
237 int64_t Offset = (Value & ~1);
239 return "will be converted to nop";
243 llvm_unreachable("Unexpected fixup kind in reasonForFixupRelaxation()!");
248 bool ARMAsmBackend::fixupNeedsRelaxation(const MCFixup &Fixup, uint64_t Value,
249 const MCRelaxableFragment *DF,
250 const MCAsmLayout &Layout) const {
251 return reasonForFixupRelaxation(Fixup, Value);
254 void ARMAsmBackend::relaxInstruction(const MCInst &Inst, MCInst &Res) const {
255 unsigned RelaxedOp = getRelaxedOpcode(Inst.getOpcode());
257 // Sanity check w/ diagnostic if we get here w/ a bogus instruction.
258 if (RelaxedOp == Inst.getOpcode()) {
259 SmallString<256> Tmp;
260 raw_svector_ostream OS(Tmp);
261 Inst.dump_pretty(OS);
263 report_fatal_error("unexpected instruction to relax: " + OS.str());
266 // If we are changing Thumb CBZ or CBNZ instruction to a NOP, aka tHINT, we
267 // have to change the operands too.
268 if ((Inst.getOpcode() == ARM::tCBZ || Inst.getOpcode() == ARM::tCBNZ) &&
269 RelaxedOp == ARM::tHINT) {
270 Res.setOpcode(RelaxedOp);
271 Res.addOperand(MCOperand::createImm(0));
272 Res.addOperand(MCOperand::createImm(14));
273 Res.addOperand(MCOperand::createReg(0));
277 // The rest of instructions we're relaxing have the same operands.
278 // We just need to update to the proper opcode.
280 Res.setOpcode(RelaxedOp);
283 bool ARMAsmBackend::writeNopData(uint64_t Count, MCObjectWriter *OW) const {
284 const uint16_t Thumb1_16bitNopEncoding = 0x46c0; // using MOV r8,r8
285 const uint16_t Thumb2_16bitNopEncoding = 0xbf00; // NOP
286 const uint32_t ARMv4_NopEncoding = 0xe1a00000; // using MOV r0,r0
287 const uint32_t ARMv6T2_NopEncoding = 0xe320f000; // NOP
289 const uint16_t nopEncoding =
290 hasNOP() ? Thumb2_16bitNopEncoding : Thumb1_16bitNopEncoding;
291 uint64_t NumNops = Count / 2;
292 for (uint64_t i = 0; i != NumNops; ++i)
293 OW->write16(nopEncoding);
299 const uint32_t nopEncoding =
300 hasNOP() ? ARMv6T2_NopEncoding : ARMv4_NopEncoding;
301 uint64_t NumNops = Count / 4;
302 for (uint64_t i = 0; i != NumNops; ++i)
303 OW->write32(nopEncoding);
304 // FIXME: should this function return false when unable to write exactly
305 // 'Count' bytes with NOP encodings?
308 break; // No leftover bytes to write
324 static uint32_t swapHalfWords(uint32_t Value, bool IsLittleEndian) {
325 if (IsLittleEndian) {
326 // Note that the halfwords are stored high first and low second in thumb;
327 // so we need to swap the fixup value here to map properly.
328 uint32_t Swapped = (Value & 0xFFFF0000) >> 16;
329 Swapped |= (Value & 0x0000FFFF) << 16;
335 static uint32_t joinHalfWords(uint32_t FirstHalf, uint32_t SecondHalf,
336 bool IsLittleEndian) {
339 if (IsLittleEndian) {
340 Value = (SecondHalf & 0xFFFF) << 16;
341 Value |= (FirstHalf & 0xFFFF);
343 Value = (SecondHalf & 0xFFFF);
344 Value |= (FirstHalf & 0xFFFF) << 16;
350 unsigned ARMAsmBackend::adjustFixupValue(const MCFixup &Fixup, uint64_t Value,
351 bool IsPCRel, MCContext *Ctx,
353 bool IsResolved) const {
354 unsigned Kind = Fixup.getKind();
357 llvm_unreachable("Unknown fixup kind!");
366 case ARM::fixup_arm_movt_hi16:
370 case ARM::fixup_arm_movw_lo16: {
371 unsigned Hi4 = (Value & 0xF000) >> 12;
372 unsigned Lo12 = Value & 0x0FFF;
373 // inst{19-16} = Hi4;
374 // inst{11-0} = Lo12;
375 Value = (Hi4 << 16) | (Lo12);
378 case ARM::fixup_t2_movt_hi16:
382 case ARM::fixup_t2_movw_lo16: {
383 unsigned Hi4 = (Value & 0xF000) >> 12;
384 unsigned i = (Value & 0x800) >> 11;
385 unsigned Mid3 = (Value & 0x700) >> 8;
386 unsigned Lo8 = Value & 0x0FF;
387 // inst{19-16} = Hi4;
389 // inst{14-12} = Mid3;
391 Value = (Hi4 << 16) | (i << 26) | (Mid3 << 12) | (Lo8);
392 return swapHalfWords(Value, IsLittleEndian);
394 case ARM::fixup_arm_ldst_pcrel_12:
395 // ARM PC-relative values are offset by 8.
398 case ARM::fixup_t2_ldst_pcrel_12: {
399 // Offset by 4, adjusted by two due to the half-word ordering of thumb.
402 if ((int64_t)Value < 0) {
406 if (Ctx && Value >= 4096) {
407 Ctx->reportError(Fixup.getLoc(), "out of range pc-relative fixup value");
410 Value |= isAdd << 23;
412 // Same addressing mode as fixup_arm_pcrel_10,
413 // but with 16-bit halfwords swapped.
414 if (Kind == ARM::fixup_t2_ldst_pcrel_12)
415 return swapHalfWords(Value, IsLittleEndian);
419 case ARM::fixup_arm_adr_pcrel_12: {
420 // ARM PC-relative values are offset by 8.
422 unsigned opc = 4; // bits {24-21}. Default to add: 0b0100
423 if ((int64_t)Value < 0) {
427 if (Ctx && ARM_AM::getSOImmVal(Value) == -1) {
428 Ctx->reportError(Fixup.getLoc(), "out of range pc-relative fixup value");
431 // Encode the immediate and shift the opcode into place.
432 return ARM_AM::getSOImmVal(Value) | (opc << 21);
435 case ARM::fixup_t2_adr_pcrel_12: {
438 if ((int64_t)Value < 0) {
443 uint32_t out = (opc << 21);
444 out |= (Value & 0x800) << 15;
445 out |= (Value & 0x700) << 4;
446 out |= (Value & 0x0FF);
448 return swapHalfWords(out, IsLittleEndian);
451 case ARM::fixup_arm_condbranch:
452 case ARM::fixup_arm_uncondbranch:
453 case ARM::fixup_arm_uncondbl:
454 case ARM::fixup_arm_condbl:
455 case ARM::fixup_arm_blx:
456 // These values don't encode the low two bits since they're always zero.
457 // Offset by 8 just as above.
458 if (const MCSymbolRefExpr *SRE =
459 dyn_cast<MCSymbolRefExpr>(Fixup.getValue()))
460 if (SRE->getKind() == MCSymbolRefExpr::VK_ARM_TLSCALL)
462 return 0xffffff & ((Value - 8) >> 2);
463 case ARM::fixup_t2_uncondbranch: {
465 Value >>= 1; // Low bit is not encoded.
468 bool I = Value & 0x800000;
469 bool J1 = Value & 0x400000;
470 bool J2 = Value & 0x200000;
474 out |= I << 26; // S bit
475 out |= !J1 << 13; // J1 bit
476 out |= !J2 << 11; // J2 bit
477 out |= (Value & 0x1FF800) << 5; // imm6 field
478 out |= (Value & 0x0007FF); // imm11 field
480 return swapHalfWords(out, IsLittleEndian);
482 case ARM::fixup_t2_condbranch: {
484 Value >>= 1; // Low bit is not encoded.
487 out |= (Value & 0x80000) << 7; // S bit
488 out |= (Value & 0x40000) >> 7; // J2 bit
489 out |= (Value & 0x20000) >> 4; // J1 bit
490 out |= (Value & 0x1F800) << 5; // imm6 field
491 out |= (Value & 0x007FF); // imm11 field
493 return swapHalfWords(out, IsLittleEndian);
495 case ARM::fixup_arm_thumb_bl: {
496 // The value doesn't encode the low bit (always zero) and is offset by
497 // four. The 32-bit immediate value is encoded as
498 // imm32 = SignExtend(S:I1:I2:imm10:imm11:0)
499 // where I1 = NOT(J1 ^ S) and I2 = NOT(J2 ^ S).
500 // The value is encoded into disjoint bit positions in the destination
501 // opcode. x = unchanged, I = immediate value bit, S = sign extension bit,
502 // J = either J1 or J2 bit
504 // BL: xxxxxSIIIIIIIIII xxJxJIIIIIIIIIII
506 // Note that the halfwords are stored high first, low second; so we need
507 // to transpose the fixup value here to map properly.
508 uint32_t offset = (Value - 4) >> 1;
509 uint32_t signBit = (offset & 0x800000) >> 23;
510 uint32_t I1Bit = (offset & 0x400000) >> 22;
511 uint32_t J1Bit = (I1Bit ^ 0x1) ^ signBit;
512 uint32_t I2Bit = (offset & 0x200000) >> 21;
513 uint32_t J2Bit = (I2Bit ^ 0x1) ^ signBit;
514 uint32_t imm10Bits = (offset & 0x1FF800) >> 11;
515 uint32_t imm11Bits = (offset & 0x000007FF);
517 uint32_t FirstHalf = (((uint16_t)signBit << 10) | (uint16_t)imm10Bits);
518 uint32_t SecondHalf = (((uint16_t)J1Bit << 13) | ((uint16_t)J2Bit << 11) |
519 (uint16_t)imm11Bits);
520 return joinHalfWords(FirstHalf, SecondHalf, IsLittleEndian);
522 case ARM::fixup_arm_thumb_blx: {
523 // The value doesn't encode the low two bits (always zero) and is offset by
524 // four (see fixup_arm_thumb_cp). The 32-bit immediate value is encoded as
525 // imm32 = SignExtend(S:I1:I2:imm10H:imm10L:00)
526 // where I1 = NOT(J1 ^ S) and I2 = NOT(J2 ^ S).
527 // The value is encoded into disjoint bit positions in the destination
528 // opcode. x = unchanged, I = immediate value bit, S = sign extension bit,
529 // J = either J1 or J2 bit, 0 = zero.
531 // BLX: xxxxxSIIIIIIIIII xxJxJIIIIIIIIII0
533 // Note that the halfwords are stored high first, low second; so we need
534 // to transpose the fixup value here to map properly.
535 uint32_t offset = (Value - 2) >> 2;
536 if (const MCSymbolRefExpr *SRE =
537 dyn_cast<MCSymbolRefExpr>(Fixup.getValue()))
538 if (SRE->getKind() == MCSymbolRefExpr::VK_ARM_TLSCALL)
540 uint32_t signBit = (offset & 0x400000) >> 22;
541 uint32_t I1Bit = (offset & 0x200000) >> 21;
542 uint32_t J1Bit = (I1Bit ^ 0x1) ^ signBit;
543 uint32_t I2Bit = (offset & 0x100000) >> 20;
544 uint32_t J2Bit = (I2Bit ^ 0x1) ^ signBit;
545 uint32_t imm10HBits = (offset & 0xFFC00) >> 10;
546 uint32_t imm10LBits = (offset & 0x3FF);
548 uint32_t FirstHalf = (((uint16_t)signBit << 10) | (uint16_t)imm10HBits);
549 uint32_t SecondHalf = (((uint16_t)J1Bit << 13) | ((uint16_t)J2Bit << 11) |
550 ((uint16_t)imm10LBits) << 1);
551 return joinHalfWords(FirstHalf, SecondHalf, IsLittleEndian);
553 case ARM::fixup_thumb_adr_pcrel_10:
554 case ARM::fixup_arm_thumb_cp:
555 // On CPUs supporting Thumb2, this will be relaxed to an ldr.w, otherwise we
556 // could have an error on our hands.
557 if (Ctx && !STI->getFeatureBits()[ARM::FeatureThumb2] && IsResolved) {
558 const char *FixupDiagnostic = reasonForFixupRelaxation(Fixup, Value);
559 if (FixupDiagnostic) {
560 Ctx->reportError(Fixup.getLoc(), FixupDiagnostic);
564 // Offset by 4, and don't encode the low two bits.
565 return ((Value - 4) >> 2) & 0xff;
566 case ARM::fixup_arm_thumb_cb: {
567 // Offset by 4 and don't encode the lower bit, which is always 0.
568 // FIXME: diagnose if no Thumb2
569 uint32_t Binary = (Value - 4) >> 1;
570 return ((Binary & 0x20) << 4) | ((Binary & 0x1f) << 3);
572 case ARM::fixup_arm_thumb_br:
573 // Offset by 4 and don't encode the lower bit, which is always 0.
574 if (Ctx && !STI->getFeatureBits()[ARM::FeatureThumb2]) {
575 const char *FixupDiagnostic = reasonForFixupRelaxation(Fixup, Value);
576 if (FixupDiagnostic) {
577 Ctx->reportError(Fixup.getLoc(), FixupDiagnostic);
581 return ((Value - 4) >> 1) & 0x7ff;
582 case ARM::fixup_arm_thumb_bcc:
583 // Offset by 4 and don't encode the lower bit, which is always 0.
584 if (Ctx && !STI->getFeatureBits()[ARM::FeatureThumb2]) {
585 const char *FixupDiagnostic = reasonForFixupRelaxation(Fixup, Value);
586 if (FixupDiagnostic) {
587 Ctx->reportError(Fixup.getLoc(), FixupDiagnostic);
591 return ((Value - 4) >> 1) & 0xff;
592 case ARM::fixup_arm_pcrel_10_unscaled: {
593 Value = Value - 8; // ARM fixups offset by an additional word and don't
594 // need to adjust for the half-word ordering.
596 if ((int64_t)Value < 0) {
600 // The value has the low 4 bits encoded in [3:0] and the high 4 in [11:8].
601 if (Ctx && Value >= 256) {
602 Ctx->reportError(Fixup.getLoc(), "out of range pc-relative fixup value");
605 Value = (Value & 0xf) | ((Value & 0xf0) << 4);
606 return Value | (isAdd << 23);
608 case ARM::fixup_arm_pcrel_10:
609 Value = Value - 4; // ARM fixups offset by an additional word and don't
610 // need to adjust for the half-word ordering.
612 case ARM::fixup_t2_pcrel_10: {
613 // Offset by 4, adjusted by two due to the half-word ordering of thumb.
616 if ((int64_t)Value < 0) {
620 // These values don't encode the low two bits since they're always zero.
622 if (Ctx && Value >= 256) {
623 Ctx->reportError(Fixup.getLoc(), "out of range pc-relative fixup value");
626 Value |= isAdd << 23;
628 // Same addressing mode as fixup_arm_pcrel_10, but with 16-bit halfwords
630 if (Kind == ARM::fixup_t2_pcrel_10)
631 return swapHalfWords(Value, IsLittleEndian);
635 case ARM::fixup_arm_pcrel_9:
636 Value = Value - 4; // ARM fixups offset by an additional word and don't
637 // need to adjust for the half-word ordering.
639 case ARM::fixup_t2_pcrel_9: {
640 // Offset by 4, adjusted by two due to the half-word ordering of thumb.
643 if ((int64_t)Value < 0) {
647 // These values don't encode the low bit since it's always zero.
648 if (Ctx && (Value & 1)) {
649 Ctx->reportError(Fixup.getLoc(), "invalid value for this fixup");
653 if (Ctx && Value >= 256) {
654 Ctx->reportError(Fixup.getLoc(), "out of range pc-relative fixup value");
657 Value |= isAdd << 23;
659 // Same addressing mode as fixup_arm_pcrel_9, but with 16-bit halfwords
661 if (Kind == ARM::fixup_t2_pcrel_9)
662 return swapHalfWords(Value, IsLittleEndian);
669 void ARMAsmBackend::processFixupValue(const MCAssembler &Asm,
670 const MCAsmLayout &Layout,
671 const MCFixup &Fixup,
672 const MCFragment *DF,
673 const MCValue &Target, uint64_t &Value,
675 const MCSymbolRefExpr *A = Target.getSymA();
676 const MCSymbol *Sym = A ? &A->getSymbol() : nullptr;
677 // Some fixups to thumb function symbols need the low bit (thumb bit)
679 if ((unsigned)Fixup.getKind() != ARM::fixup_arm_ldst_pcrel_12 &&
680 (unsigned)Fixup.getKind() != ARM::fixup_t2_ldst_pcrel_12 &&
681 (unsigned)Fixup.getKind() != ARM::fixup_arm_adr_pcrel_12 &&
682 (unsigned)Fixup.getKind() != ARM::fixup_thumb_adr_pcrel_10 &&
683 (unsigned)Fixup.getKind() != ARM::fixup_t2_adr_pcrel_12 &&
684 (unsigned)Fixup.getKind() != ARM::fixup_arm_thumb_cp) {
686 if (Asm.isThumbFunc(Sym))
690 if (IsResolved && (unsigned)Fixup.getKind() == ARM::fixup_arm_thumb_bl) {
691 assert(Sym && "How did we resolve this?");
693 // If the symbol is external the linker will handle it.
694 // FIXME: Should we handle it as an optimization?
696 // If the symbol is out of range, produce a relocation and hope the
697 // linker can handle it. GNU AS produces an error in this case.
698 if (Sym->isExternal() || Value >= 0x400004)
701 // We must always generate a relocation for BL/BLX instructions if we have
702 // a symbol to reference, as the linker relies on knowing the destination
703 // symbol's thumb-ness to get interworking right.
704 if (A && ((unsigned)Fixup.getKind() == ARM::fixup_arm_thumb_blx ||
705 (unsigned)Fixup.getKind() == ARM::fixup_arm_blx ||
706 (unsigned)Fixup.getKind() == ARM::fixup_arm_uncondbl ||
707 (unsigned)Fixup.getKind() == ARM::fixup_arm_condbl))
710 // Try to get the encoded value for the fixup as-if we're mapping it into
711 // the instruction. This allows adjustFixupValue() to issue a diagnostic
712 // if the value aren't invalid.
713 (void)adjustFixupValue(Fixup, Value, false, &Asm.getContext(),
714 IsLittleEndian, IsResolved);
717 /// getFixupKindNumBytes - The number of bytes the fixup may change.
718 static unsigned getFixupKindNumBytes(unsigned Kind) {
721 llvm_unreachable("Unknown fixup kind!");
724 case ARM::fixup_arm_thumb_bcc:
725 case ARM::fixup_arm_thumb_cp:
726 case ARM::fixup_thumb_adr_pcrel_10:
730 case ARM::fixup_arm_thumb_br:
731 case ARM::fixup_arm_thumb_cb:
734 case ARM::fixup_arm_pcrel_10_unscaled:
735 case ARM::fixup_arm_ldst_pcrel_12:
736 case ARM::fixup_arm_pcrel_10:
737 case ARM::fixup_arm_pcrel_9:
738 case ARM::fixup_arm_adr_pcrel_12:
739 case ARM::fixup_arm_uncondbl:
740 case ARM::fixup_arm_condbl:
741 case ARM::fixup_arm_blx:
742 case ARM::fixup_arm_condbranch:
743 case ARM::fixup_arm_uncondbranch:
747 case ARM::fixup_t2_ldst_pcrel_12:
748 case ARM::fixup_t2_condbranch:
749 case ARM::fixup_t2_uncondbranch:
750 case ARM::fixup_t2_pcrel_10:
751 case ARM::fixup_t2_pcrel_9:
752 case ARM::fixup_t2_adr_pcrel_12:
753 case ARM::fixup_arm_thumb_bl:
754 case ARM::fixup_arm_thumb_blx:
755 case ARM::fixup_arm_movt_hi16:
756 case ARM::fixup_arm_movw_lo16:
757 case ARM::fixup_t2_movt_hi16:
758 case ARM::fixup_t2_movw_lo16:
768 /// getFixupKindContainerSizeBytes - The number of bytes of the
769 /// container involved in big endian.
770 static unsigned getFixupKindContainerSizeBytes(unsigned Kind) {
773 llvm_unreachable("Unknown fixup kind!");
782 case ARM::fixup_arm_thumb_bcc:
783 case ARM::fixup_arm_thumb_cp:
784 case ARM::fixup_thumb_adr_pcrel_10:
785 case ARM::fixup_arm_thumb_br:
786 case ARM::fixup_arm_thumb_cb:
787 // Instruction size is 2 bytes.
790 case ARM::fixup_arm_pcrel_10_unscaled:
791 case ARM::fixup_arm_ldst_pcrel_12:
792 case ARM::fixup_arm_pcrel_10:
793 case ARM::fixup_arm_adr_pcrel_12:
794 case ARM::fixup_arm_uncondbl:
795 case ARM::fixup_arm_condbl:
796 case ARM::fixup_arm_blx:
797 case ARM::fixup_arm_condbranch:
798 case ARM::fixup_arm_uncondbranch:
799 case ARM::fixup_t2_ldst_pcrel_12:
800 case ARM::fixup_t2_condbranch:
801 case ARM::fixup_t2_uncondbranch:
802 case ARM::fixup_t2_pcrel_10:
803 case ARM::fixup_t2_adr_pcrel_12:
804 case ARM::fixup_arm_thumb_bl:
805 case ARM::fixup_arm_thumb_blx:
806 case ARM::fixup_arm_movt_hi16:
807 case ARM::fixup_arm_movw_lo16:
808 case ARM::fixup_t2_movt_hi16:
809 case ARM::fixup_t2_movw_lo16:
810 // Instruction size is 4 bytes.
815 void ARMAsmBackend::applyFixup(const MCFixup &Fixup, char *Data,
816 unsigned DataSize, uint64_t Value,
817 bool IsPCRel) const {
818 unsigned NumBytes = getFixupKindNumBytes(Fixup.getKind());
820 adjustFixupValue(Fixup, Value, IsPCRel, nullptr, IsLittleEndian, true);
822 return; // Doesn't change encoding.
824 unsigned Offset = Fixup.getOffset();
825 assert(Offset + NumBytes <= DataSize && "Invalid fixup offset!");
827 // Used to point to big endian bytes.
828 unsigned FullSizeBytes;
829 if (!IsLittleEndian) {
830 FullSizeBytes = getFixupKindContainerSizeBytes(Fixup.getKind());
831 assert((Offset + FullSizeBytes) <= DataSize && "Invalid fixup size!");
832 assert(NumBytes <= FullSizeBytes && "Invalid fixup size!");
835 // For each byte of the fragment that the fixup touches, mask in the bits from
836 // the fixup value. The Value has been "split up" into the appropriate
838 for (unsigned i = 0; i != NumBytes; ++i) {
839 unsigned Idx = IsLittleEndian ? i : (FullSizeBytes - 1 - i);
840 Data[Offset + Idx] |= uint8_t((Value >> (i * 8)) & 0xff);
846 /// \brief Compact unwind encoding values.
847 enum CompactUnwindEncodings {
848 UNWIND_ARM_MODE_MASK = 0x0F000000,
849 UNWIND_ARM_MODE_FRAME = 0x01000000,
850 UNWIND_ARM_MODE_FRAME_D = 0x02000000,
851 UNWIND_ARM_MODE_DWARF = 0x04000000,
853 UNWIND_ARM_FRAME_STACK_ADJUST_MASK = 0x00C00000,
855 UNWIND_ARM_FRAME_FIRST_PUSH_R4 = 0x00000001,
856 UNWIND_ARM_FRAME_FIRST_PUSH_R5 = 0x00000002,
857 UNWIND_ARM_FRAME_FIRST_PUSH_R6 = 0x00000004,
859 UNWIND_ARM_FRAME_SECOND_PUSH_R8 = 0x00000008,
860 UNWIND_ARM_FRAME_SECOND_PUSH_R9 = 0x00000010,
861 UNWIND_ARM_FRAME_SECOND_PUSH_R10 = 0x00000020,
862 UNWIND_ARM_FRAME_SECOND_PUSH_R11 = 0x00000040,
863 UNWIND_ARM_FRAME_SECOND_PUSH_R12 = 0x00000080,
865 UNWIND_ARM_FRAME_D_REG_COUNT_MASK = 0x00000F00,
867 UNWIND_ARM_DWARF_SECTION_OFFSET = 0x00FFFFFF
870 } // end CU namespace
872 /// Generate compact unwind encoding for the function based on the CFI
873 /// instructions. If the CFI instructions describe a frame that cannot be
874 /// encoded in compact unwind, the method returns UNWIND_ARM_MODE_DWARF which
875 /// tells the runtime to fallback and unwind using dwarf.
876 uint32_t ARMAsmBackendDarwin::generateCompactUnwindEncoding(
877 ArrayRef<MCCFIInstruction> Instrs) const {
878 DEBUG_WITH_TYPE("compact-unwind", llvm::dbgs() << "generateCU()\n");
879 // Only armv7k uses CFI based unwinding.
880 if (Subtype != MachO::CPU_SUBTYPE_ARM_V7K)
882 // No .cfi directives means no frame.
885 // Start off assuming CFA is at SP+0.
886 int CFARegister = ARM::SP;
887 int CFARegisterOffset = 0;
888 // Mark savable registers as initially unsaved
889 DenseMap<unsigned, int> RegOffsets;
890 int FloatRegCount = 0;
891 // Process each .cfi directive and build up compact unwind info.
892 for (size_t i = 0, e = Instrs.size(); i != e; ++i) {
894 const MCCFIInstruction &Inst = Instrs[i];
895 switch (Inst.getOperation()) {
896 case MCCFIInstruction::OpDefCfa: // DW_CFA_def_cfa
897 CFARegisterOffset = -Inst.getOffset();
898 CFARegister = MRI.getLLVMRegNum(Inst.getRegister(), true);
900 case MCCFIInstruction::OpDefCfaOffset: // DW_CFA_def_cfa_offset
901 CFARegisterOffset = -Inst.getOffset();
903 case MCCFIInstruction::OpDefCfaRegister: // DW_CFA_def_cfa_register
904 CFARegister = MRI.getLLVMRegNum(Inst.getRegister(), true);
906 case MCCFIInstruction::OpOffset: // DW_CFA_offset
907 Reg = MRI.getLLVMRegNum(Inst.getRegister(), true);
908 if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
909 RegOffsets[Reg] = Inst.getOffset();
910 else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg)) {
911 RegOffsets[Reg] = Inst.getOffset();
914 DEBUG_WITH_TYPE("compact-unwind",
915 llvm::dbgs() << ".cfi_offset on unknown register="
916 << Inst.getRegister() << "\n");
917 return CU::UNWIND_ARM_MODE_DWARF;
920 case MCCFIInstruction::OpRelOffset: // DW_CFA_advance_loc
924 // Directive not convertable to compact unwind, bail out.
925 DEBUG_WITH_TYPE("compact-unwind",
927 << "CFI directive not compatiable with comact "
928 "unwind encoding, opcode=" << Inst.getOperation()
930 return CU::UNWIND_ARM_MODE_DWARF;
935 // If no frame set up, return no unwind info.
936 if ((CFARegister == ARM::SP) && (CFARegisterOffset == 0))
939 // Verify standard frame (lr/r7) was used.
940 if (CFARegister != ARM::R7) {
941 DEBUG_WITH_TYPE("compact-unwind", llvm::dbgs() << "frame register is "
943 << " instead of r7\n");
944 return CU::UNWIND_ARM_MODE_DWARF;
946 int StackAdjust = CFARegisterOffset - 8;
947 if (RegOffsets.lookup(ARM::LR) != (-4 - StackAdjust)) {
948 DEBUG_WITH_TYPE("compact-unwind",
950 << "LR not saved as standard frame, StackAdjust="
952 << ", CFARegisterOffset=" << CFARegisterOffset
953 << ", lr save at offset=" << RegOffsets[14] << "\n");
954 return CU::UNWIND_ARM_MODE_DWARF;
956 if (RegOffsets.lookup(ARM::R7) != (-8 - StackAdjust)) {
957 DEBUG_WITH_TYPE("compact-unwind",
958 llvm::dbgs() << "r7 not saved as standard frame\n");
959 return CU::UNWIND_ARM_MODE_DWARF;
961 uint32_t CompactUnwindEncoding = CU::UNWIND_ARM_MODE_FRAME;
963 // If var-args are used, there may be a stack adjust required.
964 switch (StackAdjust) {
968 CompactUnwindEncoding |= 0x00400000;
971 CompactUnwindEncoding |= 0x00800000;
974 CompactUnwindEncoding |= 0x00C00000;
977 DEBUG_WITH_TYPE("compact-unwind", llvm::dbgs()
978 << ".cfi_def_cfa stack adjust ("
979 << StackAdjust << ") out of range\n");
980 return CU::UNWIND_ARM_MODE_DWARF;
983 // If r6 is saved, it must be right below r7.
987 } GPRCSRegs[] = {{ARM::R6, CU::UNWIND_ARM_FRAME_FIRST_PUSH_R6},
988 {ARM::R5, CU::UNWIND_ARM_FRAME_FIRST_PUSH_R5},
989 {ARM::R4, CU::UNWIND_ARM_FRAME_FIRST_PUSH_R4},
990 {ARM::R12, CU::UNWIND_ARM_FRAME_SECOND_PUSH_R12},
991 {ARM::R11, CU::UNWIND_ARM_FRAME_SECOND_PUSH_R11},
992 {ARM::R10, CU::UNWIND_ARM_FRAME_SECOND_PUSH_R10},
993 {ARM::R9, CU::UNWIND_ARM_FRAME_SECOND_PUSH_R9},
994 {ARM::R8, CU::UNWIND_ARM_FRAME_SECOND_PUSH_R8}};
996 int CurOffset = -8 - StackAdjust;
997 for (auto CSReg : GPRCSRegs) {
998 auto Offset = RegOffsets.find(CSReg.Reg);
999 if (Offset == RegOffsets.end())
1002 int RegOffset = Offset->second;
1003 if (RegOffset != CurOffset - 4) {
1004 DEBUG_WITH_TYPE("compact-unwind",
1005 llvm::dbgs() << MRI.getName(CSReg.Reg) << " saved at "
1006 << RegOffset << " but only supported at "
1007 << CurOffset << "\n");
1008 return CU::UNWIND_ARM_MODE_DWARF;
1010 CompactUnwindEncoding |= CSReg.Encoding;
1014 // If no floats saved, we are done.
1015 if (FloatRegCount == 0)
1016 return CompactUnwindEncoding;
1018 // Switch mode to include D register saving.
1019 CompactUnwindEncoding &= ~CU::UNWIND_ARM_MODE_MASK;
1020 CompactUnwindEncoding |= CU::UNWIND_ARM_MODE_FRAME_D;
1022 // FIXME: supporting more than 4 saved D-registers compactly would be trivial,
1023 // but needs coordination with the linker and libunwind.
1024 if (FloatRegCount > 4) {
1025 DEBUG_WITH_TYPE("compact-unwind",
1026 llvm::dbgs() << "unsupported number of D registers saved ("
1027 << FloatRegCount << ")\n");
1028 return CU::UNWIND_ARM_MODE_DWARF;
1031 // Floating point registers must either be saved sequentially, or we defer to
1032 // DWARF. No gaps allowed here so check that each saved d-register is
1033 // precisely where it should be.
1034 static unsigned FPRCSRegs[] = { ARM::D8, ARM::D10, ARM::D12, ARM::D14 };
1035 for (int Idx = FloatRegCount - 1; Idx >= 0; --Idx) {
1036 auto Offset = RegOffsets.find(FPRCSRegs[Idx]);
1037 if (Offset == RegOffsets.end()) {
1038 DEBUG_WITH_TYPE("compact-unwind",
1039 llvm::dbgs() << FloatRegCount << " D-regs saved, but "
1040 << MRI.getName(FPRCSRegs[Idx])
1042 return CU::UNWIND_ARM_MODE_DWARF;
1043 } else if (Offset->second != CurOffset - 8) {
1044 DEBUG_WITH_TYPE("compact-unwind",
1045 llvm::dbgs() << FloatRegCount << " D-regs saved, but "
1046 << MRI.getName(FPRCSRegs[Idx])
1047 << " saved at " << Offset->second
1048 << ", expected at " << CurOffset - 8
1050 return CU::UNWIND_ARM_MODE_DWARF;
1055 return CompactUnwindEncoding | ((FloatRegCount - 1) << 8);
1058 static MachO::CPUSubTypeARM getMachOSubTypeFromArch(StringRef Arch) {
1059 unsigned AK = ARM::parseArch(Arch);
1062 return MachO::CPU_SUBTYPE_ARM_V7;
1063 case ARM::AK_ARMV4T:
1064 return MachO::CPU_SUBTYPE_ARM_V4T;
1065 case ARM::AK_ARMV5T:
1066 case ARM::AK_ARMV5TE:
1067 case ARM::AK_ARMV5TEJ:
1068 return MachO::CPU_SUBTYPE_ARM_V5;
1070 case ARM::AK_ARMV6K:
1071 return MachO::CPU_SUBTYPE_ARM_V6;
1072 case ARM::AK_ARMV7A:
1073 return MachO::CPU_SUBTYPE_ARM_V7;
1074 case ARM::AK_ARMV7S:
1075 return MachO::CPU_SUBTYPE_ARM_V7S;
1076 case ARM::AK_ARMV7K:
1077 return MachO::CPU_SUBTYPE_ARM_V7K;
1078 case ARM::AK_ARMV6M:
1079 return MachO::CPU_SUBTYPE_ARM_V6M;
1080 case ARM::AK_ARMV7M:
1081 return MachO::CPU_SUBTYPE_ARM_V7M;
1082 case ARM::AK_ARMV7EM:
1083 return MachO::CPU_SUBTYPE_ARM_V7EM;
1087 MCAsmBackend *llvm::createARMAsmBackend(const Target &T,
1088 const MCRegisterInfo &MRI,
1089 const Triple &TheTriple, StringRef CPU,
1091 switch (TheTriple.getObjectFormat()) {
1093 llvm_unreachable("unsupported object format");
1094 case Triple::MachO: {
1095 MachO::CPUSubTypeARM CS = getMachOSubTypeFromArch(TheTriple.getArchName());
1096 return new ARMAsmBackendDarwin(T, TheTriple, MRI, CS);
1099 assert(TheTriple.isOSWindows() && "non-Windows ARM COFF is not supported");
1100 return new ARMAsmBackendWinCOFF(T, TheTriple);
1102 assert(TheTriple.isOSBinFormatELF() && "using ELF for non-ELF target");
1103 uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
1104 return new ARMAsmBackendELF(T, TheTriple, OSABI, isLittle);
1108 MCAsmBackend *llvm::createARMLEAsmBackend(const Target &T,
1109 const MCRegisterInfo &MRI,
1110 const Triple &TT, StringRef CPU) {
1111 return createARMAsmBackend(T, MRI, TT, CPU, true);
1114 MCAsmBackend *llvm::createARMBEAsmBackend(const Target &T,
1115 const MCRegisterInfo &MRI,
1116 const Triple &TT, StringRef CPU) {
1117 return createARMAsmBackend(T, MRI, TT, CPU, false);
1120 MCAsmBackend *llvm::createThumbLEAsmBackend(const Target &T,
1121 const MCRegisterInfo &MRI,
1122 const Triple &TT, StringRef CPU) {
1123 return createARMAsmBackend(T, MRI, TT, CPU, true);
1126 MCAsmBackend *llvm::createThumbBEAsmBackend(const Target &T,
1127 const MCRegisterInfo &MRI,
1128 const Triple &TT, StringRef CPU) {
1129 return createARMAsmBackend(T, MRI, TT, CPU, false);