Rename TargetAsmBackend to MCAsmBackend; rename createAsmBackend to createMCAsmBackend.
[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/ARMBaseInfo.h"
11 #include "MCTargetDesc/ARMFixupKinds.h"
12 #include "MCTargetDesc/ARMAddressingModes.h"
13 #include "llvm/ADT/Twine.h"
14 #include "llvm/MC/MCAssembler.h"
15 #include "llvm/MC/MCDirectives.h"
16 #include "llvm/MC/MCELFObjectWriter.h"
17 #include "llvm/MC/MCExpr.h"
18 #include "llvm/MC/MCMachObjectWriter.h"
19 #include "llvm/MC/MCObjectWriter.h"
20 #include "llvm/MC/MCSectionELF.h"
21 #include "llvm/MC/MCSectionMachO.h"
22 #include "llvm/MC/MCAsmBackend.h"
23 #include "llvm/Object/MachOFormat.h"
24 #include "llvm/Support/ELF.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
27 using namespace llvm;
28
29 namespace {
30 class ARMELFObjectWriter : public MCELFObjectTargetWriter {
31 public:
32   ARMELFObjectWriter(Triple::OSType OSType)
33     : MCELFObjectTargetWriter(/*Is64Bit*/ false, OSType, ELF::EM_ARM,
34                               /*HasRelocationAddend*/ false) {}
35 };
36
37 class ARMAsmBackend : public MCAsmBackend {
38   bool isThumbMode;  // Currently emitting Thumb code.
39 public:
40   ARMAsmBackend(const Target &T) : MCAsmBackend(), isThumbMode(false) {}
41
42   unsigned getNumFixupKinds() const { return ARM::NumTargetFixupKinds; }
43
44   const MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const {
45     const static MCFixupKindInfo Infos[ARM::NumTargetFixupKinds] = {
46 // This table *must* be in the order that the fixup_* kinds are defined in
47 // ARMFixupKinds.h.
48 //
49 // Name                      Offset (bits) Size (bits)     Flags
50 { "fixup_arm_ldst_pcrel_12", 1,            24,  MCFixupKindInfo::FKF_IsPCRel },
51 { "fixup_t2_ldst_pcrel_12",  0,            32,  MCFixupKindInfo::FKF_IsPCRel |
52                                    MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
53 { "fixup_arm_pcrel_10",      1,            24,  MCFixupKindInfo::FKF_IsPCRel },
54 { "fixup_t2_pcrel_10",       0,            32,  MCFixupKindInfo::FKF_IsPCRel |
55                                    MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
56 { "fixup_thumb_adr_pcrel_10",0,            8,   MCFixupKindInfo::FKF_IsPCRel |
57                                    MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
58 { "fixup_arm_adr_pcrel_12",  1,            24,  MCFixupKindInfo::FKF_IsPCRel },
59 { "fixup_t2_adr_pcrel_12",   0,            32,  MCFixupKindInfo::FKF_IsPCRel |
60                                    MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
61 { "fixup_arm_condbranch",    0,            24,  MCFixupKindInfo::FKF_IsPCRel },
62 { "fixup_arm_uncondbranch",  0,            24,  MCFixupKindInfo::FKF_IsPCRel },
63 { "fixup_t2_condbranch",     0,            32,  MCFixupKindInfo::FKF_IsPCRel },
64 { "fixup_t2_uncondbranch",   0,            32,  MCFixupKindInfo::FKF_IsPCRel },
65 { "fixup_arm_thumb_br",      0,            16,  MCFixupKindInfo::FKF_IsPCRel },
66 { "fixup_arm_thumb_bl",      0,            32,  MCFixupKindInfo::FKF_IsPCRel },
67 { "fixup_arm_thumb_blx",     7,            21,  MCFixupKindInfo::FKF_IsPCRel },
68 { "fixup_arm_thumb_cb",      0,            16,  MCFixupKindInfo::FKF_IsPCRel },
69 { "fixup_arm_thumb_cp",      1,             8,  MCFixupKindInfo::FKF_IsPCRel },
70 { "fixup_arm_thumb_bcc",     0,             8,  MCFixupKindInfo::FKF_IsPCRel },
71 // movw / movt: 16-bits immediate but scattered into two chunks 0 - 12, 16 - 19.
72 { "fixup_arm_movt_hi16",     0,            20,  0 },
73 { "fixup_arm_movw_lo16",     0,            20,  0 },
74 { "fixup_t2_movt_hi16",      0,            20,  0 },
75 { "fixup_t2_movw_lo16",      0,            20,  0 },
76 { "fixup_arm_movt_hi16_pcrel", 0,          20,  MCFixupKindInfo::FKF_IsPCRel },
77 { "fixup_arm_movw_lo16_pcrel", 0,          20,  MCFixupKindInfo::FKF_IsPCRel },
78 { "fixup_t2_movt_hi16_pcrel", 0,           20,  MCFixupKindInfo::FKF_IsPCRel },
79 { "fixup_t2_movw_lo16_pcrel", 0,           20,  MCFixupKindInfo::FKF_IsPCRel },
80     };
81
82     if (Kind < FirstTargetFixupKind)
83       return MCAsmBackend::getFixupKindInfo(Kind);
84
85     assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
86            "Invalid kind!");
87     return Infos[Kind - FirstTargetFixupKind];
88   }
89
90   bool MayNeedRelaxation(const MCInst &Inst) const;
91
92   void RelaxInstruction(const MCInst &Inst, MCInst &Res) const;
93
94   bool WriteNopData(uint64_t Count, MCObjectWriter *OW) const;
95
96   void HandleAssemblerFlag(MCAssemblerFlag Flag) {
97     switch (Flag) {
98     default: break;
99     case MCAF_Code16:
100       setIsThumb(true);
101       break;
102     case MCAF_Code32:
103       setIsThumb(false);
104       break;
105     }
106   }
107
108   unsigned getPointerSize() const { return 4; }
109   bool isThumb() const { return isThumbMode; }
110   void setIsThumb(bool it) { isThumbMode = it; }
111 };
112 } // end anonymous namespace
113
114 bool ARMAsmBackend::MayNeedRelaxation(const MCInst &Inst) const {
115   // FIXME: Thumb targets, different move constant targets..
116   return false;
117 }
118
119 void ARMAsmBackend::RelaxInstruction(const MCInst &Inst, MCInst &Res) const {
120   assert(0 && "ARMAsmBackend::RelaxInstruction() unimplemented");
121   return;
122 }
123
124 bool ARMAsmBackend::WriteNopData(uint64_t Count, MCObjectWriter *OW) const {
125   if (isThumb()) {
126     // FIXME: 0xbf00 is the ARMv7 value. For v6 and before, we'll need to
127     // use 0x46c0 (which is a 'mov r8, r8' insn).
128     uint64_t NumNops = Count / 2;
129     for (uint64_t i = 0; i != NumNops; ++i)
130       OW->Write16(0xbf00);
131     if (Count & 1)
132       OW->Write8(0);
133     return true;
134   }
135   // ARM mode
136   uint64_t NumNops = Count / 4;
137   for (uint64_t i = 0; i != NumNops; ++i)
138     OW->Write32(0xe1a00000);
139   switch (Count % 4) {
140   default: break; // No leftover bytes to write
141   case 1: OW->Write8(0); break;
142   case 2: OW->Write16(0); break;
143   case 3: OW->Write16(0); OW->Write8(0xa0); break;
144   }
145
146   return true;
147 }
148
149 static unsigned adjustFixupValue(unsigned Kind, uint64_t Value) {
150   switch (Kind) {
151   default:
152     llvm_unreachable("Unknown fixup kind!");
153   case FK_Data_1:
154   case FK_Data_2:
155   case FK_Data_4:
156     return Value;
157   case ARM::fixup_arm_movt_hi16:
158     Value >>= 16;
159     // Fallthrough
160   case ARM::fixup_arm_movw_lo16:
161   case ARM::fixup_arm_movt_hi16_pcrel:
162   case ARM::fixup_arm_movw_lo16_pcrel: {
163     unsigned Hi4 = (Value & 0xF000) >> 12;
164     unsigned Lo12 = Value & 0x0FFF;
165     assert ((((int64_t)Value) >= -0x8000) && (((int64_t)Value) <= 0x7fff) &&
166             "Out of range pc-relative fixup value!");
167     // inst{19-16} = Hi4;
168     // inst{11-0} = Lo12;
169     Value = (Hi4 << 16) | (Lo12);
170     return Value;
171   }
172   case ARM::fixup_t2_movt_hi16:
173     Value >>= 16;
174     // Fallthrough
175   case ARM::fixup_t2_movw_lo16:
176   case ARM::fixup_t2_movt_hi16_pcrel:  //FIXME: Shouldn't this be shifted like
177                                        // the other hi16 fixup?
178   case ARM::fixup_t2_movw_lo16_pcrel: {
179     unsigned Hi4 = (Value & 0xF000) >> 12;
180     unsigned i = (Value & 0x800) >> 11;
181     unsigned Mid3 = (Value & 0x700) >> 8;
182     unsigned Lo8 = Value & 0x0FF;
183     // inst{19-16} = Hi4;
184     // inst{26} = i;
185     // inst{14-12} = Mid3;
186     // inst{7-0} = Lo8;
187     // The value comes in as the whole thing, not just the portion required
188     // for this fixup, so we need to mask off the bits not handled by this
189     // portion (lo vs. hi).
190     Value &= 0xffff;
191     Value = (Hi4 << 16) | (i << 26) | (Mid3 << 12) | (Lo8);
192     uint64_t swapped = (Value & 0xFFFF0000) >> 16;
193     swapped |= (Value & 0x0000FFFF) << 16;
194     return swapped;
195   }
196   case ARM::fixup_arm_ldst_pcrel_12:
197     // ARM PC-relative values are offset by 8.
198     Value -= 4;
199     // FALLTHROUGH
200   case ARM::fixup_t2_ldst_pcrel_12: {
201     // Offset by 4, adjusted by two due to the half-word ordering of thumb.
202     Value -= 4;
203     bool isAdd = true;
204     if ((int64_t)Value < 0) {
205       Value = -Value;
206       isAdd = false;
207     }
208     assert ((Value < 4096) && "Out of range pc-relative fixup value!");
209     Value |= isAdd << 23;
210
211     // Same addressing mode as fixup_arm_pcrel_10,
212     // but with 16-bit halfwords swapped.
213     if (Kind == ARM::fixup_t2_ldst_pcrel_12) {
214       uint64_t swapped = (Value & 0xFFFF0000) >> 16;
215       swapped |= (Value & 0x0000FFFF) << 16;
216       return swapped;
217     }
218
219     return Value;
220   }
221   case ARM::fixup_thumb_adr_pcrel_10:
222     return ((Value - 4) >> 2) & 0xff;
223   case ARM::fixup_arm_adr_pcrel_12: {
224     // ARM PC-relative values are offset by 8.
225     Value -= 8;
226     unsigned opc = 4; // bits {24-21}. Default to add: 0b0100
227     if ((int64_t)Value < 0) {
228       Value = -Value;
229       opc = 2; // 0b0010
230     }
231     assert(ARM_AM::getSOImmVal(Value) != -1 &&
232            "Out of range pc-relative fixup value!");
233     // Encode the immediate and shift the opcode into place.
234     return ARM_AM::getSOImmVal(Value) | (opc << 21);
235   }
236
237   case ARM::fixup_t2_adr_pcrel_12: {
238     Value -= 4;
239     unsigned opc = 0;
240     if ((int64_t)Value < 0) {
241       Value = -Value;
242       opc = 5;
243     }
244
245     uint32_t out = (opc << 21);
246     out |= (Value & 0x800) << 15;
247     out |= (Value & 0x700) << 4;
248     out |= (Value & 0x0FF);
249
250     uint64_t swapped = (out & 0xFFFF0000) >> 16;
251     swapped |= (out & 0x0000FFFF) << 16;
252     return swapped;
253   }
254
255   case ARM::fixup_arm_condbranch:
256   case ARM::fixup_arm_uncondbranch:
257     // These values don't encode the low two bits since they're always zero.
258     // Offset by 8 just as above.
259     return 0xffffff & ((Value - 8) >> 2);
260   case ARM::fixup_t2_uncondbranch: {
261     Value = Value - 4;
262     Value >>= 1; // Low bit is not encoded.
263
264     uint32_t out = 0;
265     bool I =  Value & 0x800000;
266     bool J1 = Value & 0x400000;
267     bool J2 = Value & 0x200000;
268     J1 ^= I;
269     J2 ^= I;
270
271     out |= I  << 26; // S bit
272     out |= !J1 << 13; // J1 bit
273     out |= !J2 << 11; // J2 bit
274     out |= (Value & 0x1FF800)  << 5; // imm6 field
275     out |= (Value & 0x0007FF);        // imm11 field
276
277     uint64_t swapped = (out & 0xFFFF0000) >> 16;
278     swapped |= (out & 0x0000FFFF) << 16;
279     return swapped;
280   }
281   case ARM::fixup_t2_condbranch: {
282     Value = Value - 4;
283     Value >>= 1; // Low bit is not encoded.
284
285     uint64_t out = 0;
286     out |= (Value & 0x80000) << 7; // S bit
287     out |= (Value & 0x40000) >> 7; // J2 bit
288     out |= (Value & 0x20000) >> 4; // J1 bit
289     out |= (Value & 0x1F800) << 5; // imm6 field
290     out |= (Value & 0x007FF);      // imm11 field
291
292     uint32_t swapped = (out & 0xFFFF0000) >> 16;
293     swapped |= (out & 0x0000FFFF) << 16;
294     return swapped;
295   }
296   case ARM::fixup_arm_thumb_bl: {
297     // The value doesn't encode the low bit (always zero) and is offset by
298     // four. The value is encoded into disjoint bit positions in the destination
299     // opcode. x = unchanged, I = immediate value bit, S = sign extension bit
300     //
301     //   BL:  xxxxxSIIIIIIIIII xxxxxIIIIIIIIIII
302     //
303     // Note that the halfwords are stored high first, low second; so we need
304     // to transpose the fixup value here to map properly.
305     unsigned isNeg = (int64_t(Value - 4) < 0) ? 1 : 0;
306     uint32_t Binary = 0;
307     Value = 0x3fffff & ((Value - 4) >> 1);
308     Binary  = (Value & 0x7ff) << 16;    // Low imm11 value.
309     Binary |= (Value & 0x1ffc00) >> 11; // High imm10 value.
310     Binary |= isNeg << 10;              // Sign bit.
311     return Binary;
312   }
313   case ARM::fixup_arm_thumb_blx: {
314     // The value doesn't encode the low two bits (always zero) and is offset by
315     // four (see fixup_arm_thumb_cp). The value is encoded into disjoint bit
316     // positions in the destination opcode. x = unchanged, I = immediate value
317     // bit, S = sign extension bit, 0 = zero.
318     //
319     //   BLX: xxxxxSIIIIIIIIII xxxxxIIIIIIIIII0
320     //
321     // Note that the halfwords are stored high first, low second; so we need
322     // to transpose the fixup value here to map properly.
323     unsigned isNeg = (int64_t(Value-4) < 0) ? 1 : 0;
324     uint32_t Binary = 0;
325     Value = 0xfffff & ((Value - 2) >> 2);
326     Binary  = (Value & 0x3ff) << 17;    // Low imm10L value.
327     Binary |= (Value & 0xffc00) >> 10;  // High imm10H value.
328     Binary |= isNeg << 10;              // Sign bit.
329     return Binary;
330   }
331   case ARM::fixup_arm_thumb_cp:
332     // Offset by 4, and don't encode the low two bits. Two bytes of that
333     // 'off by 4' is implicitly handled by the half-word ordering of the
334     // Thumb encoding, so we only need to adjust by 2 here.
335     return ((Value - 2) >> 2) & 0xff;
336   case ARM::fixup_arm_thumb_cb: {
337     // Offset by 4 and don't encode the lower bit, which is always 0.
338     uint32_t Binary = (Value - 4) >> 1;
339     return ((Binary & 0x20) << 4) | ((Binary & 0x1f) << 3);
340   }
341   case ARM::fixup_arm_thumb_br:
342     // Offset by 4 and don't encode the lower bit, which is always 0.
343     return ((Value - 4) >> 1) & 0x7ff;
344   case ARM::fixup_arm_thumb_bcc:
345     // Offset by 4 and don't encode the lower bit, which is always 0.
346     return ((Value - 4) >> 1) & 0xff;
347   case ARM::fixup_arm_pcrel_10:
348     Value = Value - 4; // ARM fixups offset by an additional word and don't
349                        // need to adjust for the half-word ordering.
350     // Fall through.
351   case ARM::fixup_t2_pcrel_10: {
352     // Offset by 4, adjusted by two due to the half-word ordering of thumb.
353     Value = Value - 4;
354     bool isAdd = true;
355     if ((int64_t)Value < 0) {
356       Value = -Value;
357       isAdd = false;
358     }
359     // These values don't encode the low two bits since they're always zero.
360     Value >>= 2;
361     assert ((Value < 256) && "Out of range pc-relative fixup value!");
362     Value |= isAdd << 23;
363
364     // Same addressing mode as fixup_arm_pcrel_10,
365     // but with 16-bit halfwords swapped.
366     if (Kind == ARM::fixup_t2_pcrel_10) {
367       uint32_t swapped = (Value & 0xFFFF0000) >> 16;
368       swapped |= (Value & 0x0000FFFF) << 16;
369       return swapped;
370     }
371
372     return Value;
373   }
374   }
375 }
376
377 namespace {
378
379 // FIXME: This should be in a separate file.
380 // ELF is an ELF of course...
381 class ELFARMAsmBackend : public ARMAsmBackend {
382 public:
383   Triple::OSType OSType;
384   ELFARMAsmBackend(const Target &T, Triple::OSType _OSType)
385     : ARMAsmBackend(T), OSType(_OSType) { }
386
387   void ApplyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize,
388                   uint64_t Value) const;
389
390   MCObjectWriter *createObjectWriter(raw_ostream &OS) const {
391     return createELFObjectWriter(new ARMELFObjectWriter(OSType), OS,
392                               /*IsLittleEndian*/ true);
393   }
394 };
395
396 // FIXME: Raise this to share code between Darwin and ELF.
397 void ELFARMAsmBackend::ApplyFixup(const MCFixup &Fixup, char *Data,
398                                   unsigned DataSize, uint64_t Value) const {
399   unsigned NumBytes = 4;        // FIXME: 2 for Thumb
400   Value = adjustFixupValue(Fixup.getKind(), Value);
401   if (!Value) return;           // Doesn't change encoding.
402
403   unsigned Offset = Fixup.getOffset();
404
405   // For each byte of the fragment that the fixup touches, mask in the bits from
406   // the fixup value. The Value has been "split up" into the appropriate
407   // bitfields above.
408   for (unsigned i = 0; i != NumBytes; ++i)
409     Data[Offset + i] |= uint8_t((Value >> (i * 8)) & 0xff);
410 }
411
412 // FIXME: This should be in a separate file.
413 class DarwinARMAsmBackend : public ARMAsmBackend {
414 public:
415   const object::mach::CPUSubtypeARM Subtype;
416   DarwinARMAsmBackend(const Target &T, object::mach::CPUSubtypeARM st)
417     : ARMAsmBackend(T), Subtype(st) { }
418
419   MCObjectWriter *createObjectWriter(raw_ostream &OS) const {
420     return createARMMachObjectWriter(OS, /*Is64Bit=*/false,
421                                      object::mach::CTM_ARM,
422                                      Subtype);
423   }
424
425   void ApplyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize,
426                   uint64_t Value) const;
427
428   virtual bool doesSectionRequireSymbols(const MCSection &Section) const {
429     return false;
430   }
431 };
432
433 /// getFixupKindNumBytes - The number of bytes the fixup may change.
434 static unsigned getFixupKindNumBytes(unsigned Kind) {
435   switch (Kind) {
436   default:
437     llvm_unreachable("Unknown fixup kind!");
438
439   case FK_Data_1:
440   case ARM::fixup_arm_thumb_bcc:
441   case ARM::fixup_arm_thumb_cp:
442   case ARM::fixup_thumb_adr_pcrel_10:
443     return 1;
444
445   case FK_Data_2:
446   case ARM::fixup_arm_thumb_br:
447   case ARM::fixup_arm_thumb_cb:
448     return 2;
449
450   case ARM::fixup_arm_ldst_pcrel_12:
451   case ARM::fixup_arm_pcrel_10:
452   case ARM::fixup_arm_adr_pcrel_12:
453   case ARM::fixup_arm_condbranch:
454   case ARM::fixup_arm_uncondbranch:
455     return 3;
456
457   case FK_Data_4:
458   case ARM::fixup_t2_ldst_pcrel_12:
459   case ARM::fixup_t2_condbranch:
460   case ARM::fixup_t2_uncondbranch:
461   case ARM::fixup_t2_pcrel_10:
462   case ARM::fixup_t2_adr_pcrel_12:
463   case ARM::fixup_arm_thumb_bl:
464   case ARM::fixup_arm_thumb_blx:
465   case ARM::fixup_arm_movt_hi16:
466   case ARM::fixup_arm_movw_lo16:
467   case ARM::fixup_arm_movt_hi16_pcrel:
468   case ARM::fixup_arm_movw_lo16_pcrel:
469   case ARM::fixup_t2_movt_hi16:
470   case ARM::fixup_t2_movw_lo16:
471   case ARM::fixup_t2_movt_hi16_pcrel:
472   case ARM::fixup_t2_movw_lo16_pcrel:
473     return 4;
474   }
475 }
476
477 void DarwinARMAsmBackend::ApplyFixup(const MCFixup &Fixup, char *Data,
478                                      unsigned DataSize, uint64_t Value) const {
479   unsigned NumBytes = getFixupKindNumBytes(Fixup.getKind());
480   Value = adjustFixupValue(Fixup.getKind(), Value);
481   if (!Value) return;           // Doesn't change encoding.
482
483   unsigned Offset = Fixup.getOffset();
484   assert(Offset + NumBytes <= DataSize && "Invalid fixup offset!");
485
486   // For each byte of the fragment that the fixup touches, mask in the
487   // bits from the fixup value.
488   for (unsigned i = 0; i != NumBytes; ++i)
489     Data[Offset + i] |= uint8_t((Value >> (i * 8)) & 0xff);
490 }
491
492 } // end anonymous namespace
493
494 MCAsmBackend *llvm::createARMAsmBackend(const Target &T, StringRef TT) {
495   Triple TheTriple(TT);
496
497   if (TheTriple.isOSDarwin()) {
498     if (TheTriple.getArchName() == "armv4t" ||
499         TheTriple.getArchName() == "thumbv4t")
500       return new DarwinARMAsmBackend(T, object::mach::CSARM_V4T);
501     else if (TheTriple.getArchName() == "armv5e" ||
502         TheTriple.getArchName() == "thumbv5e")
503       return new DarwinARMAsmBackend(T, object::mach::CSARM_V5TEJ);
504     else if (TheTriple.getArchName() == "armv6" ||
505         TheTriple.getArchName() == "thumbv6")
506       return new DarwinARMAsmBackend(T, object::mach::CSARM_V6);
507     return new DarwinARMAsmBackend(T, object::mach::CSARM_V7);
508   }
509
510   if (TheTriple.isOSWindows())
511     assert(0 && "Windows not supported on ARM");
512
513   return new ELFARMAsmBackend(T, Triple(TT).getOS());
514 }