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