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