Use raw_pwrite_stream in the object writer/streamer.
[oota-llvm.git] / lib / Target / X86 / MCTargetDesc / X86MachObjectWriter.cpp
1 //===-- X86MachObjectWriter.cpp - X86 Mach-O 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/X86MCTargetDesc.h"
11 #include "MCTargetDesc/X86FixupKinds.h"
12 #include "llvm/ADT/Twine.h"
13 #include "llvm/MC/MCAsmInfo.h"
14 #include "llvm/MC/MCAsmLayout.h"
15 #include "llvm/MC/MCAssembler.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCMachObjectWriter.h"
18 #include "llvm/MC/MCSectionMachO.h"
19 #include "llvm/MC/MCValue.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/Format.h"
22 #include "llvm/Support/MachO.h"
23
24 using namespace llvm;
25
26 namespace {
27 class X86MachObjectWriter : public MCMachObjectTargetWriter {
28   bool RecordScatteredRelocation(MachObjectWriter *Writer,
29                                  const MCAssembler &Asm,
30                                  const MCAsmLayout &Layout,
31                                  const MCFragment *Fragment,
32                                  const MCFixup &Fixup,
33                                  MCValue Target,
34                                  unsigned Log2Size,
35                                  uint64_t &FixedValue);
36   void RecordTLVPRelocation(MachObjectWriter *Writer,
37                             const MCAssembler &Asm,
38                             const MCAsmLayout &Layout,
39                             const MCFragment *Fragment,
40                             const MCFixup &Fixup,
41                             MCValue Target,
42                             uint64_t &FixedValue);
43
44   void RecordX86Relocation(MachObjectWriter *Writer,
45                               const MCAssembler &Asm,
46                               const MCAsmLayout &Layout,
47                               const MCFragment *Fragment,
48                               const MCFixup &Fixup,
49                               MCValue Target,
50                               uint64_t &FixedValue);
51   void RecordX86_64Relocation(MachObjectWriter *Writer, MCAssembler &Asm,
52                               const MCAsmLayout &Layout,
53                               const MCFragment *Fragment, const MCFixup &Fixup,
54                               MCValue Target, uint64_t &FixedValue);
55
56 public:
57   X86MachObjectWriter(bool Is64Bit, uint32_t CPUType,
58                       uint32_t CPUSubtype)
59     : MCMachObjectTargetWriter(Is64Bit, CPUType, CPUSubtype,
60                                /*UseAggressiveSymbolFolding=*/Is64Bit) {}
61
62   void RecordRelocation(MachObjectWriter *Writer, MCAssembler &Asm,
63                         const MCAsmLayout &Layout, const MCFragment *Fragment,
64                         const MCFixup &Fixup, MCValue Target,
65                         uint64_t &FixedValue) override {
66     if (Writer->is64Bit())
67       RecordX86_64Relocation(Writer, Asm, Layout, Fragment, Fixup, Target,
68                              FixedValue);
69     else
70       RecordX86Relocation(Writer, Asm, Layout, Fragment, Fixup, Target,
71                           FixedValue);
72   }
73 };
74 }
75
76 static bool isFixupKindRIPRel(unsigned Kind) {
77   return Kind == X86::reloc_riprel_4byte ||
78     Kind == X86::reloc_riprel_4byte_movq_load;
79 }
80
81 static unsigned getFixupKindLog2Size(unsigned Kind) {
82   switch (Kind) {
83   default:
84     llvm_unreachable("invalid fixup kind!");
85   case FK_PCRel_1:
86   case FK_Data_1: return 0;
87   case FK_PCRel_2:
88   case FK_Data_2: return 1;
89   case FK_PCRel_4:
90     // FIXME: Remove these!!!
91   case X86::reloc_riprel_4byte:
92   case X86::reloc_riprel_4byte_movq_load:
93   case X86::reloc_signed_4byte:
94   case FK_Data_4: return 2;
95   case FK_Data_8: return 3;
96   }
97 }
98
99 void X86MachObjectWriter::RecordX86_64Relocation(
100     MachObjectWriter *Writer, MCAssembler &Asm, const MCAsmLayout &Layout,
101     const MCFragment *Fragment, const MCFixup &Fixup, MCValue Target,
102     uint64_t &FixedValue) {
103   unsigned IsPCRel = Writer->isFixupKindPCRel(Asm, Fixup.getKind());
104   unsigned IsRIPRel = isFixupKindRIPRel(Fixup.getKind());
105   unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
106
107   // See <reloc.h>.
108   uint32_t FixupOffset =
109     Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
110   uint32_t FixupAddress =
111     Writer->getFragmentAddress(Fragment, Layout) + Fixup.getOffset();
112   int64_t Value = 0;
113   unsigned Index = 0;
114   unsigned IsExtern = 0;
115   unsigned Type = 0;
116   const MCSymbolData *RelSymbol = nullptr;
117
118   Value = Target.getConstant();
119
120   if (IsPCRel) {
121     // Compensate for the relocation offset, Darwin x86_64 relocations only have
122     // the addend and appear to have attempted to define it to be the actual
123     // expression addend without the PCrel bias. However, instructions with data
124     // following the relocation are not accommodated for (see comment below
125     // regarding SIGNED{1,2,4}), so it isn't exactly that either.
126     Value += 1LL << Log2Size;
127   }
128
129   if (Target.isAbsolute()) { // constant
130     // SymbolNum of 0 indicates the absolute section.
131     Type = MachO::X86_64_RELOC_UNSIGNED;
132
133     // FIXME: I believe this is broken, I don't think the linker can understand
134     // it. I think it would require a local relocation, but I'm not sure if that
135     // would work either. The official way to get an absolute PCrel relocation
136     // is to use an absolute symbol (which we don't support yet).
137     if (IsPCRel) {
138       IsExtern = 1;
139       Type = MachO::X86_64_RELOC_BRANCH;
140     }
141   } else if (Target.getSymB()) { // A - B + constant
142     const MCSymbol *A = &Target.getSymA()->getSymbol();
143     if (A->isTemporary())
144       A = &A->AliasedSymbol();
145     const MCSymbolData &A_SD = Asm.getSymbolData(*A);
146     const MCSymbolData *A_Base = Asm.getAtom(&A_SD);
147
148     const MCSymbol *B = &Target.getSymB()->getSymbol();
149     if (B->isTemporary())
150       B = &B->AliasedSymbol();
151     const MCSymbolData &B_SD = Asm.getSymbolData(*B);
152     const MCSymbolData *B_Base = Asm.getAtom(&B_SD);
153
154     // Neither symbol can be modified.
155     if (Target.getSymA()->getKind() != MCSymbolRefExpr::VK_None ||
156         Target.getSymB()->getKind() != MCSymbolRefExpr::VK_None)
157       report_fatal_error("unsupported relocation of modified symbol", false);
158
159     // We don't support PCrel relocations of differences. Darwin 'as' doesn't
160     // implement most of these correctly.
161     if (IsPCRel)
162       report_fatal_error("unsupported pc-relative relocation of difference",
163                          false);
164
165     // The support for the situation where one or both of the symbols would
166     // require a local relocation is handled just like if the symbols were
167     // external.  This is certainly used in the case of debug sections where the
168     // section has only temporary symbols and thus the symbols don't have base
169     // symbols.  This is encoded using the section ordinal and non-extern
170     // relocation entries.
171
172     // Darwin 'as' doesn't emit correct relocations for this (it ends up with a
173     // single SIGNED relocation); reject it for now.  Except the case where both
174     // symbols don't have a base, equal but both NULL.
175     if (A_Base == B_Base && A_Base)
176       report_fatal_error("unsupported relocation with identical base", false);
177
178     // A subtraction expression where either symbol is undefined is a
179     // non-relocatable expression.
180     if (A->isUndefined() || B->isUndefined()) {
181       StringRef Name = A->isUndefined() ? A->getName() : B->getName();
182       Asm.getContext().FatalError(Fixup.getLoc(),
183         "unsupported relocation with subtraction expression, symbol '" +
184         Name + "' can not be undefined in a subtraction expression");
185     }
186
187     Value += Writer->getSymbolAddress(&A_SD, Layout) -
188       (!A_Base ? 0 : Writer->getSymbolAddress(A_Base, Layout));
189     Value -= Writer->getSymbolAddress(&B_SD, Layout) -
190       (!B_Base ? 0 : Writer->getSymbolAddress(B_Base, Layout));
191
192     if (!A_Base)
193       Index = A_SD.getFragment()->getParent()->getOrdinal() + 1;
194     Type = MachO::X86_64_RELOC_UNSIGNED;
195
196     MachO::any_relocation_info MRE;
197     MRE.r_word0 = FixupOffset;
198     MRE.r_word1 =
199         (Index << 0) | (IsPCRel << 24) | (Log2Size << 25) | (Type << 28);
200     Writer->addRelocation(A_Base, Fragment->getParent(), MRE);
201
202     if (B_Base)
203       RelSymbol = B_Base;
204     else
205       Index = B_SD.getFragment()->getParent()->getOrdinal() + 1;
206     Type = MachO::X86_64_RELOC_SUBTRACTOR;
207   } else {
208     const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
209     if (Symbol->isTemporary() && Value) {
210       const MCSection &Sec = Symbol->getSection();
211       if (!Asm.getContext().getAsmInfo()->isSectionAtomizableBySymbols(Sec))
212         Asm.addLocalUsedInReloc(*Symbol);
213     }
214     const MCSymbolData &SD = Asm.getSymbolData(*Symbol);
215     RelSymbol = Asm.getAtom(&SD);
216
217     // Relocations inside debug sections always use local relocations when
218     // possible. This seems to be done because the debugger doesn't fully
219     // understand x86_64 relocation entries, and expects to find values that
220     // have already been fixed up.
221     if (Symbol->isInSection()) {
222       const MCSectionMachO &Section = static_cast<const MCSectionMachO&>(
223         Fragment->getParent()->getSection());
224       if (Section.hasAttribute(MachO::S_ATTR_DEBUG))
225         RelSymbol = nullptr;
226     }
227
228     // x86_64 almost always uses external relocations, except when there is no
229     // symbol to use as a base address (a local symbol with no preceding
230     // non-local symbol).
231     if (RelSymbol) {
232       // Add the local offset, if needed.
233       if (RelSymbol != &SD)
234         Value +=
235             Layout.getSymbolOffset(&SD) - Layout.getSymbolOffset(RelSymbol);
236     } else if (Symbol->isInSection() && !Symbol->isVariable()) {
237       // The index is the section ordinal (1-based).
238       Index = SD.getFragment()->getParent()->getOrdinal() + 1;
239       Value += Writer->getSymbolAddress(&SD, Layout);
240
241       if (IsPCRel)
242         Value -= FixupAddress + (1 << Log2Size);
243     } else if (Symbol->isVariable()) {
244       const MCExpr *Value = Symbol->getVariableValue();
245       int64_t Res;
246       bool isAbs = Value->EvaluateAsAbsolute(Res, Layout,
247                                              Writer->getSectionAddressMap());
248       if (isAbs) {
249         FixedValue = Res;
250         return;
251       } else {
252         report_fatal_error("unsupported relocation of variable '" +
253                            Symbol->getName() + "'", false);
254       }
255     } else {
256       report_fatal_error("unsupported relocation of undefined symbol '" +
257                          Symbol->getName() + "'", false);
258     }
259
260     MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
261     if (IsPCRel) {
262       if (IsRIPRel) {
263         if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
264           // x86_64 distinguishes movq foo@GOTPCREL so that the linker can
265           // rewrite the movq to an leaq at link time if the symbol ends up in
266           // the same linkage unit.
267           if (unsigned(Fixup.getKind()) == X86::reloc_riprel_4byte_movq_load)
268             Type = MachO::X86_64_RELOC_GOT_LOAD;
269           else
270             Type = MachO::X86_64_RELOC_GOT;
271         }  else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
272           Type = MachO::X86_64_RELOC_TLV;
273         }  else if (Modifier != MCSymbolRefExpr::VK_None) {
274           report_fatal_error("unsupported symbol modifier in relocation",
275                              false);
276         } else {
277           Type = MachO::X86_64_RELOC_SIGNED;
278
279           // The Darwin x86_64 relocation format has a problem where it cannot
280           // encode an address (L<foo> + <constant>) which is outside the atom
281           // containing L<foo>. Generally, this shouldn't occur but it does
282           // happen when we have a RIPrel instruction with data following the
283           // relocation entry (e.g., movb $012, L0(%rip)). Even with the PCrel
284           // adjustment Darwin x86_64 uses, the offset is still negative and the
285           // linker has no way to recognize this.
286           //
287           // To work around this, Darwin uses several special relocation types
288           // to indicate the offsets. However, the specification or
289           // implementation of these seems to also be incomplete; they should
290           // adjust the addend as well based on the actual encoded instruction
291           // (the additional bias), but instead appear to just look at the final
292           // offset.
293           switch (-(Target.getConstant() + (1LL << Log2Size))) {
294           case 1: Type = MachO::X86_64_RELOC_SIGNED_1; break;
295           case 2: Type = MachO::X86_64_RELOC_SIGNED_2; break;
296           case 4: Type = MachO::X86_64_RELOC_SIGNED_4; break;
297           }
298         }
299       } else {
300         if (Modifier != MCSymbolRefExpr::VK_None)
301           report_fatal_error("unsupported symbol modifier in branch "
302                              "relocation", false);
303
304         Type = MachO::X86_64_RELOC_BRANCH;
305       }
306     } else {
307       if (Modifier == MCSymbolRefExpr::VK_GOT) {
308         Type = MachO::X86_64_RELOC_GOT;
309       } else if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
310         // GOTPCREL is allowed as a modifier on non-PCrel instructions, in which
311         // case all we do is set the PCrel bit in the relocation entry; this is
312         // used with exception handling, for example. The source is required to
313         // include any necessary offset directly.
314         Type = MachO::X86_64_RELOC_GOT;
315         IsPCRel = 1;
316       } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
317         report_fatal_error("TLVP symbol modifier should have been rip-rel",
318                            false);
319       } else if (Modifier != MCSymbolRefExpr::VK_None)
320         report_fatal_error("unsupported symbol modifier in relocation", false);
321       else {
322         Type = MachO::X86_64_RELOC_UNSIGNED;
323         unsigned Kind = Fixup.getKind();
324         if (Kind == X86::reloc_signed_4byte)
325           report_fatal_error("32-bit absolute addressing is not supported in "
326                              "64-bit mode", false);
327       }
328     }
329   }
330
331   // x86_64 always writes custom values into the fixups.
332   FixedValue = Value;
333
334   // struct relocation_info (8 bytes)
335   MachO::any_relocation_info MRE;
336   MRE.r_word0 = FixupOffset;
337   MRE.r_word1 = (Index << 0) | (IsPCRel << 24) | (Log2Size << 25) |
338                 (IsExtern << 27) | (Type << 28);
339   Writer->addRelocation(RelSymbol, Fragment->getParent(), MRE);
340 }
341
342 bool X86MachObjectWriter::RecordScatteredRelocation(MachObjectWriter *Writer,
343                                                     const MCAssembler &Asm,
344                                                     const MCAsmLayout &Layout,
345                                                     const MCFragment *Fragment,
346                                                     const MCFixup &Fixup,
347                                                     MCValue Target,
348                                                     unsigned Log2Size,
349                                                     uint64_t &FixedValue) {
350   uint64_t OriginalFixedValue = FixedValue;
351   uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
352   unsigned IsPCRel = Writer->isFixupKindPCRel(Asm, Fixup.getKind());
353   unsigned Type = MachO::GENERIC_RELOC_VANILLA;
354
355   // See <reloc.h>.
356   const MCSymbol *A = &Target.getSymA()->getSymbol();
357   const MCSymbolData *A_SD = &Asm.getSymbolData(*A);
358
359   if (!A_SD->getFragment())
360     report_fatal_error("symbol '" + A->getName() +
361                        "' can not be undefined in a subtraction expression",
362                        false);
363
364   uint32_t Value = Writer->getSymbolAddress(A_SD, Layout);
365   uint64_t SecAddr = Writer->getSectionAddress(A_SD->getFragment()->getParent());
366   FixedValue += SecAddr;
367   uint32_t Value2 = 0;
368
369   if (const MCSymbolRefExpr *B = Target.getSymB()) {
370     const MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
371
372     if (!B_SD->getFragment())
373       report_fatal_error("symbol '" + B->getSymbol().getName() +
374                          "' can not be undefined in a subtraction expression",
375                          false);
376
377     // Select the appropriate difference relocation type.
378     //
379     // Note that there is no longer any semantic difference between these two
380     // relocation types from the linkers point of view, this is done solely for
381     // pedantic compatibility with 'as'.
382     Type = A_SD->isExternal() ? (unsigned)MachO::GENERIC_RELOC_SECTDIFF :
383       (unsigned)MachO::GENERIC_RELOC_LOCAL_SECTDIFF;
384     Value2 = Writer->getSymbolAddress(B_SD, Layout);
385     FixedValue -= Writer->getSectionAddress(B_SD->getFragment()->getParent());
386   }
387
388   // Relocations are written out in reverse order, so the PAIR comes first.
389   if (Type == MachO::GENERIC_RELOC_SECTDIFF ||
390       Type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
391     // If the offset is too large to fit in a scattered relocation,
392     // we're hosed. It's an unfortunate limitation of the MachO format.
393     if (FixupOffset > 0xffffff) {
394       char Buffer[32];
395       format("0x%x", FixupOffset).print(Buffer, sizeof(Buffer));
396       Asm.getContext().FatalError(Fixup.getLoc(),
397                          Twine("Section too large, can't encode "
398                                 "r_address (") + Buffer +
399                          ") into 24 bits of scattered "
400                          "relocation entry.");
401       llvm_unreachable("fatal error returned?!");
402     }
403
404     MachO::any_relocation_info MRE;
405     MRE.r_word0 = ((0                         <<  0) | // r_address
406                    (MachO::GENERIC_RELOC_PAIR << 24) | // r_type
407                    (Log2Size                  << 28) |
408                    (IsPCRel                   << 30) |
409                    MachO::R_SCATTERED);
410     MRE.r_word1 = Value2;
411     Writer->addRelocation(nullptr, Fragment->getParent(), MRE);
412   } else {
413     // If the offset is more than 24-bits, it won't fit in a scattered
414     // relocation offset field, so we fall back to using a non-scattered
415     // relocation. This is a bit risky, as if the offset reaches out of
416     // the block and the linker is doing scattered loading on this
417     // symbol, things can go badly.
418     //
419     // Required for 'as' compatibility.
420     if (FixupOffset > 0xffffff) {
421       FixedValue = OriginalFixedValue;
422       return false;
423     }
424   }
425
426   MachO::any_relocation_info MRE;
427   MRE.r_word0 = ((FixupOffset <<  0) |
428                  (Type        << 24) |
429                  (Log2Size    << 28) |
430                  (IsPCRel     << 30) |
431                  MachO::R_SCATTERED);
432   MRE.r_word1 = Value;
433   Writer->addRelocation(nullptr, Fragment->getParent(), MRE);
434   return true;
435 }
436
437 void X86MachObjectWriter::RecordTLVPRelocation(MachObjectWriter *Writer,
438                                                const MCAssembler &Asm,
439                                                const MCAsmLayout &Layout,
440                                                const MCFragment *Fragment,
441                                                const MCFixup &Fixup,
442                                                MCValue Target,
443                                                uint64_t &FixedValue) {
444   assert(Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP &&
445          !is64Bit() &&
446          "Should only be called with a 32-bit TLVP relocation!");
447
448   unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
449   uint32_t Value = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
450   unsigned IsPCRel = 0;
451
452   // Get the symbol data.
453   const MCSymbolData *SD_A = &Asm.getSymbolData(Target.getSymA()->getSymbol());
454
455   // We're only going to have a second symbol in pic mode and it'll be a
456   // subtraction from the picbase. For 32-bit pic the addend is the difference
457   // between the picbase and the next address.  For 32-bit static the addend is
458   // zero.
459   if (Target.getSymB()) {
460     // If this is a subtraction then we're pcrel.
461     uint32_t FixupAddress =
462       Writer->getFragmentAddress(Fragment, Layout) + Fixup.getOffset();
463     const MCSymbolData *SD_B =
464         &Asm.getSymbolData(Target.getSymB()->getSymbol());
465     IsPCRel = 1;
466     FixedValue = (FixupAddress - Writer->getSymbolAddress(SD_B, Layout) +
467                   Target.getConstant());
468     FixedValue += 1ULL << Log2Size;
469   } else {
470     FixedValue = 0;
471   }
472
473   // struct relocation_info (8 bytes)
474   MachO::any_relocation_info MRE;
475   MRE.r_word0 = Value;
476   MRE.r_word1 =
477       (IsPCRel << 24) | (Log2Size << 25) | (MachO::GENERIC_RELOC_TLV << 28);
478   Writer->addRelocation(SD_A, Fragment->getParent(), MRE);
479 }
480
481 void X86MachObjectWriter::RecordX86Relocation(MachObjectWriter *Writer,
482                                               const MCAssembler &Asm,
483                                               const MCAsmLayout &Layout,
484                                               const MCFragment *Fragment,
485                                               const MCFixup &Fixup,
486                                               MCValue Target,
487                                               uint64_t &FixedValue) {
488   unsigned IsPCRel = Writer->isFixupKindPCRel(Asm, Fixup.getKind());
489   unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
490
491   // If this is a 32-bit TLVP reloc it's handled a bit differently.
492   if (Target.getSymA() &&
493       Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP) {
494     RecordTLVPRelocation(Writer, Asm, Layout, Fragment, Fixup, Target,
495                          FixedValue);
496     return;
497   }
498
499   // If this is a difference or a defined symbol plus an offset, then we need a
500   // scattered relocation entry. Differences always require scattered
501   // relocations.
502   if (Target.getSymB()) {
503     RecordScatteredRelocation(Writer, Asm, Layout, Fragment, Fixup,
504                               Target, Log2Size, FixedValue);
505     return;
506   }
507
508   // Get the symbol data, if any.
509   const MCSymbolData *SD = nullptr;
510   if (Target.getSymA())
511     SD = &Asm.getSymbolData(Target.getSymA()->getSymbol());
512
513   // If this is an internal relocation with an offset, it also needs a scattered
514   // relocation entry.
515   uint32_t Offset = Target.getConstant();
516   if (IsPCRel)
517     Offset += 1 << Log2Size;
518   // Try to record the scattered relocation if needed. Fall back to non
519   // scattered if necessary (see comments in RecordScatteredRelocation()
520   // for details).
521   if (Offset && SD && !Writer->doesSymbolRequireExternRelocation(SD) &&
522       RecordScatteredRelocation(Writer, Asm, Layout, Fragment, Fixup,
523                                 Target, Log2Size, FixedValue))
524     return;
525
526   // See <reloc.h>.
527   uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
528   unsigned Index = 0;
529   unsigned Type = 0;
530   const MCSymbolData *RelSymbol = nullptr;
531
532   if (Target.isAbsolute()) { // constant
533     // SymbolNum of 0 indicates the absolute section.
534     //
535     // FIXME: Currently, these are never generated (see code below). I cannot
536     // find a case where they are actually emitted.
537     Type = MachO::GENERIC_RELOC_VANILLA;
538   } else {
539     // Resolve constant variables.
540     if (SD->getSymbol().isVariable()) {
541       int64_t Res;
542       if (SD->getSymbol().getVariableValue()->EvaluateAsAbsolute(
543             Res, Layout, Writer->getSectionAddressMap())) {
544         FixedValue = Res;
545         return;
546       }
547     }
548
549     // Check whether we need an external or internal relocation.
550     if (Writer->doesSymbolRequireExternRelocation(SD)) {
551       RelSymbol = SD;
552       // For external relocations, make sure to offset the fixup value to
553       // compensate for the addend of the symbol address, if it was
554       // undefined. This occurs with weak definitions, for example.
555       if (!SD->getSymbol().isUndefined())
556         FixedValue -= Layout.getSymbolOffset(SD);
557     } else {
558       // The index is the section ordinal (1-based).
559       const MCSectionData &SymSD = Asm.getSectionData(
560         SD->getSymbol().getSection());
561       Index = SymSD.getOrdinal() + 1;
562       FixedValue += Writer->getSectionAddress(&SymSD);
563     }
564     if (IsPCRel)
565       FixedValue -= Writer->getSectionAddress(Fragment->getParent());
566
567     Type = MachO::GENERIC_RELOC_VANILLA;
568   }
569
570   // struct relocation_info (8 bytes)
571   MachO::any_relocation_info MRE;
572   MRE.r_word0 = FixupOffset;
573   MRE.r_word1 =
574       (Index << 0) | (IsPCRel << 24) | (Log2Size << 25) | (Type << 28);
575   Writer->addRelocation(RelSymbol, Fragment->getParent(), MRE);
576 }
577
578 MCObjectWriter *llvm::createX86MachObjectWriter(raw_pwrite_stream &OS,
579                                                 bool Is64Bit, uint32_t CPUType,
580                                                 uint32_t CPUSubtype) {
581   return createMachObjectWriter(new X86MachObjectWriter(Is64Bit,
582                                                         CPUType,
583                                                         CPUSubtype),
584                                 OS, /*IsLittleEndian=*/true);
585 }