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