9b60ce57b9017ee42f4f3dfb878a3319c08a87fb
[oota-llvm.git] / lib / Target / ARM / MCTargetDesc / ARMAsmBackend.cpp
1 //===-- ARMAsmBackend.cpp - ARM Assembler Backend -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
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"
40 using namespace llvm;
41
42 namespace {
43 class ARMELFObjectWriter : public MCELFObjectTargetWriter {
44 public:
45   ARMELFObjectWriter(uint8_t OSABI)
46       : MCELFObjectTargetWriter(/*Is64Bit*/ false, OSABI, ELF::EM_ARM,
47                                 /*HasRelocationAddend*/ false) {}
48 };
49
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
53       // ARMFixupKinds.h.
54       //
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
92       // - 19.
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},
97   };
98   const static MCFixupKindInfo InfosBE[ARM::NumTargetFixupKinds] = {
99       // This table *must* be in the order that the fixup_* kinds are defined in
100       // ARMFixupKinds.h.
101       //
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
139       // - 19.
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},
144   };
145
146   if (Kind < FirstTargetFixupKind)
147     return MCAsmBackend::getFixupKindInfo(Kind);
148
149   assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
150          "Invalid kind!");
151   return (IsLittleEndian ? InfosLE : InfosBE)[Kind - FirstTargetFixupKind];
152 }
153
154 void ARMAsmBackend::handleAssemblerFlag(MCAssemblerFlag Flag) {
155   switch (Flag) {
156   default:
157     break;
158   case MCAF_Code16:
159     setIsThumb(true);
160     break;
161   case MCAF_Code32:
162     setIsThumb(false);
163     break;
164   }
165 }
166 } // end anonymous namespace
167
168 unsigned ARMAsmBackend::getRelaxedOpcode(unsigned Op) const {
169   bool HasThumb2 = STI->getFeatureBits()[ARM::FeatureThumb2];
170
171   switch (Op) {
172   default:
173     return Op;
174   case ARM::tBcc:
175     return HasThumb2 ? (unsigned)ARM::t2Bcc : Op;
176   case ARM::tLDRpci:
177     return HasThumb2 ? (unsigned)ARM::t2LDRpci : Op;
178   case ARM::tADR:
179     return HasThumb2 ? (unsigned)ARM::t2ADR : Op;
180   case ARM::tB:
181     return HasThumb2 ? (unsigned)ARM::t2B : Op;
182   case ARM::tCBZ:
183     return ARM::tHINT;
184   case ARM::tCBNZ:
185     return ARM::tHINT;
186   }
187 }
188
189 bool ARMAsmBackend::mayNeedRelaxation(const MCInst &Inst) const {
190   if (getRelaxedOpcode(Inst.getOpcode()) != Inst.getOpcode())
191     return true;
192   return false;
193 }
194
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
202     // encodable.
203     //
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";
208     break;
209   }
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
214     // encodable.
215     //
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";
220     break;
221   }
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;
227     if (Offset & 3)
228       return "misaligned pc-relative fixup value";
229     else if (Offset > 1020 || Offset < 0)
230       return "out of range pc-relative fixup value";
231     break;
232   }
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);
238     if (Offset == 2)
239       return "will be converted to nop";
240     break;
241   }
242   default:
243     llvm_unreachable("Unexpected fixup kind in reasonForFixupRelaxation()!");
244   }
245   return nullptr;
246 }
247
248 bool ARMAsmBackend::fixupNeedsRelaxation(const MCFixup &Fixup, uint64_t Value,
249                                          const MCRelaxableFragment *DF,
250                                          const MCAsmLayout &Layout) const {
251   return reasonForFixupRelaxation(Fixup, Value);
252 }
253
254 void ARMAsmBackend::relaxInstruction(const MCInst &Inst, MCInst &Res) const {
255   unsigned RelaxedOp = getRelaxedOpcode(Inst.getOpcode());
256
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);
262     OS << "\n";
263     report_fatal_error("unexpected instruction to relax: " + OS.str());
264   }
265
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));
274     return;
275   }
276
277   // The rest of instructions we're relaxing have the same operands.
278   // We just need to update to the proper opcode.
279   Res = Inst;
280   Res.setOpcode(RelaxedOp);
281 }
282
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
288   if (isThumb()) {
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);
294     if (Count & 1)
295       OW->write8(0);
296     return true;
297   }
298   // ARM mode
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?
306   switch (Count % 4) {
307   default:
308     break; // No leftover bytes to write
309   case 1:
310     OW->write8(0);
311     break;
312   case 2:
313     OW->write16(0);
314     break;
315   case 3:
316     OW->write16(0);
317     OW->write8(0xa0);
318     break;
319   }
320
321   return true;
322 }
323
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;
330     return Swapped;
331   } else
332     return Value;
333 }
334
335 static uint32_t joinHalfWords(uint32_t FirstHalf, uint32_t SecondHalf,
336                               bool IsLittleEndian) {
337   uint32_t Value;
338
339   if (IsLittleEndian) {
340     Value = (SecondHalf & 0xFFFF) << 16;
341     Value |= (FirstHalf & 0xFFFF);
342   } else {
343     Value = (SecondHalf & 0xFFFF);
344     Value |= (FirstHalf & 0xFFFF) << 16;
345   }
346
347   return Value;
348 }
349
350 unsigned ARMAsmBackend::adjustFixupValue(const MCFixup &Fixup, uint64_t Value,
351                                          bool IsPCRel, MCContext *Ctx,
352                                          bool IsLittleEndian,
353                                          bool IsResolved) const {
354   unsigned Kind = Fixup.getKind();
355   switch (Kind) {
356   default:
357     llvm_unreachable("Unknown fixup kind!");
358   case FK_Data_1:
359   case FK_Data_2:
360   case FK_Data_4:
361     return Value;
362   case FK_SecRel_2:
363     return Value;
364   case FK_SecRel_4:
365     return Value;
366   case ARM::fixup_arm_movt_hi16:
367     if (!IsPCRel)
368       Value >>= 16;
369   // Fallthrough
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);
376     return Value;
377   }
378   case ARM::fixup_t2_movt_hi16:
379     if (!IsPCRel)
380       Value >>= 16;
381   // Fallthrough
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;
388     // inst{26} = i;
389     // inst{14-12} = Mid3;
390     // inst{7-0} = Lo8;
391     Value = (Hi4 << 16) | (i << 26) | (Mid3 << 12) | (Lo8);
392     return swapHalfWords(Value, IsLittleEndian);
393   }
394   case ARM::fixup_arm_ldst_pcrel_12:
395     // ARM PC-relative values are offset by 8.
396     Value -= 4;
397   // FALLTHROUGH
398   case ARM::fixup_t2_ldst_pcrel_12: {
399     // Offset by 4, adjusted by two due to the half-word ordering of thumb.
400     Value -= 4;
401     bool isAdd = true;
402     if ((int64_t)Value < 0) {
403       Value = -Value;
404       isAdd = false;
405     }
406     if (Ctx && Value >= 4096) {
407       Ctx->reportError(Fixup.getLoc(), "out of range pc-relative fixup value");
408       return 0;
409     }
410     Value |= isAdd << 23;
411
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);
416
417     return Value;
418   }
419   case ARM::fixup_arm_adr_pcrel_12: {
420     // ARM PC-relative values are offset by 8.
421     Value -= 8;
422     unsigned opc = 4; // bits {24-21}. Default to add: 0b0100
423     if ((int64_t)Value < 0) {
424       Value = -Value;
425       opc = 2; // 0b0010
426     }
427     if (Ctx && ARM_AM::getSOImmVal(Value) == -1) {
428       Ctx->reportError(Fixup.getLoc(), "out of range pc-relative fixup value");
429       return 0;
430     }
431     // Encode the immediate and shift the opcode into place.
432     return ARM_AM::getSOImmVal(Value) | (opc << 21);
433   }
434
435   case ARM::fixup_t2_adr_pcrel_12: {
436     Value -= 4;
437     unsigned opc = 0;
438     if ((int64_t)Value < 0) {
439       Value = -Value;
440       opc = 5;
441     }
442
443     uint32_t out = (opc << 21);
444     out |= (Value & 0x800) << 15;
445     out |= (Value & 0x700) << 4;
446     out |= (Value & 0x0FF);
447
448     return swapHalfWords(out, IsLittleEndian);
449   }
450
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)
461         return 0;
462     return 0xffffff & ((Value - 8) >> 2);
463   case ARM::fixup_t2_uncondbranch: {
464     Value = Value - 4;
465     Value >>= 1; // Low bit is not encoded.
466
467     uint32_t out = 0;
468     bool I = Value & 0x800000;
469     bool J1 = Value & 0x400000;
470     bool J2 = Value & 0x200000;
471     J1 ^= I;
472     J2 ^= I;
473
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
479
480     return swapHalfWords(out, IsLittleEndian);
481   }
482   case ARM::fixup_t2_condbranch: {
483     Value = Value - 4;
484     Value >>= 1; // Low bit is not encoded.
485
486     uint64_t out = 0;
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
492
493     return swapHalfWords(out, IsLittleEndian);
494   }
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
503     //
504     //   BL:  xxxxxSIIIIIIIIII xxJxJIIIIIIIIIII
505     //
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);
516
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);
521   }
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.
530     //
531     //   BLX: xxxxxSIIIIIIIIII xxJxJIIIIIIIIII0
532     //
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)
539         offset = 0;
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);
547
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);
552   }
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);
561         return 0;
562       }
563     }
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);
571   }
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);
578         return 0;
579       }
580     }
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);
588         return 0;
589       }
590     }
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.
595     bool isAdd = true;
596     if ((int64_t)Value < 0) {
597       Value = -Value;
598       isAdd = false;
599     }
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");
603       return 0;
604     }
605     Value = (Value & 0xf) | ((Value & 0xf0) << 4);
606     return Value | (isAdd << 23);
607   }
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.
611                        // Fall through.
612   case ARM::fixup_t2_pcrel_10: {
613     // Offset by 4, adjusted by two due to the half-word ordering of thumb.
614     Value = Value - 4;
615     bool isAdd = true;
616     if ((int64_t)Value < 0) {
617       Value = -Value;
618       isAdd = false;
619     }
620     // These values don't encode the low two bits since they're always zero.
621     Value >>= 2;
622     if (Ctx && Value >= 256) {
623       Ctx->reportError(Fixup.getLoc(), "out of range pc-relative fixup value");
624       return 0;
625     }
626     Value |= isAdd << 23;
627
628     // Same addressing mode as fixup_arm_pcrel_10, but with 16-bit halfwords
629     // swapped.
630     if (Kind == ARM::fixup_t2_pcrel_10)
631       return swapHalfWords(Value, IsLittleEndian);
632
633     return Value;
634   }
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.
638                        // Fall through.
639   case ARM::fixup_t2_pcrel_9: {
640     // Offset by 4, adjusted by two due to the half-word ordering of thumb.
641     Value = Value - 4;
642     bool isAdd = true;
643     if ((int64_t)Value < 0) {
644       Value = -Value;
645       isAdd = false;
646     }
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");
650       return 0;
651     }
652     Value >>= 1;
653     if (Ctx && Value >= 256) {
654       Ctx->reportError(Fixup.getLoc(), "out of range pc-relative fixup value");
655       return 0;
656     }
657     Value |= isAdd << 23;
658
659     // Same addressing mode as fixup_arm_pcrel_9, but with 16-bit halfwords
660     // swapped.
661     if (Kind == ARM::fixup_t2_pcrel_9)
662       return swapHalfWords(Value, IsLittleEndian);
663
664     return Value;
665   }
666   }
667 }
668
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,
674                                       bool &IsResolved) {
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)
678   // twiddled.
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) {
685     if (Sym) {
686       if (Asm.isThumbFunc(Sym))
687         Value |= 1;
688     }
689   }
690   if (IsResolved && (unsigned)Fixup.getKind() == ARM::fixup_arm_thumb_bl) {
691     assert(Sym && "How did we resolve this?");
692
693     // If the symbol is external the linker will handle it.
694     // FIXME: Should we handle it as an optimization?
695
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)
699       IsResolved = false;
700   }
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))
708     IsResolved = false;
709
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);
715 }
716
717 /// getFixupKindNumBytes - The number of bytes the fixup may change.
718 static unsigned getFixupKindNumBytes(unsigned Kind) {
719   switch (Kind) {
720   default:
721     llvm_unreachable("Unknown fixup kind!");
722
723   case FK_Data_1:
724   case ARM::fixup_arm_thumb_bcc:
725   case ARM::fixup_arm_thumb_cp:
726   case ARM::fixup_thumb_adr_pcrel_10:
727     return 1;
728
729   case FK_Data_2:
730   case ARM::fixup_arm_thumb_br:
731   case ARM::fixup_arm_thumb_cb:
732     return 2;
733
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:
744     return 3;
745
746   case FK_Data_4:
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:
759     return 4;
760
761   case FK_SecRel_2:
762     return 2;
763   case FK_SecRel_4:
764     return 4;
765   }
766 }
767
768 /// getFixupKindContainerSizeBytes - The number of bytes of the
769 /// container involved in big endian.
770 static unsigned getFixupKindContainerSizeBytes(unsigned Kind) {
771   switch (Kind) {
772   default:
773     llvm_unreachable("Unknown fixup kind!");
774
775   case FK_Data_1:
776     return 1;
777   case FK_Data_2:
778     return 2;
779   case FK_Data_4:
780     return 4;
781
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.
788     return 2;
789
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.
811     return 4;
812   }
813 }
814
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());
819   Value =
820       adjustFixupValue(Fixup, Value, IsPCRel, nullptr, IsLittleEndian, true);
821   if (!Value)
822     return; // Doesn't change encoding.
823
824   unsigned Offset = Fixup.getOffset();
825   assert(Offset + NumBytes <= DataSize && "Invalid fixup offset!");
826
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!");
833   }
834
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
837   // bitfields above.
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);
841   }
842 }
843
844 namespace CU {
845
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,
852
853   UNWIND_ARM_FRAME_STACK_ADJUST_MASK           = 0x00C00000,
854
855   UNWIND_ARM_FRAME_FIRST_PUSH_R4               = 0x00000001,
856   UNWIND_ARM_FRAME_FIRST_PUSH_R5               = 0x00000002,
857   UNWIND_ARM_FRAME_FIRST_PUSH_R6               = 0x00000004,
858
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,
864
865   UNWIND_ARM_FRAME_D_REG_COUNT_MASK            = 0x00000F00,
866
867   UNWIND_ARM_DWARF_SECTION_OFFSET              = 0x00FFFFFF
868 };
869
870 } // end CU namespace
871
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)
881     return 0;
882   // No .cfi directives means no frame.
883   if (Instrs.empty())
884     return 0;
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) {
893     int Reg;
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);
899       break;
900     case MCCFIInstruction::OpDefCfaOffset: // DW_CFA_def_cfa_offset
901       CFARegisterOffset = -Inst.getOffset();
902       break;
903     case MCCFIInstruction::OpDefCfaRegister: // DW_CFA_def_cfa_register
904       CFARegister = MRI.getLLVMRegNum(Inst.getRegister(), true);
905       break;
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();
912         ++FloatRegCount;
913       } else {
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;
918       }
919       break;
920     case MCCFIInstruction::OpRelOffset: // DW_CFA_advance_loc
921       // Ignore
922       break;
923     default:
924       // Directive not convertable to compact unwind, bail out.
925       DEBUG_WITH_TYPE("compact-unwind",
926                       llvm::dbgs()
927                           << "CFI directive not compatiable with comact "
928                              "unwind encoding, opcode=" << Inst.getOperation()
929                           << "\n");
930       return CU::UNWIND_ARM_MODE_DWARF;
931       break;
932     }
933   }
934
935   // If no frame set up, return no unwind info.
936   if ((CFARegister == ARM::SP) && (CFARegisterOffset == 0))
937     return 0;
938
939   // Verify standard frame (lr/r7) was used.
940   if (CFARegister != ARM::R7) {
941     DEBUG_WITH_TYPE("compact-unwind", llvm::dbgs() << "frame register is "
942                                                    << CFARegister
943                                                    << " instead of r7\n");
944     return CU::UNWIND_ARM_MODE_DWARF;
945   }
946   int StackAdjust = CFARegisterOffset - 8;
947   if (RegOffsets.lookup(ARM::LR) != (-4 - StackAdjust)) {
948     DEBUG_WITH_TYPE("compact-unwind",
949                     llvm::dbgs()
950                         << "LR not saved as standard frame, StackAdjust="
951                         << StackAdjust
952                         << ", CFARegisterOffset=" << CFARegisterOffset
953                         << ", lr save at offset=" << RegOffsets[14] << "\n");
954     return CU::UNWIND_ARM_MODE_DWARF;
955   }
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;
960   }
961   uint32_t CompactUnwindEncoding = CU::UNWIND_ARM_MODE_FRAME;
962
963   // If var-args are used, there may be a stack adjust required.
964   switch (StackAdjust) {
965   case 0:
966     break;
967   case 4:
968     CompactUnwindEncoding |= 0x00400000;
969     break;
970   case 8:
971     CompactUnwindEncoding |= 0x00800000;
972     break;
973   case 12:
974     CompactUnwindEncoding |= 0x00C00000;
975     break;
976   default:
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;
981   }
982
983   // If r6 is saved, it must be right below r7.
984   static struct {
985     unsigned Reg;
986     unsigned Encoding;
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}};
995
996   int CurOffset = -8 - StackAdjust;
997   for (auto CSReg : GPRCSRegs) {
998     auto Offset = RegOffsets.find(CSReg.Reg);
999     if (Offset == RegOffsets.end())
1000       continue;
1001
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;
1009     }
1010     CompactUnwindEncoding |= CSReg.Encoding;
1011     CurOffset -= 4;
1012   }
1013
1014   // If no floats saved, we are done.
1015   if (FloatRegCount == 0)
1016     return CompactUnwindEncoding;
1017
1018   // Switch mode to include D register saving.
1019   CompactUnwindEncoding &= ~CU::UNWIND_ARM_MODE_MASK;
1020   CompactUnwindEncoding |= CU::UNWIND_ARM_MODE_FRAME_D;
1021
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;
1029   }
1030
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])
1041                                    << " not saved\n");
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
1049                                    << "\n");
1050       return CU::UNWIND_ARM_MODE_DWARF;
1051     }
1052     CurOffset -= 8;
1053   }
1054
1055   return CompactUnwindEncoding | ((FloatRegCount - 1) << 8);
1056 }
1057
1058 static MachO::CPUSubTypeARM getMachOSubTypeFromArch(StringRef Arch) {
1059   unsigned AK = ARM::parseArch(Arch);
1060   switch (AK) {
1061   default:
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;
1069   case ARM::AK_ARMV6:
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;
1084   }
1085 }
1086
1087 MCAsmBackend *llvm::createARMAsmBackend(const Target &T,
1088                                         const MCRegisterInfo &MRI,
1089                                         const Triple &TheTriple, StringRef CPU,
1090                                         bool isLittle) {
1091   switch (TheTriple.getObjectFormat()) {
1092   default:
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);
1097   }
1098   case Triple::COFF:
1099     assert(TheTriple.isOSWindows() && "non-Windows ARM COFF is not supported");
1100     return new ARMAsmBackendWinCOFF(T, TheTriple);
1101   case Triple::ELF:
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);
1105   }
1106 }
1107
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);
1112 }
1113
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);
1118 }
1119
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);
1124 }
1125
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);
1130 }