AVX512: Implemented DAG lowering for shuff62x2/shufi62x2 instructions ( shuffle packe...
[oota-llvm.git] / lib / Target / ARM / MCTargetDesc / ARMAsmBackend.cpp
1 //===-- ARMAsmBackend.cpp - ARM Assembler Backend -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "MCTargetDesc/ARMMCTargetDesc.h"
11 #include "MCTargetDesc/ARMAddressingModes.h"
12 #include "MCTargetDesc/ARMAsmBackend.h"
13 #include "MCTargetDesc/ARMAsmBackendDarwin.h"
14 #include "MCTargetDesc/ARMAsmBackendELF.h"
15 #include "MCTargetDesc/ARMAsmBackendWinCOFF.h"
16 #include "MCTargetDesc/ARMBaseInfo.h"
17 #include "MCTargetDesc/ARMFixupKinds.h"
18 #include "llvm/ADT/StringSwitch.h"
19 #include "llvm/MC/MCAsmBackend.h"
20 #include "llvm/MC/MCAssembler.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCDirectives.h"
23 #include "llvm/MC/MCELFObjectWriter.h"
24 #include "llvm/MC/MCExpr.h"
25 #include "llvm/MC/MCFixupKindInfo.h"
26 #include "llvm/MC/MCMachObjectWriter.h"
27 #include "llvm/MC/MCObjectWriter.h"
28 #include "llvm/MC/MCSectionELF.h"
29 #include "llvm/MC/MCSectionMachO.h"
30 #include "llvm/MC/MCSubtargetInfo.h"
31 #include "llvm/MC/MCValue.h"
32 #include "llvm/Support/ELF.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MachO.h"
35 #include "llvm/Support/TargetParser.h"
36 #include "llvm/Support/raw_ostream.h"
37 using namespace llvm;
38
39 namespace {
40 class ARMELFObjectWriter : public MCELFObjectTargetWriter {
41 public:
42   ARMELFObjectWriter(uint8_t OSABI)
43       : MCELFObjectTargetWriter(/*Is64Bit*/ false, OSABI, ELF::EM_ARM,
44                                 /*HasRelocationAddend*/ false) {}
45 };
46
47 const MCFixupKindInfo &ARMAsmBackend::getFixupKindInfo(MCFixupKind Kind) const {
48   const static MCFixupKindInfo InfosLE[ARM::NumTargetFixupKinds] = {
49       // This table *must* be in the order that the fixup_* kinds are defined in
50       // ARMFixupKinds.h.
51       //
52       // Name                      Offset (bits) Size (bits)     Flags
53       {"fixup_arm_ldst_pcrel_12", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
54       {"fixup_t2_ldst_pcrel_12", 0, 32,
55        MCFixupKindInfo::FKF_IsPCRel |
56            MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
57       {"fixup_arm_pcrel_10_unscaled", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
58       {"fixup_arm_pcrel_10", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
59       {"fixup_t2_pcrel_10", 0, 32,
60        MCFixupKindInfo::FKF_IsPCRel |
61            MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
62       {"fixup_thumb_adr_pcrel_10", 0, 8,
63        MCFixupKindInfo::FKF_IsPCRel |
64            MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
65       {"fixup_arm_adr_pcrel_12", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
66       {"fixup_t2_adr_pcrel_12", 0, 32,
67        MCFixupKindInfo::FKF_IsPCRel |
68            MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
69       {"fixup_arm_condbranch", 0, 24, MCFixupKindInfo::FKF_IsPCRel},
70       {"fixup_arm_uncondbranch", 0, 24, MCFixupKindInfo::FKF_IsPCRel},
71       {"fixup_t2_condbranch", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
72       {"fixup_t2_uncondbranch", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
73       {"fixup_arm_thumb_br", 0, 16, MCFixupKindInfo::FKF_IsPCRel},
74       {"fixup_arm_uncondbl", 0, 24, MCFixupKindInfo::FKF_IsPCRel},
75       {"fixup_arm_condbl", 0, 24, MCFixupKindInfo::FKF_IsPCRel},
76       {"fixup_arm_blx", 0, 24, MCFixupKindInfo::FKF_IsPCRel},
77       {"fixup_arm_thumb_bl", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
78       {"fixup_arm_thumb_blx", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
79       {"fixup_arm_thumb_cb", 0, 16, MCFixupKindInfo::FKF_IsPCRel},
80       {"fixup_arm_thumb_cp", 0, 8,
81        MCFixupKindInfo::FKF_IsPCRel |
82            MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
83       {"fixup_arm_thumb_bcc", 0, 8, MCFixupKindInfo::FKF_IsPCRel},
84       // movw / movt: 16-bits immediate but scattered into two chunks 0 - 12, 16
85       // - 19.
86       {"fixup_arm_movt_hi16", 0, 20, 0},
87       {"fixup_arm_movw_lo16", 0, 20, 0},
88       {"fixup_t2_movt_hi16", 0, 20, 0},
89       {"fixup_t2_movw_lo16", 0, 20, 0},
90   };
91   const static MCFixupKindInfo InfosBE[ARM::NumTargetFixupKinds] = {
92       // This table *must* be in the order that the fixup_* kinds are defined in
93       // ARMFixupKinds.h.
94       //
95       // Name                      Offset (bits) Size (bits)     Flags
96       {"fixup_arm_ldst_pcrel_12", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
97       {"fixup_t2_ldst_pcrel_12", 0, 32,
98        MCFixupKindInfo::FKF_IsPCRel |
99            MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
100       {"fixup_arm_pcrel_10_unscaled", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
101       {"fixup_arm_pcrel_10", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
102       {"fixup_t2_pcrel_10", 0, 32,
103        MCFixupKindInfo::FKF_IsPCRel |
104            MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
105       {"fixup_thumb_adr_pcrel_10", 8, 8,
106        MCFixupKindInfo::FKF_IsPCRel |
107            MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
108       {"fixup_arm_adr_pcrel_12", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
109       {"fixup_t2_adr_pcrel_12", 0, 32,
110        MCFixupKindInfo::FKF_IsPCRel |
111            MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
112       {"fixup_arm_condbranch", 8, 24, MCFixupKindInfo::FKF_IsPCRel},
113       {"fixup_arm_uncondbranch", 8, 24, MCFixupKindInfo::FKF_IsPCRel},
114       {"fixup_t2_condbranch", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
115       {"fixup_t2_uncondbranch", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
116       {"fixup_arm_thumb_br", 0, 16, MCFixupKindInfo::FKF_IsPCRel},
117       {"fixup_arm_uncondbl", 8, 24, MCFixupKindInfo::FKF_IsPCRel},
118       {"fixup_arm_condbl", 8, 24, MCFixupKindInfo::FKF_IsPCRel},
119       {"fixup_arm_blx", 8, 24, MCFixupKindInfo::FKF_IsPCRel},
120       {"fixup_arm_thumb_bl", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
121       {"fixup_arm_thumb_blx", 0, 32, MCFixupKindInfo::FKF_IsPCRel},
122       {"fixup_arm_thumb_cb", 0, 16, MCFixupKindInfo::FKF_IsPCRel},
123       {"fixup_arm_thumb_cp", 8, 8,
124        MCFixupKindInfo::FKF_IsPCRel |
125            MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
126       {"fixup_arm_thumb_bcc", 8, 8, MCFixupKindInfo::FKF_IsPCRel},
127       // movw / movt: 16-bits immediate but scattered into two chunks 0 - 12, 16
128       // - 19.
129       {"fixup_arm_movt_hi16", 12, 20, 0},
130       {"fixup_arm_movw_lo16", 12, 20, 0},
131       {"fixup_t2_movt_hi16", 12, 20, 0},
132       {"fixup_t2_movw_lo16", 12, 20, 0},
133   };
134
135   if (Kind < FirstTargetFixupKind)
136     return MCAsmBackend::getFixupKindInfo(Kind);
137
138   assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
139          "Invalid kind!");
140   return (IsLittleEndian ? InfosLE : InfosBE)[Kind - FirstTargetFixupKind];
141 }
142
143 void ARMAsmBackend::handleAssemblerFlag(MCAssemblerFlag Flag) {
144   switch (Flag) {
145   default:
146     break;
147   case MCAF_Code16:
148     setIsThumb(true);
149     break;
150   case MCAF_Code32:
151     setIsThumb(false);
152     break;
153   }
154 }
155 } // end anonymous namespace
156
157 unsigned ARMAsmBackend::getRelaxedOpcode(unsigned Op) const {
158   bool HasThumb2 = STI->getFeatureBits()[ARM::FeatureThumb2];
159
160   switch (Op) {
161   default:
162     return Op;
163   case ARM::tBcc:
164     return HasThumb2 ? (unsigned)ARM::t2Bcc : Op;
165   case ARM::tLDRpci:
166     return HasThumb2 ? (unsigned)ARM::t2LDRpci : Op;
167   case ARM::tADR:
168     return HasThumb2 ? (unsigned)ARM::t2ADR : Op;
169   case ARM::tB:
170     return HasThumb2 ? (unsigned)ARM::t2B : Op;
171   case ARM::tCBZ:
172     return ARM::tHINT;
173   case ARM::tCBNZ:
174     return ARM::tHINT;
175   }
176 }
177
178 bool ARMAsmBackend::mayNeedRelaxation(const MCInst &Inst) const {
179   if (getRelaxedOpcode(Inst.getOpcode()) != Inst.getOpcode())
180     return true;
181   return false;
182 }
183
184 const char *ARMAsmBackend::reasonForFixupRelaxation(const MCFixup &Fixup,
185                                                     uint64_t Value) const {
186   switch ((unsigned)Fixup.getKind()) {
187   case ARM::fixup_arm_thumb_br: {
188     // Relaxing tB to t2B. tB has a signed 12-bit displacement with the
189     // low bit being an implied zero. There's an implied +4 offset for the
190     // branch, so we adjust the other way here to determine what's
191     // encodable.
192     //
193     // Relax if the value is too big for a (signed) i8.
194     int64_t Offset = int64_t(Value) - 4;
195     if (Offset > 2046 || Offset < -2048)
196       return "out of range pc-relative fixup value";
197     break;
198   }
199   case ARM::fixup_arm_thumb_bcc: {
200     // Relaxing tBcc to t2Bcc. tBcc has a signed 9-bit displacement with the
201     // low bit being an implied zero. There's an implied +4 offset for the
202     // branch, so we adjust the other way here to determine what's
203     // encodable.
204     //
205     // Relax if the value is too big for a (signed) i8.
206     int64_t Offset = int64_t(Value) - 4;
207     if (Offset > 254 || Offset < -256)
208       return "out of range pc-relative fixup value";
209     break;
210   }
211   case ARM::fixup_thumb_adr_pcrel_10:
212   case ARM::fixup_arm_thumb_cp: {
213     // If the immediate is negative, greater than 1020, or not a multiple
214     // of four, the wide version of the instruction must be used.
215     int64_t Offset = int64_t(Value) - 4;
216     if (Offset & 3)
217       return "misaligned pc-relative fixup value";
218     else if (Offset > 1020 || Offset < 0)
219       return "out of range pc-relative fixup value";
220     break;
221   }
222   case ARM::fixup_arm_thumb_cb: {
223     // If we have a Thumb CBZ or CBNZ instruction and its target is the next
224     // instruction it is is actually out of range for the instruction.
225     // It will be changed to a NOP.
226     int64_t Offset = (Value & ~1);
227     if (Offset == 2)
228       return "will be converted to nop";
229     break;
230   }
231   default:
232     llvm_unreachable("Unexpected fixup kind in reasonForFixupRelaxation()!");
233   }
234   return nullptr;
235 }
236
237 bool ARMAsmBackend::fixupNeedsRelaxation(const MCFixup &Fixup, uint64_t Value,
238                                          const MCRelaxableFragment *DF,
239                                          const MCAsmLayout &Layout) const {
240   return reasonForFixupRelaxation(Fixup, Value);
241 }
242
243 void ARMAsmBackend::relaxInstruction(const MCInst &Inst, MCInst &Res) const {
244   unsigned RelaxedOp = getRelaxedOpcode(Inst.getOpcode());
245
246   // Sanity check w/ diagnostic if we get here w/ a bogus instruction.
247   if (RelaxedOp == Inst.getOpcode()) {
248     SmallString<256> Tmp;
249     raw_svector_ostream OS(Tmp);
250     Inst.dump_pretty(OS);
251     OS << "\n";
252     report_fatal_error("unexpected instruction to relax: " + OS.str());
253   }
254
255   // If we are changing Thumb CBZ or CBNZ instruction to a NOP, aka tHINT, we
256   // have to change the operands too.
257   if ((Inst.getOpcode() == ARM::tCBZ || Inst.getOpcode() == ARM::tCBNZ) &&
258       RelaxedOp == ARM::tHINT) {
259     Res.setOpcode(RelaxedOp);
260     Res.addOperand(MCOperand::createImm(0));
261     Res.addOperand(MCOperand::createImm(14));
262     Res.addOperand(MCOperand::createReg(0));
263     return;
264   }
265
266   // The rest of instructions we're relaxing have the same operands.
267   // We just need to update to the proper opcode.
268   Res = Inst;
269   Res.setOpcode(RelaxedOp);
270 }
271
272 bool ARMAsmBackend::writeNopData(uint64_t Count, MCObjectWriter *OW) const {
273   const uint16_t Thumb1_16bitNopEncoding = 0x46c0; // using MOV r8,r8
274   const uint16_t Thumb2_16bitNopEncoding = 0xbf00; // NOP
275   const uint32_t ARMv4_NopEncoding = 0xe1a00000;   // using MOV r0,r0
276   const uint32_t ARMv6T2_NopEncoding = 0xe320f000; // NOP
277   if (isThumb()) {
278     const uint16_t nopEncoding =
279         hasNOP() ? Thumb2_16bitNopEncoding : Thumb1_16bitNopEncoding;
280     uint64_t NumNops = Count / 2;
281     for (uint64_t i = 0; i != NumNops; ++i)
282       OW->write16(nopEncoding);
283     if (Count & 1)
284       OW->write8(0);
285     return true;
286   }
287   // ARM mode
288   const uint32_t nopEncoding =
289       hasNOP() ? ARMv6T2_NopEncoding : ARMv4_NopEncoding;
290   uint64_t NumNops = Count / 4;
291   for (uint64_t i = 0; i != NumNops; ++i)
292     OW->write32(nopEncoding);
293   // FIXME: should this function return false when unable to write exactly
294   // 'Count' bytes with NOP encodings?
295   switch (Count % 4) {
296   default:
297     break; // No leftover bytes to write
298   case 1:
299     OW->write8(0);
300     break;
301   case 2:
302     OW->write16(0);
303     break;
304   case 3:
305     OW->write16(0);
306     OW->write8(0xa0);
307     break;
308   }
309
310   return true;
311 }
312
313 static uint32_t swapHalfWords(uint32_t Value, bool IsLittleEndian) {
314   if (IsLittleEndian) {
315     // Note that the halfwords are stored high first and low second in thumb;
316     // so we need to swap the fixup value here to map properly.
317     uint32_t Swapped = (Value & 0xFFFF0000) >> 16;
318     Swapped |= (Value & 0x0000FFFF) << 16;
319     return Swapped;
320   } else
321     return Value;
322 }
323
324 static uint32_t joinHalfWords(uint32_t FirstHalf, uint32_t SecondHalf,
325                               bool IsLittleEndian) {
326   uint32_t Value;
327
328   if (IsLittleEndian) {
329     Value = (SecondHalf & 0xFFFF) << 16;
330     Value |= (FirstHalf & 0xFFFF);
331   } else {
332     Value = (SecondHalf & 0xFFFF);
333     Value |= (FirstHalf & 0xFFFF) << 16;
334   }
335
336   return Value;
337 }
338
339 unsigned ARMAsmBackend::adjustFixupValue(const MCFixup &Fixup, uint64_t Value,
340                                          bool IsPCRel, MCContext *Ctx,
341                                          bool IsLittleEndian,
342                                          bool IsResolved) const {
343   unsigned Kind = Fixup.getKind();
344   switch (Kind) {
345   default:
346     llvm_unreachable("Unknown fixup kind!");
347   case FK_Data_1:
348   case FK_Data_2:
349   case FK_Data_4:
350     return Value;
351   case FK_SecRel_2:
352     return Value;
353   case FK_SecRel_4:
354     return Value;
355   case ARM::fixup_arm_movt_hi16:
356     if (!IsPCRel)
357       Value >>= 16;
358   // Fallthrough
359   case ARM::fixup_arm_movw_lo16: {
360     unsigned Hi4 = (Value & 0xF000) >> 12;
361     unsigned Lo12 = Value & 0x0FFF;
362     // inst{19-16} = Hi4;
363     // inst{11-0} = Lo12;
364     Value = (Hi4 << 16) | (Lo12);
365     return Value;
366   }
367   case ARM::fixup_t2_movt_hi16:
368     if (!IsPCRel)
369       Value >>= 16;
370   // Fallthrough
371   case ARM::fixup_t2_movw_lo16: {
372     unsigned Hi4 = (Value & 0xF000) >> 12;
373     unsigned i = (Value & 0x800) >> 11;
374     unsigned Mid3 = (Value & 0x700) >> 8;
375     unsigned Lo8 = Value & 0x0FF;
376     // inst{19-16} = Hi4;
377     // inst{26} = i;
378     // inst{14-12} = Mid3;
379     // inst{7-0} = Lo8;
380     Value = (Hi4 << 16) | (i << 26) | (Mid3 << 12) | (Lo8);
381     return swapHalfWords(Value, IsLittleEndian);
382   }
383   case ARM::fixup_arm_ldst_pcrel_12:
384     // ARM PC-relative values are offset by 8.
385     Value -= 4;
386   // FALLTHROUGH
387   case ARM::fixup_t2_ldst_pcrel_12: {
388     // Offset by 4, adjusted by two due to the half-word ordering of thumb.
389     Value -= 4;
390     bool isAdd = true;
391     if ((int64_t)Value < 0) {
392       Value = -Value;
393       isAdd = false;
394     }
395     if (Ctx && Value >= 4096)
396       Ctx->reportFatalError(Fixup.getLoc(), "out of range pc-relative fixup value");
397     Value |= isAdd << 23;
398
399     // Same addressing mode as fixup_arm_pcrel_10,
400     // but with 16-bit halfwords swapped.
401     if (Kind == ARM::fixup_t2_ldst_pcrel_12)
402       return swapHalfWords(Value, IsLittleEndian);
403
404     return Value;
405   }
406   case ARM::fixup_arm_adr_pcrel_12: {
407     // ARM PC-relative values are offset by 8.
408     Value -= 8;
409     unsigned opc = 4; // bits {24-21}. Default to add: 0b0100
410     if ((int64_t)Value < 0) {
411       Value = -Value;
412       opc = 2; // 0b0010
413     }
414     if (Ctx && ARM_AM::getSOImmVal(Value) == -1)
415       Ctx->reportFatalError(Fixup.getLoc(), "out of range pc-relative fixup value");
416     // Encode the immediate and shift the opcode into place.
417     return ARM_AM::getSOImmVal(Value) | (opc << 21);
418   }
419
420   case ARM::fixup_t2_adr_pcrel_12: {
421     Value -= 4;
422     unsigned opc = 0;
423     if ((int64_t)Value < 0) {
424       Value = -Value;
425       opc = 5;
426     }
427
428     uint32_t out = (opc << 21);
429     out |= (Value & 0x800) << 15;
430     out |= (Value & 0x700) << 4;
431     out |= (Value & 0x0FF);
432
433     return swapHalfWords(out, IsLittleEndian);
434   }
435
436   case ARM::fixup_arm_condbranch:
437   case ARM::fixup_arm_uncondbranch:
438   case ARM::fixup_arm_uncondbl:
439   case ARM::fixup_arm_condbl:
440   case ARM::fixup_arm_blx:
441     // These values don't encode the low two bits since they're always zero.
442     // Offset by 8 just as above.
443     if (const MCSymbolRefExpr *SRE =
444             dyn_cast<MCSymbolRefExpr>(Fixup.getValue()))
445       if (SRE->getKind() == MCSymbolRefExpr::VK_ARM_TLSCALL)
446         return 0;
447     return 0xffffff & ((Value - 8) >> 2);
448   case ARM::fixup_t2_uncondbranch: {
449     Value = Value - 4;
450     Value >>= 1; // Low bit is not encoded.
451
452     uint32_t out = 0;
453     bool I = Value & 0x800000;
454     bool J1 = Value & 0x400000;
455     bool J2 = Value & 0x200000;
456     J1 ^= I;
457     J2 ^= I;
458
459     out |= I << 26;                 // S bit
460     out |= !J1 << 13;               // J1 bit
461     out |= !J2 << 11;               // J2 bit
462     out |= (Value & 0x1FF800) << 5; // imm6 field
463     out |= (Value & 0x0007FF);      // imm11 field
464
465     return swapHalfWords(out, IsLittleEndian);
466   }
467   case ARM::fixup_t2_condbranch: {
468     Value = Value - 4;
469     Value >>= 1; // Low bit is not encoded.
470
471     uint64_t out = 0;
472     out |= (Value & 0x80000) << 7; // S bit
473     out |= (Value & 0x40000) >> 7; // J2 bit
474     out |= (Value & 0x20000) >> 4; // J1 bit
475     out |= (Value & 0x1F800) << 5; // imm6 field
476     out |= (Value & 0x007FF);      // imm11 field
477
478     return swapHalfWords(out, IsLittleEndian);
479   }
480   case ARM::fixup_arm_thumb_bl: {
481     // The value doesn't encode the low bit (always zero) and is offset by
482     // four. The 32-bit immediate value is encoded as
483     //   imm32 = SignExtend(S:I1:I2:imm10:imm11:0)
484     // where I1 = NOT(J1 ^ S) and I2 = NOT(J2 ^ S).
485     // The value is encoded into disjoint bit positions in the destination
486     // opcode. x = unchanged, I = immediate value bit, S = sign extension bit,
487     // J = either J1 or J2 bit
488     //
489     //   BL:  xxxxxSIIIIIIIIII xxJxJIIIIIIIIIII
490     //
491     // Note that the halfwords are stored high first, low second; so we need
492     // to transpose the fixup value here to map properly.
493     uint32_t offset = (Value - 4) >> 1;
494     uint32_t signBit = (offset & 0x800000) >> 23;
495     uint32_t I1Bit = (offset & 0x400000) >> 22;
496     uint32_t J1Bit = (I1Bit ^ 0x1) ^ signBit;
497     uint32_t I2Bit = (offset & 0x200000) >> 21;
498     uint32_t J2Bit = (I2Bit ^ 0x1) ^ signBit;
499     uint32_t imm10Bits = (offset & 0x1FF800) >> 11;
500     uint32_t imm11Bits = (offset & 0x000007FF);
501
502     uint32_t FirstHalf = (((uint16_t)signBit << 10) | (uint16_t)imm10Bits);
503     uint32_t SecondHalf = (((uint16_t)J1Bit << 13) | ((uint16_t)J2Bit << 11) |
504                            (uint16_t)imm11Bits);
505     return joinHalfWords(FirstHalf, SecondHalf, IsLittleEndian);
506   }
507   case ARM::fixup_arm_thumb_blx: {
508     // The value doesn't encode the low two bits (always zero) and is offset by
509     // four (see fixup_arm_thumb_cp). The 32-bit immediate value is encoded as
510     //   imm32 = SignExtend(S:I1:I2:imm10H:imm10L:00)
511     // where I1 = NOT(J1 ^ S) and I2 = NOT(J2 ^ S).
512     // The value is encoded into disjoint bit positions in the destination
513     // opcode. x = unchanged, I = immediate value bit, S = sign extension bit,
514     // J = either J1 or J2 bit, 0 = zero.
515     //
516     //   BLX: xxxxxSIIIIIIIIII xxJxJIIIIIIIIII0
517     //
518     // Note that the halfwords are stored high first, low second; so we need
519     // to transpose the fixup value here to map properly.
520     uint32_t offset = (Value - 2) >> 2;
521     if (const MCSymbolRefExpr *SRE =
522             dyn_cast<MCSymbolRefExpr>(Fixup.getValue()))
523       if (SRE->getKind() == MCSymbolRefExpr::VK_ARM_TLSCALL)
524         offset = 0;
525     uint32_t signBit = (offset & 0x400000) >> 22;
526     uint32_t I1Bit = (offset & 0x200000) >> 21;
527     uint32_t J1Bit = (I1Bit ^ 0x1) ^ signBit;
528     uint32_t I2Bit = (offset & 0x100000) >> 20;
529     uint32_t J2Bit = (I2Bit ^ 0x1) ^ signBit;
530     uint32_t imm10HBits = (offset & 0xFFC00) >> 10;
531     uint32_t imm10LBits = (offset & 0x3FF);
532
533     uint32_t FirstHalf = (((uint16_t)signBit << 10) | (uint16_t)imm10HBits);
534     uint32_t SecondHalf = (((uint16_t)J1Bit << 13) | ((uint16_t)J2Bit << 11) |
535                            ((uint16_t)imm10LBits) << 1);
536     return joinHalfWords(FirstHalf, SecondHalf, IsLittleEndian);
537   }
538   case ARM::fixup_thumb_adr_pcrel_10:
539   case ARM::fixup_arm_thumb_cp:
540     // On CPUs supporting Thumb2, this will be relaxed to an ldr.w, otherwise we
541     // could have an error on our hands.
542     if (Ctx && !STI->getFeatureBits()[ARM::FeatureThumb2] && IsResolved) {
543       const char *FixupDiagnostic = reasonForFixupRelaxation(Fixup, Value);
544       if (FixupDiagnostic)
545         Ctx->reportFatalError(Fixup.getLoc(), FixupDiagnostic);
546     }
547     // Offset by 4, and don't encode the low two bits.
548     return ((Value - 4) >> 2) & 0xff;
549   case ARM::fixup_arm_thumb_cb: {
550     // Offset by 4 and don't encode the lower bit, which is always 0.
551     // FIXME: diagnose if no Thumb2
552     uint32_t Binary = (Value - 4) >> 1;
553     return ((Binary & 0x20) << 4) | ((Binary & 0x1f) << 3);
554   }
555   case ARM::fixup_arm_thumb_br:
556     // Offset by 4 and don't encode the lower bit, which is always 0.
557     if (Ctx && !STI->getFeatureBits()[ARM::FeatureThumb2]) {
558       const char *FixupDiagnostic = reasonForFixupRelaxation(Fixup, Value);
559       if (FixupDiagnostic)
560         Ctx->reportFatalError(Fixup.getLoc(), FixupDiagnostic);
561     }
562     return ((Value - 4) >> 1) & 0x7ff;
563   case ARM::fixup_arm_thumb_bcc:
564     // Offset by 4 and don't encode the lower bit, which is always 0.
565     if (Ctx && !STI->getFeatureBits()[ARM::FeatureThumb2]) {
566       const char *FixupDiagnostic = reasonForFixupRelaxation(Fixup, Value);
567       if (FixupDiagnostic)
568         Ctx->reportFatalError(Fixup.getLoc(), FixupDiagnostic);
569     }
570     return ((Value - 4) >> 1) & 0xff;
571   case ARM::fixup_arm_pcrel_10_unscaled: {
572     Value = Value - 8; // ARM fixups offset by an additional word and don't
573                        // need to adjust for the half-word ordering.
574     bool isAdd = true;
575     if ((int64_t)Value < 0) {
576       Value = -Value;
577       isAdd = false;
578     }
579     // The value has the low 4 bits encoded in [3:0] and the high 4 in [11:8].
580     if (Ctx && Value >= 256)
581       Ctx->reportFatalError(Fixup.getLoc(), "out of range pc-relative fixup value");
582     Value = (Value & 0xf) | ((Value & 0xf0) << 4);
583     return Value | (isAdd << 23);
584   }
585   case ARM::fixup_arm_pcrel_10:
586     Value = Value - 4; // ARM fixups offset by an additional word and don't
587                        // need to adjust for the half-word ordering.
588                        // Fall through.
589   case ARM::fixup_t2_pcrel_10: {
590     // Offset by 4, adjusted by two due to the half-word ordering of thumb.
591     Value = Value - 4;
592     bool isAdd = true;
593     if ((int64_t)Value < 0) {
594       Value = -Value;
595       isAdd = false;
596     }
597     // These values don't encode the low two bits since they're always zero.
598     Value >>= 2;
599     if (Ctx && Value >= 256)
600       Ctx->reportFatalError(Fixup.getLoc(), "out of range pc-relative fixup value");
601     Value |= isAdd << 23;
602
603     // Same addressing mode as fixup_arm_pcrel_10, but with 16-bit halfwords
604     // swapped.
605     if (Kind == ARM::fixup_t2_pcrel_10)
606       return swapHalfWords(Value, IsLittleEndian);
607
608     return Value;
609   }
610   }
611 }
612
613 void ARMAsmBackend::processFixupValue(const MCAssembler &Asm,
614                                       const MCAsmLayout &Layout,
615                                       const MCFixup &Fixup,
616                                       const MCFragment *DF,
617                                       const MCValue &Target, uint64_t &Value,
618                                       bool &IsResolved) {
619   const MCSymbolRefExpr *A = Target.getSymA();
620   // Some fixups to thumb function symbols need the low bit (thumb bit)
621   // twiddled.
622   if ((unsigned)Fixup.getKind() != ARM::fixup_arm_ldst_pcrel_12 &&
623       (unsigned)Fixup.getKind() != ARM::fixup_t2_ldst_pcrel_12 &&
624       (unsigned)Fixup.getKind() != ARM::fixup_arm_adr_pcrel_12 &&
625       (unsigned)Fixup.getKind() != ARM::fixup_thumb_adr_pcrel_10 &&
626       (unsigned)Fixup.getKind() != ARM::fixup_t2_adr_pcrel_12 &&
627       (unsigned)Fixup.getKind() != ARM::fixup_arm_thumb_cp) {
628     if (A) {
629       const MCSymbol &Sym = A->getSymbol();
630       if (Asm.isThumbFunc(&Sym))
631         Value |= 1;
632     }
633   }
634   // For Thumb1 BL instruction, it is possible to be a long jump between
635   // the basic blocks of the same function.  Thus, we would like to resolve
636   // the offset when the destination has the same MCFragment.
637   if (A && (unsigned)Fixup.getKind() == ARM::fixup_arm_thumb_bl) {
638     const MCSymbol &Sym = A->getSymbol();
639     IsResolved = (Sym.getFragment() == DF);
640   }
641   // We must always generate a relocation for BL/BLX instructions if we have
642   // a symbol to reference, as the linker relies on knowing the destination
643   // symbol's thumb-ness to get interworking right.
644   if (A && ((unsigned)Fixup.getKind() == ARM::fixup_arm_thumb_blx ||
645             (unsigned)Fixup.getKind() == ARM::fixup_arm_blx ||
646             (unsigned)Fixup.getKind() == ARM::fixup_arm_uncondbl ||
647             (unsigned)Fixup.getKind() == ARM::fixup_arm_condbl))
648     IsResolved = false;
649
650   // Try to get the encoded value for the fixup as-if we're mapping it into
651   // the instruction. This allows adjustFixupValue() to issue a diagnostic
652   // if the value aren't invalid.
653   (void)adjustFixupValue(Fixup, Value, false, &Asm.getContext(),
654                          IsLittleEndian, IsResolved);
655 }
656
657 /// getFixupKindNumBytes - The number of bytes the fixup may change.
658 static unsigned getFixupKindNumBytes(unsigned Kind) {
659   switch (Kind) {
660   default:
661     llvm_unreachable("Unknown fixup kind!");
662
663   case FK_Data_1:
664   case ARM::fixup_arm_thumb_bcc:
665   case ARM::fixup_arm_thumb_cp:
666   case ARM::fixup_thumb_adr_pcrel_10:
667     return 1;
668
669   case FK_Data_2:
670   case ARM::fixup_arm_thumb_br:
671   case ARM::fixup_arm_thumb_cb:
672     return 2;
673
674   case ARM::fixup_arm_pcrel_10_unscaled:
675   case ARM::fixup_arm_ldst_pcrel_12:
676   case ARM::fixup_arm_pcrel_10:
677   case ARM::fixup_arm_adr_pcrel_12:
678   case ARM::fixup_arm_uncondbl:
679   case ARM::fixup_arm_condbl:
680   case ARM::fixup_arm_blx:
681   case ARM::fixup_arm_condbranch:
682   case ARM::fixup_arm_uncondbranch:
683     return 3;
684
685   case FK_Data_4:
686   case ARM::fixup_t2_ldst_pcrel_12:
687   case ARM::fixup_t2_condbranch:
688   case ARM::fixup_t2_uncondbranch:
689   case ARM::fixup_t2_pcrel_10:
690   case ARM::fixup_t2_adr_pcrel_12:
691   case ARM::fixup_arm_thumb_bl:
692   case ARM::fixup_arm_thumb_blx:
693   case ARM::fixup_arm_movt_hi16:
694   case ARM::fixup_arm_movw_lo16:
695   case ARM::fixup_t2_movt_hi16:
696   case ARM::fixup_t2_movw_lo16:
697     return 4;
698
699   case FK_SecRel_2:
700     return 2;
701   case FK_SecRel_4:
702     return 4;
703   }
704 }
705
706 /// getFixupKindContainerSizeBytes - The number of bytes of the
707 /// container involved in big endian.
708 static unsigned getFixupKindContainerSizeBytes(unsigned Kind) {
709   switch (Kind) {
710   default:
711     llvm_unreachable("Unknown fixup kind!");
712
713   case FK_Data_1:
714     return 1;
715   case FK_Data_2:
716     return 2;
717   case FK_Data_4:
718     return 4;
719
720   case ARM::fixup_arm_thumb_bcc:
721   case ARM::fixup_arm_thumb_cp:
722   case ARM::fixup_thumb_adr_pcrel_10:
723   case ARM::fixup_arm_thumb_br:
724   case ARM::fixup_arm_thumb_cb:
725     // Instruction size is 2 bytes.
726     return 2;
727
728   case ARM::fixup_arm_pcrel_10_unscaled:
729   case ARM::fixup_arm_ldst_pcrel_12:
730   case ARM::fixup_arm_pcrel_10:
731   case ARM::fixup_arm_adr_pcrel_12:
732   case ARM::fixup_arm_uncondbl:
733   case ARM::fixup_arm_condbl:
734   case ARM::fixup_arm_blx:
735   case ARM::fixup_arm_condbranch:
736   case ARM::fixup_arm_uncondbranch:
737   case ARM::fixup_t2_ldst_pcrel_12:
738   case ARM::fixup_t2_condbranch:
739   case ARM::fixup_t2_uncondbranch:
740   case ARM::fixup_t2_pcrel_10:
741   case ARM::fixup_t2_adr_pcrel_12:
742   case ARM::fixup_arm_thumb_bl:
743   case ARM::fixup_arm_thumb_blx:
744   case ARM::fixup_arm_movt_hi16:
745   case ARM::fixup_arm_movw_lo16:
746   case ARM::fixup_t2_movt_hi16:
747   case ARM::fixup_t2_movw_lo16:
748     // Instruction size is 4 bytes.
749     return 4;
750   }
751 }
752
753 void ARMAsmBackend::applyFixup(const MCFixup &Fixup, char *Data,
754                                unsigned DataSize, uint64_t Value,
755                                bool IsPCRel) const {
756   unsigned NumBytes = getFixupKindNumBytes(Fixup.getKind());
757   Value =
758       adjustFixupValue(Fixup, Value, IsPCRel, nullptr, IsLittleEndian, true);
759   if (!Value)
760     return; // Doesn't change encoding.
761
762   unsigned Offset = Fixup.getOffset();
763   assert(Offset + NumBytes <= DataSize && "Invalid fixup offset!");
764
765   // Used to point to big endian bytes.
766   unsigned FullSizeBytes;
767   if (!IsLittleEndian) {
768     FullSizeBytes = getFixupKindContainerSizeBytes(Fixup.getKind());
769     assert((Offset + FullSizeBytes) <= DataSize && "Invalid fixup size!");
770     assert(NumBytes <= FullSizeBytes && "Invalid fixup size!");
771   }
772
773   // For each byte of the fragment that the fixup touches, mask in the bits from
774   // the fixup value. The Value has been "split up" into the appropriate
775   // bitfields above.
776   for (unsigned i = 0; i != NumBytes; ++i) {
777     unsigned Idx = IsLittleEndian ? i : (FullSizeBytes - 1 - i);
778     Data[Offset + Idx] |= uint8_t((Value >> (i * 8)) & 0xff);
779   }
780 }
781
782 static MachO::CPUSubTypeARM getMachOSubTypeFromArch(StringRef Arch) {
783   unsigned AK = ARM::parseArch(Arch);
784   switch (AK) {
785   default:
786     return MachO::CPU_SUBTYPE_ARM_V7;
787   case ARM::AK_ARMV4T:
788     return MachO::CPU_SUBTYPE_ARM_V4T;
789   case ARM::AK_ARMV6:
790   case ARM::AK_ARMV6K:
791     return MachO::CPU_SUBTYPE_ARM_V6;
792   case ARM::AK_ARMV5:
793     return MachO::CPU_SUBTYPE_ARM_V5;
794   case ARM::AK_ARMV5T:
795   case ARM::AK_ARMV5E:
796   case ARM::AK_ARMV5TE:
797   case ARM::AK_ARMV5TEJ:
798     return MachO::CPU_SUBTYPE_ARM_V5TEJ;
799   case ARM::AK_ARMV7:
800     return MachO::CPU_SUBTYPE_ARM_V7;
801   case ARM::AK_ARMV7S:
802     return MachO::CPU_SUBTYPE_ARM_V7S;
803   case ARM::AK_ARMV7K:
804     return MachO::CPU_SUBTYPE_ARM_V7K;
805   case ARM::AK_ARMV6M:
806   case ARM::AK_ARMV6SM:
807     return MachO::CPU_SUBTYPE_ARM_V6M;
808   case ARM::AK_ARMV7M:
809     return MachO::CPU_SUBTYPE_ARM_V7M;
810   case ARM::AK_ARMV7EM:
811     return MachO::CPU_SUBTYPE_ARM_V7EM;
812   }
813 }
814
815 MCAsmBackend *llvm::createARMAsmBackend(const Target &T,
816                                         const MCRegisterInfo &MRI,
817                                         const Triple &TheTriple, StringRef CPU,
818                                         bool isLittle) {
819   switch (TheTriple.getObjectFormat()) {
820   default:
821     llvm_unreachable("unsupported object format");
822   case Triple::MachO: {
823     MachO::CPUSubTypeARM CS = getMachOSubTypeFromArch(TheTriple.getArchName());
824     return new ARMAsmBackendDarwin(T, TheTriple, CS);
825   }
826   case Triple::COFF:
827     assert(TheTriple.isOSWindows() && "non-Windows ARM COFF is not supported");
828     return new ARMAsmBackendWinCOFF(T, TheTriple);
829   case Triple::ELF:
830     assert(TheTriple.isOSBinFormatELF() && "using ELF for non-ELF target");
831     uint8_t OSABI = MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
832     return new ARMAsmBackendELF(T, TheTriple, OSABI, isLittle);
833   }
834 }
835
836 MCAsmBackend *llvm::createARMLEAsmBackend(const Target &T,
837                                           const MCRegisterInfo &MRI,
838                                           const Triple &TT, StringRef CPU) {
839   return createARMAsmBackend(T, MRI, TT, CPU, true);
840 }
841
842 MCAsmBackend *llvm::createARMBEAsmBackend(const Target &T,
843                                           const MCRegisterInfo &MRI,
844                                           const Triple &TT, StringRef CPU) {
845   return createARMAsmBackend(T, MRI, TT, CPU, false);
846 }
847
848 MCAsmBackend *llvm::createThumbLEAsmBackend(const Target &T,
849                                             const MCRegisterInfo &MRI,
850                                             const Triple &TT, StringRef CPU) {
851   return createARMAsmBackend(T, MRI, TT, CPU, true);
852 }
853
854 MCAsmBackend *llvm::createThumbBEAsmBackend(const Target &T,
855                                             const MCRegisterInfo &MRI,
856                                             const Triple &TT, StringRef CPU) {
857   return createARMAsmBackend(T, MRI, TT, CPU, false);
858 }