MC: Clean up naming in MCObjectWriter. NFC.
[oota-llvm.git] / lib / Target / ARM / MCTargetDesc / ARMMachObjectWriter.cpp
1 //===-- ARMMachObjectWriter.cpp - ARM Mach Object Writer ------------------===//
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/ARMBaseInfo.h"
12 #include "MCTargetDesc/ARMFixupKinds.h"
13 #include "llvm/ADT/Twine.h"
14 #include "llvm/MC/MCAsmLayout.h"
15 #include "llvm/MC/MCAssembler.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCExpr.h"
18 #include "llvm/MC/MCFixup.h"
19 #include "llvm/MC/MCFixupKindInfo.h"
20 #include "llvm/MC/MCMachOSymbolFlags.h"
21 #include "llvm/MC/MCMachObjectWriter.h"
22 #include "llvm/MC/MCSection.h"
23 #include "llvm/MC/MCValue.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/MachO.h"
26 using namespace llvm;
27
28 namespace {
29 class ARMMachObjectWriter : public MCMachObjectTargetWriter {
30   void RecordARMScatteredRelocation(MachObjectWriter *Writer,
31                                     const MCAssembler &Asm,
32                                     const MCAsmLayout &Layout,
33                                     const MCFragment *Fragment,
34                                     const MCFixup &Fixup,
35                                     MCValue Target,
36                                     unsigned Type,
37                                     unsigned Log2Size,
38                                     uint64_t &FixedValue);
39   void RecordARMScatteredHalfRelocation(MachObjectWriter *Writer,
40                                         const MCAssembler &Asm,
41                                         const MCAsmLayout &Layout,
42                                         const MCFragment *Fragment,
43                                         const MCFixup &Fixup, MCValue Target,
44                                         uint64_t &FixedValue);
45
46   bool requiresExternRelocation(MachObjectWriter *Writer,
47                                 const MCAssembler &Asm,
48                                 const MCFragment &Fragment, unsigned RelocType,
49                                 const MCSymbol &S, uint64_t FixedValue);
50
51 public:
52   ARMMachObjectWriter(bool Is64Bit, uint32_t CPUType, uint32_t CPUSubtype)
53       : MCMachObjectTargetWriter(Is64Bit, CPUType, CPUSubtype) {}
54
55   void recordRelocation(MachObjectWriter *Writer, MCAssembler &Asm,
56                         const MCAsmLayout &Layout, const MCFragment *Fragment,
57                         const MCFixup &Fixup, MCValue Target,
58                         uint64_t &FixedValue) override;
59 };
60 }
61
62 static bool getARMFixupKindMachOInfo(unsigned Kind, unsigned &RelocType,
63                               unsigned &Log2Size) {
64   RelocType = unsigned(MachO::ARM_RELOC_VANILLA);
65   Log2Size = ~0U;
66
67   switch (Kind) {
68   default:
69     return false;
70
71   case FK_Data_1:
72     Log2Size = llvm::Log2_32(1);
73     return true;
74   case FK_Data_2:
75     Log2Size = llvm::Log2_32(2);
76     return true;
77   case FK_Data_4:
78     Log2Size = llvm::Log2_32(4);
79     return true;
80   case FK_Data_8:
81     Log2Size = llvm::Log2_32(8);
82     return true;
83
84     // These fixups are expected to always be resolvable at assembly time and
85     // have no relocations supported.
86   case ARM::fixup_arm_ldst_pcrel_12:
87   case ARM::fixup_arm_pcrel_10:
88   case ARM::fixup_arm_adr_pcrel_12:
89   case ARM::fixup_arm_thumb_br:
90     return false;
91
92     // Handle 24-bit branch kinds.
93   case ARM::fixup_arm_condbranch:
94   case ARM::fixup_arm_uncondbranch:
95   case ARM::fixup_arm_uncondbl:
96   case ARM::fixup_arm_condbl:
97   case ARM::fixup_arm_blx:
98     RelocType = unsigned(MachO::ARM_RELOC_BR24);
99     // Report as 'long', even though that is not quite accurate.
100     Log2Size = llvm::Log2_32(4);
101     return true;
102
103   case ARM::fixup_t2_uncondbranch:
104   case ARM::fixup_arm_thumb_bl:
105   case ARM::fixup_arm_thumb_blx:
106     RelocType = unsigned(MachO::ARM_THUMB_RELOC_BR22);
107     Log2Size = llvm::Log2_32(4);
108     return true;
109
110   // For movw/movt r_type relocations they always have a pair following them and
111   // the r_length bits are used differently.  The encoding of the r_length is as
112   // follows:
113   //   low bit of r_length:
114   //      0 - :lower16: for movw instructions
115   //      1 - :upper16: for movt instructions
116   //   high bit of r_length:
117   //      0 - arm instructions
118   //      1 - thumb instructions
119   case ARM::fixup_arm_movt_hi16:
120     RelocType = unsigned(MachO::ARM_RELOC_HALF);
121     Log2Size = 1;
122     return true;
123   case ARM::fixup_t2_movt_hi16:
124     RelocType = unsigned(MachO::ARM_RELOC_HALF);
125     Log2Size = 3;
126     return true;
127
128   case ARM::fixup_arm_movw_lo16:
129     RelocType = unsigned(MachO::ARM_RELOC_HALF);
130     Log2Size = 0;
131     return true;
132   case ARM::fixup_t2_movw_lo16:
133     RelocType = unsigned(MachO::ARM_RELOC_HALF);
134     Log2Size = 2;
135     return true;
136   }
137 }
138
139 void ARMMachObjectWriter::
140 RecordARMScatteredHalfRelocation(MachObjectWriter *Writer,
141                                  const MCAssembler &Asm,
142                                  const MCAsmLayout &Layout,
143                                  const MCFragment *Fragment,
144                                  const MCFixup &Fixup,
145                                  MCValue Target,
146                                  uint64_t &FixedValue) {
147   uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
148   unsigned IsPCRel = Writer->isFixupKindPCRel(Asm, Fixup.getKind());
149   unsigned Type = MachO::ARM_RELOC_HALF;
150
151   // See <reloc.h>.
152   const MCSymbol *A = &Target.getSymA()->getSymbol();
153
154   if (!A->getFragment())
155     Asm.getContext().reportFatalError(Fixup.getLoc(),
156                        "symbol '" + A->getName() +
157                        "' can not be undefined in a subtraction expression");
158
159   uint32_t Value = Writer->getSymbolAddress(*A, Layout);
160   uint32_t Value2 = 0;
161   uint64_t SecAddr = Writer->getSectionAddress(A->getFragment()->getParent());
162   FixedValue += SecAddr;
163
164   if (const MCSymbolRefExpr *B = Target.getSymB()) {
165     const MCSymbol *SB = &B->getSymbol();
166
167     if (!SB->getFragment())
168       Asm.getContext().reportFatalError(Fixup.getLoc(),
169                          "symbol '" + B->getSymbol().getName() +
170                          "' can not be undefined in a subtraction expression");
171
172     // Select the appropriate difference relocation type.
173     Type = MachO::ARM_RELOC_HALF_SECTDIFF;
174     Value2 = Writer->getSymbolAddress(B->getSymbol(), Layout);
175     FixedValue -= Writer->getSectionAddress(SB->getFragment()->getParent());
176   }
177
178   // Relocations are written out in reverse order, so the PAIR comes first.
179   // ARM_RELOC_HALF and ARM_RELOC_HALF_SECTDIFF abuse the r_length field:
180   //
181   // For these two r_type relocations they always have a pair following them and
182   // the r_length bits are used differently.  The encoding of the r_length is as
183   // follows:
184   //   low bit of r_length:
185   //      0 - :lower16: for movw instructions
186   //      1 - :upper16: for movt instructions
187   //   high bit of r_length:
188   //      0 - arm instructions
189   //      1 - thumb instructions
190   // the other half of the relocated expression is in the following pair
191   // relocation entry in the low 16 bits of r_address field.
192   unsigned ThumbBit = 0;
193   unsigned MovtBit = 0;
194   switch ((unsigned)Fixup.getKind()) {
195   default: break;
196   case ARM::fixup_arm_movt_hi16:
197     MovtBit = 1;
198     // The thumb bit shouldn't be set in the 'other-half' bit of the
199     // relocation, but it will be set in FixedValue if the base symbol
200     // is a thumb function. Clear it out here.
201     if (Asm.isThumbFunc(A))
202       FixedValue &= 0xfffffffe;
203     break;
204   case ARM::fixup_t2_movt_hi16:
205     if (Asm.isThumbFunc(A))
206       FixedValue &= 0xfffffffe;
207     MovtBit = 1;
208     // Fallthrough
209   case ARM::fixup_t2_movw_lo16:
210     ThumbBit = 1;
211     break;
212   }
213
214   if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
215     uint32_t OtherHalf = MovtBit
216       ? (FixedValue & 0xffff) : ((FixedValue & 0xffff0000) >> 16);
217
218     MachO::any_relocation_info MRE;
219     MRE.r_word0 = ((OtherHalf             <<  0) |
220                    (MachO::ARM_RELOC_PAIR << 24) |
221                    (MovtBit               << 28) |
222                    (ThumbBit              << 29) |
223                    (IsPCRel               << 30) |
224                    MachO::R_SCATTERED);
225     MRE.r_word1 = Value2;
226     Writer->addRelocation(nullptr, Fragment->getParent(), MRE);
227   }
228
229   MachO::any_relocation_info MRE;
230   MRE.r_word0 = ((FixupOffset <<  0) |
231                  (Type        << 24) |
232                  (MovtBit     << 28) |
233                  (ThumbBit    << 29) |
234                  (IsPCRel     << 30) |
235                  MachO::R_SCATTERED);
236   MRE.r_word1 = Value;
237   Writer->addRelocation(nullptr, Fragment->getParent(), MRE);
238 }
239
240 void ARMMachObjectWriter::RecordARMScatteredRelocation(MachObjectWriter *Writer,
241                                                     const MCAssembler &Asm,
242                                                     const MCAsmLayout &Layout,
243                                                     const MCFragment *Fragment,
244                                                     const MCFixup &Fixup,
245                                                     MCValue Target,
246                                                     unsigned Type,
247                                                     unsigned Log2Size,
248                                                     uint64_t &FixedValue) {
249   uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
250   unsigned IsPCRel = Writer->isFixupKindPCRel(Asm, Fixup.getKind());
251
252   // See <reloc.h>.
253   const MCSymbol *A = &Target.getSymA()->getSymbol();
254
255   if (!A->getFragment())
256     Asm.getContext().reportFatalError(Fixup.getLoc(),
257                        "symbol '" + A->getName() +
258                        "' can not be undefined in a subtraction expression");
259
260   uint32_t Value = Writer->getSymbolAddress(*A, Layout);
261   uint64_t SecAddr = Writer->getSectionAddress(A->getFragment()->getParent());
262   FixedValue += SecAddr;
263   uint32_t Value2 = 0;
264
265   if (const MCSymbolRefExpr *B = Target.getSymB()) {
266     assert(Type == MachO::ARM_RELOC_VANILLA && "invalid reloc for 2 symbols");
267     const MCSymbol *SB = &B->getSymbol();
268
269     if (!SB->getFragment())
270       Asm.getContext().reportFatalError(Fixup.getLoc(),
271                          "symbol '" + B->getSymbol().getName() +
272                          "' can not be undefined in a subtraction expression");
273
274     // Select the appropriate difference relocation type.
275     Type = MachO::ARM_RELOC_SECTDIFF;
276     Value2 = Writer->getSymbolAddress(B->getSymbol(), Layout);
277     FixedValue -= Writer->getSectionAddress(SB->getFragment()->getParent());
278   }
279
280   // Relocations are written out in reverse order, so the PAIR comes first.
281   if (Type == MachO::ARM_RELOC_SECTDIFF ||
282       Type == MachO::ARM_RELOC_LOCAL_SECTDIFF) {
283     MachO::any_relocation_info MRE;
284     MRE.r_word0 = ((0                     <<  0) |
285                    (MachO::ARM_RELOC_PAIR << 24) |
286                    (Log2Size              << 28) |
287                    (IsPCRel               << 30) |
288                    MachO::R_SCATTERED);
289     MRE.r_word1 = Value2;
290     Writer->addRelocation(nullptr, Fragment->getParent(), MRE);
291   }
292
293   MachO::any_relocation_info MRE;
294   MRE.r_word0 = ((FixupOffset <<  0) |
295                  (Type        << 24) |
296                  (Log2Size    << 28) |
297                  (IsPCRel     << 30) |
298                  MachO::R_SCATTERED);
299   MRE.r_word1 = Value;
300   Writer->addRelocation(nullptr, Fragment->getParent(), MRE);
301 }
302
303 bool ARMMachObjectWriter::requiresExternRelocation(MachObjectWriter *Writer,
304                                                    const MCAssembler &Asm,
305                                                    const MCFragment &Fragment,
306                                                    unsigned RelocType,
307                                                    const MCSymbol &S,
308                                                    uint64_t FixedValue) {
309   // Most cases can be identified purely from the symbol.
310   if (Writer->doesSymbolRequireExternRelocation(S))
311     return true;
312   int64_t Value = (int64_t)FixedValue;  // The displacement is signed.
313   int64_t Range;
314   switch (RelocType) {
315   default:
316     return false;
317   case MachO::ARM_RELOC_BR24:
318     // PC pre-adjustment of 8 for these instructions.
319     Value -= 8;
320     // ARM BL/BLX has a 25-bit offset.
321     Range = 0x1ffffff;
322     break;
323   case MachO::ARM_THUMB_RELOC_BR22:
324     // PC pre-adjustment of 4 for these instructions.
325     Value -= 4;
326     // Thumb BL/BLX has a 24-bit offset.
327     Range = 0xffffff;
328   }
329   // BL/BLX also use external relocations when an internal relocation
330   // would result in the target being out of range. This gives the linker
331   // enough information to generate a branch island.
332   Value += Writer->getSectionAddress(&S.getSection());
333   Value -= Writer->getSectionAddress(Fragment.getParent());
334   // If the resultant value would be out of range for an internal relocation,
335   // use an external instead.
336   if (Value > Range || Value < -(Range + 1))
337     return true;
338   return false;
339 }
340
341 void ARMMachObjectWriter::recordRelocation(MachObjectWriter *Writer,
342                                            MCAssembler &Asm,
343                                            const MCAsmLayout &Layout,
344                                            const MCFragment *Fragment,
345                                            const MCFixup &Fixup, MCValue Target,
346                                            uint64_t &FixedValue) {
347   unsigned IsPCRel = Writer->isFixupKindPCRel(Asm, Fixup.getKind());
348   unsigned Log2Size;
349   unsigned RelocType = MachO::ARM_RELOC_VANILLA;
350   if (!getARMFixupKindMachOInfo(Fixup.getKind(), RelocType, Log2Size))
351     // If we failed to get fixup kind info, it's because there's no legal
352     // relocation type for the fixup kind. This happens when it's a fixup that's
353     // expected to always be resolvable at assembly time and not have any
354     // relocations needed.
355     Asm.getContext().reportFatalError(Fixup.getLoc(),
356                                 "unsupported relocation on symbol");
357
358   // If this is a difference or a defined symbol plus an offset, then we need a
359   // scattered relocation entry.  Differences always require scattered
360   // relocations.
361   if (Target.getSymB()) {
362     if (RelocType == MachO::ARM_RELOC_HALF)
363       return RecordARMScatteredHalfRelocation(Writer, Asm, Layout, Fragment,
364                                               Fixup, Target, FixedValue);
365     return RecordARMScatteredRelocation(Writer, Asm, Layout, Fragment, Fixup,
366                                         Target, RelocType, Log2Size,
367                                         FixedValue);
368   }
369
370   // Get the symbol data, if any.
371   const MCSymbol *A = nullptr;
372   if (Target.getSymA())
373     A = &Target.getSymA()->getSymbol();
374
375   // FIXME: For other platforms, we need to use scattered relocations for
376   // internal relocations with offsets.  If this is an internal relocation with
377   // an offset, it also needs a scattered relocation entry.
378   //
379   // Is this right for ARM?
380   uint32_t Offset = Target.getConstant();
381   if (IsPCRel && RelocType == MachO::ARM_RELOC_VANILLA)
382     Offset += 1 << Log2Size;
383   if (Offset && A && !Writer->doesSymbolRequireExternRelocation(*A))
384     return RecordARMScatteredRelocation(Writer, Asm, Layout, Fragment, Fixup,
385                                         Target, RelocType, Log2Size,
386                                         FixedValue);
387
388   // See <reloc.h>.
389   uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
390   unsigned Index = 0;
391   unsigned Type = 0;
392   const MCSymbol *RelSymbol = nullptr;
393
394   if (Target.isAbsolute()) { // constant
395     // FIXME!
396     report_fatal_error("FIXME: relocations to absolute targets "
397                        "not yet implemented");
398   } else {
399     // Resolve constant variables.
400     if (A->isVariable()) {
401       int64_t Res;
402       if (A->getVariableValue()->evaluateAsAbsolute(
403               Res, Layout, Writer->getSectionAddressMap())) {
404         FixedValue = Res;
405         return;
406       }
407     }
408
409     // Check whether we need an external or internal relocation.
410     if (requiresExternRelocation(Writer, Asm, *Fragment, RelocType, *A,
411                                  FixedValue)) {
412       RelSymbol = A;
413
414       // For external relocations, make sure to offset the fixup value to
415       // compensate for the addend of the symbol address, if it was
416       // undefined. This occurs with weak definitions, for example.
417       if (!A->isUndefined())
418         FixedValue -= Layout.getSymbolOffset(*A);
419     } else {
420       // The index is the section ordinal (1-based).
421       const MCSection &Sec = A->getSection();
422       Index = Sec.getOrdinal() + 1;
423       FixedValue += Writer->getSectionAddress(&Sec);
424     }
425     if (IsPCRel)
426       FixedValue -= Writer->getSectionAddress(Fragment->getParent());
427
428     // The type is determined by the fixup kind.
429     Type = RelocType;
430   }
431
432   // struct relocation_info (8 bytes)
433   MachO::any_relocation_info MRE;
434   MRE.r_word0 = FixupOffset;
435   MRE.r_word1 =
436       (Index << 0) | (IsPCRel << 24) | (Log2Size << 25) | (Type << 28);
437
438   // Even when it's not a scattered relocation, movw/movt always uses
439   // a PAIR relocation.
440   if (Type == MachO::ARM_RELOC_HALF) {
441     // The other-half value only gets populated for the movt and movw
442     // relocation entries.
443     uint32_t Value = 0;
444     switch ((unsigned)Fixup.getKind()) {
445     default: break;
446     case ARM::fixup_arm_movw_lo16:
447     case ARM::fixup_t2_movw_lo16:
448       Value = (FixedValue >> 16) & 0xffff;
449       break;
450     case ARM::fixup_arm_movt_hi16:
451     case ARM::fixup_t2_movt_hi16:
452       Value = FixedValue & 0xffff;
453       break;
454     }
455     MachO::any_relocation_info MREPair;
456     MREPair.r_word0 = Value;
457     MREPair.r_word1 = ((0xffffff              <<  0) |
458                        (Log2Size              << 25) |
459                        (MachO::ARM_RELOC_PAIR << 28));
460
461     Writer->addRelocation(nullptr, Fragment->getParent(), MREPair);
462   }
463
464   Writer->addRelocation(RelSymbol, Fragment->getParent(), MRE);
465 }
466
467 MCObjectWriter *llvm::createARMMachObjectWriter(raw_pwrite_stream &OS,
468                                                 bool Is64Bit, uint32_t CPUType,
469                                                 uint32_t CPUSubtype) {
470   return createMachObjectWriter(new ARMMachObjectWriter(Is64Bit,
471                                                         CPUType,
472                                                         CPUSubtype),
473                                 OS, /*IsLittleEndian=*/true);
474 }