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