Fix an issue in some Thumb fixups, where the effective PC address needs to be 4-byte...
[oota-llvm.git] / lib / MC / MachObjectWriter.cpp
1 //===- lib/MC/MachObjectWriter.cpp - Mach-O File 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 "llvm/ADT/StringMap.h"
11 #include "llvm/ADT/Twine.h"
12 #include "llvm/MC/MCAssembler.h"
13 #include "llvm/MC/MCAsmLayout.h"
14 #include "llvm/MC/MCExpr.h"
15 #include "llvm/MC/MCObjectWriter.h"
16 #include "llvm/MC/MCSectionMachO.h"
17 #include "llvm/MC/MCSymbol.h"
18 #include "llvm/MC/MCMachOSymbolFlags.h"
19 #include "llvm/MC/MCValue.h"
20 #include "llvm/Object/MachOFormat.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Target/TargetAsmBackend.h"
23
24 // FIXME: Gross.
25 #include "../Target/X86/X86FixupKinds.h"
26
27 #include <vector>
28 using namespace llvm;
29 using namespace llvm::object;
30
31 // FIXME: this has been copied from (or to) X86AsmBackend.cpp
32 static unsigned getFixupKindLog2Size(unsigned Kind) {
33   switch (Kind) {
34   // FIXME: Until ARM has it's own relocation stuff spun off, it comes
35   // through here and we don't want it to puke all over. Any reasonable
36   // values will only come when ARM relocation support gets added, at which
37   // point this will be X86 only again and the llvm_unreachable can be
38   // re-enabled.
39   default: return 0;// llvm_unreachable("invalid fixup kind!");
40   case FK_PCRel_1:
41   case FK_Data_1: return 0;
42   case FK_PCRel_2:
43   case FK_Data_2: return 1;
44   case FK_PCRel_4:
45   case X86::reloc_riprel_4byte:
46   case X86::reloc_riprel_4byte_movq_load:
47   case X86::reloc_signed_4byte:
48   case FK_Data_4: return 2;
49   case FK_Data_8: return 3;
50   }
51 }
52
53 static bool isFixupKindPCRel(unsigned Kind) {
54   switch (Kind) {
55   default:
56     return false;
57   case FK_PCRel_1:
58   case FK_PCRel_2:
59   case FK_PCRel_4:
60   case X86::reloc_riprel_4byte:
61   case X86::reloc_riprel_4byte_movq_load:
62     return true;
63   }
64 }
65
66 static bool isFixupKindRIPRel(unsigned Kind) {
67   return Kind == X86::reloc_riprel_4byte ||
68     Kind == X86::reloc_riprel_4byte_movq_load;
69 }
70
71 static bool doesSymbolRequireExternRelocation(MCSymbolData *SD) {
72   // Undefined symbols are always extern.
73   if (SD->Symbol->isUndefined())
74     return true;
75
76   // References to weak definitions require external relocation entries; the
77   // definition may not always be the one in the same object file.
78   if (SD->getFlags() & SF_WeakDefinition)
79     return true;
80
81   // Otherwise, we can use an internal relocation.
82   return false;
83 }
84
85 static bool isScatteredFixupFullyResolved(const MCAssembler &Asm,
86                                           const MCValue Target,
87                                           const MCSymbolData *BaseSymbol) {
88   // The effective fixup address is
89   //     addr(atom(A)) + offset(A)
90   //   - addr(atom(B)) - offset(B)
91   //   - addr(BaseSymbol) + <fixup offset from base symbol>
92   // and the offsets are not relocatable, so the fixup is fully resolved when
93   //  addr(atom(A)) - addr(atom(B)) - addr(BaseSymbol) == 0.
94   //
95   // Note that "false" is almost always conservatively correct (it means we emit
96   // a relocation which is unnecessary), except when it would force us to emit a
97   // relocation which the target cannot encode.
98
99   const MCSymbolData *A_Base = 0, *B_Base = 0;
100   if (const MCSymbolRefExpr *A = Target.getSymA()) {
101     // Modified symbol references cannot be resolved.
102     if (A->getKind() != MCSymbolRefExpr::VK_None)
103       return false;
104
105     A_Base = Asm.getAtom(&Asm.getSymbolData(A->getSymbol()));
106     if (!A_Base)
107       return false;
108   }
109
110   if (const MCSymbolRefExpr *B = Target.getSymB()) {
111     // Modified symbol references cannot be resolved.
112     if (B->getKind() != MCSymbolRefExpr::VK_None)
113       return false;
114
115     B_Base = Asm.getAtom(&Asm.getSymbolData(B->getSymbol()));
116     if (!B_Base)
117       return false;
118   }
119
120   // If there is no base, A and B have to be the same atom for this fixup to be
121   // fully resolved.
122   if (!BaseSymbol)
123     return A_Base == B_Base;
124
125   // Otherwise, B must be missing and A must be the base.
126   return !B_Base && BaseSymbol == A_Base;
127 }
128
129 static bool isScatteredFixupFullyResolvedSimple(const MCAssembler &Asm,
130                                                 const MCValue Target,
131                                                 const MCSection *BaseSection) {
132   // The effective fixup address is
133   //     addr(atom(A)) + offset(A)
134   //   - addr(atom(B)) - offset(B)
135   //   - addr(<base symbol>) + <fixup offset from base symbol>
136   // and the offsets are not relocatable, so the fixup is fully resolved when
137   //  addr(atom(A)) - addr(atom(B)) - addr(<base symbol>)) == 0.
138   //
139   // The simple (Darwin, except on x86_64) way of dealing with this was to
140   // assume that any reference to a temporary symbol *must* be a temporary
141   // symbol in the same atom, unless the sections differ. Therefore, any PCrel
142   // relocation to a temporary symbol (in the same section) is fully
143   // resolved. This also works in conjunction with absolutized .set, which
144   // requires the compiler to use .set to absolutize the differences between
145   // symbols which the compiler knows to be assembly time constants, so we don't
146   // need to worry about considering symbol differences fully resolved.
147
148   // Non-relative fixups are only resolved if constant.
149   if (!BaseSection)
150     return Target.isAbsolute();
151
152   // Otherwise, relative fixups are only resolved if not a difference and the
153   // target is a temporary in the same section.
154   if (Target.isAbsolute() || Target.getSymB())
155     return false;
156
157   const MCSymbol *A = &Target.getSymA()->getSymbol();
158   if (!A->isTemporary() || !A->isInSection() ||
159       &A->getSection() != BaseSection)
160     return false;
161
162   return true;
163 }
164
165 namespace {
166
167 class MachObjectWriter : public MCObjectWriter {
168   /// MachSymbolData - Helper struct for containing some precomputed information
169   /// on symbols.
170   struct MachSymbolData {
171     MCSymbolData *SymbolData;
172     uint64_t StringIndex;
173     uint8_t SectionIndex;
174
175     // Support lexicographic sorting.
176     bool operator<(const MachSymbolData &RHS) const {
177       return SymbolData->getSymbol().getName() <
178              RHS.SymbolData->getSymbol().getName();
179     }
180   };
181
182   /// @name Relocation Data
183   /// @{
184
185   llvm::DenseMap<const MCSectionData*,
186                  std::vector<macho::RelocationEntry> > Relocations;
187   llvm::DenseMap<const MCSectionData*, unsigned> IndirectSymBase;
188
189   /// @}
190   /// @name Symbol Table Data
191   /// @{
192
193   SmallString<256> StringTable;
194   std::vector<MachSymbolData> LocalSymbolData;
195   std::vector<MachSymbolData> ExternalSymbolData;
196   std::vector<MachSymbolData> UndefinedSymbolData;
197
198   /// @}
199
200   SectionAddrMap SectionAddress;
201   uint64_t getSectionAddress(const MCSectionData* SD) const {
202     return SectionAddress.lookup(SD);
203   }
204   uint64_t getSymbolAddress(const MCSymbolData* SD,
205                             const MCAsmLayout &Layout) const {
206     return getSectionAddress(SD->getFragment()->getParent()) +
207       Layout.getSymbolOffset(SD);
208   }
209   uint64_t getFragmentAddress(const MCFragment *Fragment,
210                             const MCAsmLayout &Layout) const {
211     return getSectionAddress(Fragment->getParent()) +
212       Layout.getFragmentOffset(Fragment);
213   }
214
215   uint64_t getPaddingSize(const MCSectionData *SD,
216                           const MCAsmLayout &Layout) const {
217     uint64_t EndAddr = getSectionAddress(SD) + Layout.getSectionAddressSize(SD);
218     unsigned Next = SD->getLayoutOrder() + 1;
219     if (Next >= Layout.getSectionOrder().size())
220       return 0;
221
222     const MCSectionData &NextSD = *Layout.getSectionOrder()[Next];
223     if (NextSD.getSection().isVirtualSection())
224       return 0;
225     return OffsetToAlignment(EndAddr, NextSD.getAlignment());
226   }
227
228   unsigned Is64Bit : 1;
229
230   uint32_t CPUType;
231   uint32_t CPUSubtype;
232
233 public:
234   MachObjectWriter(raw_ostream &_OS,
235                    bool _Is64Bit, uint32_t _CPUType, uint32_t _CPUSubtype,
236                    bool _IsLittleEndian)
237     : MCObjectWriter(_OS, _IsLittleEndian),
238       Is64Bit(_Is64Bit), CPUType(_CPUType), CPUSubtype(_CPUSubtype) {
239   }
240
241   void WriteHeader(unsigned NumLoadCommands, unsigned LoadCommandsSize,
242                    bool SubsectionsViaSymbols) {
243     uint32_t Flags = 0;
244
245     if (SubsectionsViaSymbols)
246       Flags |= macho::HF_SubsectionsViaSymbols;
247
248     // struct mach_header (28 bytes) or
249     // struct mach_header_64 (32 bytes)
250
251     uint64_t Start = OS.tell();
252     (void) Start;
253
254     Write32(Is64Bit ? macho::HM_Object64 : macho::HM_Object32);
255
256     Write32(CPUType);
257     Write32(CPUSubtype);
258
259     Write32(macho::HFT_Object);
260     Write32(NumLoadCommands);
261     Write32(LoadCommandsSize);
262     Write32(Flags);
263     if (Is64Bit)
264       Write32(0); // reserved
265
266     assert(OS.tell() - Start == Is64Bit ? 
267            macho::Header64Size : macho::Header32Size);
268   }
269
270   /// WriteSegmentLoadCommand - Write a segment load command.
271   ///
272   /// \arg NumSections - The number of sections in this segment.
273   /// \arg SectionDataSize - The total size of the sections.
274   void WriteSegmentLoadCommand(unsigned NumSections,
275                                uint64_t VMSize,
276                                uint64_t SectionDataStartOffset,
277                                uint64_t SectionDataSize) {
278     // struct segment_command (56 bytes) or
279     // struct segment_command_64 (72 bytes)
280
281     uint64_t Start = OS.tell();
282     (void) Start;
283
284     unsigned SegmentLoadCommandSize = Is64Bit ? macho::SegmentLoadCommand64Size:
285       macho::SegmentLoadCommand32Size;
286     Write32(Is64Bit ? macho::LCT_Segment64 : macho::LCT_Segment);
287     Write32(SegmentLoadCommandSize +
288             NumSections * (Is64Bit ? macho::Section64Size :
289                            macho::Section32Size));
290
291     WriteBytes("", 16);
292     if (Is64Bit) {
293       Write64(0); // vmaddr
294       Write64(VMSize); // vmsize
295       Write64(SectionDataStartOffset); // file offset
296       Write64(SectionDataSize); // file size
297     } else {
298       Write32(0); // vmaddr
299       Write32(VMSize); // vmsize
300       Write32(SectionDataStartOffset); // file offset
301       Write32(SectionDataSize); // file size
302     }
303     Write32(0x7); // maxprot
304     Write32(0x7); // initprot
305     Write32(NumSections);
306     Write32(0); // flags
307
308     assert(OS.tell() - Start == SegmentLoadCommandSize);
309   }
310
311   void WriteSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
312                     const MCSectionData &SD, uint64_t FileOffset,
313                     uint64_t RelocationsStart, unsigned NumRelocations) {
314     uint64_t SectionSize = Layout.getSectionAddressSize(&SD);
315
316     // The offset is unused for virtual sections.
317     if (SD.getSection().isVirtualSection()) {
318       assert(Layout.getSectionFileSize(&SD) == 0 && "Invalid file size!");
319       FileOffset = 0;
320     }
321
322     // struct section (68 bytes) or
323     // struct section_64 (80 bytes)
324
325     uint64_t Start = OS.tell();
326     (void) Start;
327
328     const MCSectionMachO &Section = cast<MCSectionMachO>(SD.getSection());
329     WriteBytes(Section.getSectionName(), 16);
330     WriteBytes(Section.getSegmentName(), 16);
331     if (Is64Bit) {
332       Write64(getSectionAddress(&SD)); // address
333       Write64(SectionSize); // size
334     } else {
335       Write32(getSectionAddress(&SD)); // address
336       Write32(SectionSize); // size
337     }
338     Write32(FileOffset);
339
340     unsigned Flags = Section.getTypeAndAttributes();
341     if (SD.hasInstructions())
342       Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
343
344     assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
345     Write32(Log2_32(SD.getAlignment()));
346     Write32(NumRelocations ? RelocationsStart : 0);
347     Write32(NumRelocations);
348     Write32(Flags);
349     Write32(IndirectSymBase.lookup(&SD)); // reserved1
350     Write32(Section.getStubSize()); // reserved2
351     if (Is64Bit)
352       Write32(0); // reserved3
353
354     assert(OS.tell() - Start == Is64Bit ? macho::Section64Size :
355            macho::Section32Size);
356   }
357
358   void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
359                               uint32_t StringTableOffset,
360                               uint32_t StringTableSize) {
361     // struct symtab_command (24 bytes)
362
363     uint64_t Start = OS.tell();
364     (void) Start;
365
366     Write32(macho::LCT_Symtab);
367     Write32(macho::SymtabLoadCommandSize);
368     Write32(SymbolOffset);
369     Write32(NumSymbols);
370     Write32(StringTableOffset);
371     Write32(StringTableSize);
372
373     assert(OS.tell() - Start == macho::SymtabLoadCommandSize);
374   }
375
376   void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
377                                 uint32_t NumLocalSymbols,
378                                 uint32_t FirstExternalSymbol,
379                                 uint32_t NumExternalSymbols,
380                                 uint32_t FirstUndefinedSymbol,
381                                 uint32_t NumUndefinedSymbols,
382                                 uint32_t IndirectSymbolOffset,
383                                 uint32_t NumIndirectSymbols) {
384     // struct dysymtab_command (80 bytes)
385
386     uint64_t Start = OS.tell();
387     (void) Start;
388
389     Write32(macho::LCT_Dysymtab);
390     Write32(macho::DysymtabLoadCommandSize);
391     Write32(FirstLocalSymbol);
392     Write32(NumLocalSymbols);
393     Write32(FirstExternalSymbol);
394     Write32(NumExternalSymbols);
395     Write32(FirstUndefinedSymbol);
396     Write32(NumUndefinedSymbols);
397     Write32(0); // tocoff
398     Write32(0); // ntoc
399     Write32(0); // modtaboff
400     Write32(0); // nmodtab
401     Write32(0); // extrefsymoff
402     Write32(0); // nextrefsyms
403     Write32(IndirectSymbolOffset);
404     Write32(NumIndirectSymbols);
405     Write32(0); // extreloff
406     Write32(0); // nextrel
407     Write32(0); // locreloff
408     Write32(0); // nlocrel
409
410     assert(OS.tell() - Start == macho::DysymtabLoadCommandSize);
411   }
412
413   void WriteNlist(MachSymbolData &MSD, const MCAsmLayout &Layout) {
414     MCSymbolData &Data = *MSD.SymbolData;
415     const MCSymbol &Symbol = Data.getSymbol();
416     uint8_t Type = 0;
417     uint16_t Flags = Data.getFlags();
418     uint32_t Address = 0;
419
420     // Set the N_TYPE bits. See <mach-o/nlist.h>.
421     //
422     // FIXME: Are the prebound or indirect fields possible here?
423     if (Symbol.isUndefined())
424       Type = macho::STT_Undefined;
425     else if (Symbol.isAbsolute())
426       Type = macho::STT_Absolute;
427     else
428       Type = macho::STT_Section;
429
430     // FIXME: Set STAB bits.
431
432     if (Data.isPrivateExtern())
433       Type |= macho::STF_PrivateExtern;
434
435     // Set external bit.
436     if (Data.isExternal() || Symbol.isUndefined())
437       Type |= macho::STF_External;
438
439     // Compute the symbol address.
440     if (Symbol.isDefined()) {
441       if (Symbol.isAbsolute()) {
442         Address = cast<MCConstantExpr>(Symbol.getVariableValue())->getValue();
443       } else {
444         Address = getSymbolAddress(&Data, Layout);
445       }
446     } else if (Data.isCommon()) {
447       // Common symbols are encoded with the size in the address
448       // field, and their alignment in the flags.
449       Address = Data.getCommonSize();
450
451       // Common alignment is packed into the 'desc' bits.
452       if (unsigned Align = Data.getCommonAlignment()) {
453         unsigned Log2Size = Log2_32(Align);
454         assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
455         if (Log2Size > 15)
456           report_fatal_error("invalid 'common' alignment '" +
457                             Twine(Align) + "'");
458         // FIXME: Keep this mask with the SymbolFlags enumeration.
459         Flags = (Flags & 0xF0FF) | (Log2Size << 8);
460       }
461     }
462
463     // struct nlist (12 bytes)
464
465     Write32(MSD.StringIndex);
466     Write8(Type);
467     Write8(MSD.SectionIndex);
468
469     // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
470     // value.
471     Write16(Flags);
472     if (Is64Bit)
473       Write64(Address);
474     else
475       Write32(Address);
476   }
477
478   // FIXME: We really need to improve the relocation validation. Basically, we
479   // want to implement a separate computation which evaluates the relocation
480   // entry as the linker would, and verifies that the resultant fixup value is
481   // exactly what the encoder wanted. This will catch several classes of
482   // problems:
483   //
484   //  - Relocation entry bugs, the two algorithms are unlikely to have the same
485   //    exact bug.
486   //
487   //  - Relaxation issues, where we forget to relax something.
488   //
489   //  - Input errors, where something cannot be correctly encoded. 'as' allows
490   //    these through in many cases.
491
492   void RecordX86_64Relocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
493                               const MCFragment *Fragment,
494                               const MCFixup &Fixup, MCValue Target,
495                               uint64_t &FixedValue) {
496     unsigned IsPCRel = isFixupKindPCRel(Fixup.getKind());
497     unsigned IsRIPRel = isFixupKindRIPRel(Fixup.getKind());
498     unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
499
500     // See <reloc.h>.
501     uint32_t FixupOffset =
502       Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
503     uint32_t FixupAddress =
504       getFragmentAddress(Fragment, Layout) + Fixup.getOffset();
505     int64_t Value = 0;
506     unsigned Index = 0;
507     unsigned IsExtern = 0;
508     unsigned Type = 0;
509
510     Value = Target.getConstant();
511
512     if (IsPCRel) {
513       // Compensate for the relocation offset, Darwin x86_64 relocations only
514       // have the addend and appear to have attempted to define it to be the
515       // actual expression addend without the PCrel bias. However, instructions
516       // with data following the relocation are not accomodated for (see comment
517       // below regarding SIGNED{1,2,4}), so it isn't exactly that either.
518       Value += 1LL << Log2Size;
519     }
520
521     if (Target.isAbsolute()) { // constant
522       // SymbolNum of 0 indicates the absolute section.
523       Type = macho::RIT_X86_64_Unsigned;
524       Index = 0;
525
526       // FIXME: I believe this is broken, I don't think the linker can
527       // understand it. I think it would require a local relocation, but I'm not
528       // sure if that would work either. The official way to get an absolute
529       // PCrel relocation is to use an absolute symbol (which we don't support
530       // yet).
531       if (IsPCRel) {
532         IsExtern = 1;
533         Type = macho::RIT_X86_64_Branch;
534       }
535     } else if (Target.getSymB()) { // A - B + constant
536       const MCSymbol *A = &Target.getSymA()->getSymbol();
537       MCSymbolData &A_SD = Asm.getSymbolData(*A);
538       const MCSymbolData *A_Base = Asm.getAtom(&A_SD);
539
540       const MCSymbol *B = &Target.getSymB()->getSymbol();
541       MCSymbolData &B_SD = Asm.getSymbolData(*B);
542       const MCSymbolData *B_Base = Asm.getAtom(&B_SD);
543
544       // Neither symbol can be modified.
545       if (Target.getSymA()->getKind() != MCSymbolRefExpr::VK_None ||
546           Target.getSymB()->getKind() != MCSymbolRefExpr::VK_None)
547         report_fatal_error("unsupported relocation of modified symbol");
548
549       // We don't support PCrel relocations of differences. Darwin 'as' doesn't
550       // implement most of these correctly.
551       if (IsPCRel)
552         report_fatal_error("unsupported pc-relative relocation of difference");
553
554       // The support for the situation where one or both of the symbols would
555       // require a local relocation is handled just like if the symbols were
556       // external.  This is certainly used in the case of debug sections where
557       // the section has only temporary symbols and thus the symbols don't have
558       // base symbols.  This is encoded using the section ordinal and
559       // non-extern relocation entries.
560
561       // Darwin 'as' doesn't emit correct relocations for this (it ends up with
562       // a single SIGNED relocation); reject it for now.  Except the case where
563       // both symbols don't have a base, equal but both NULL.
564       if (A_Base == B_Base && A_Base)
565         report_fatal_error("unsupported relocation with identical base");
566
567       Value += getSymbolAddress(&A_SD, Layout) -
568         (A_Base == NULL ? 0 : getSymbolAddress(A_Base, Layout));
569       Value -= getSymbolAddress(&B_SD, Layout) -
570         (B_Base == NULL ? 0 : getSymbolAddress(B_Base, Layout));
571
572       if (A_Base) {
573         Index = A_Base->getIndex();
574         IsExtern = 1;
575       }
576       else {
577         Index = A_SD.getFragment()->getParent()->getOrdinal() + 1;
578         IsExtern = 0;
579       }
580       Type = macho::RIT_X86_64_Unsigned;
581
582       macho::RelocationEntry MRE;
583       MRE.Word0 = FixupOffset;
584       MRE.Word1 = ((Index     <<  0) |
585                    (IsPCRel   << 24) |
586                    (Log2Size  << 25) |
587                    (IsExtern  << 27) |
588                    (Type      << 28));
589       Relocations[Fragment->getParent()].push_back(MRE);
590
591       if (B_Base) {
592         Index = B_Base->getIndex();
593         IsExtern = 1;
594       }
595       else {
596         Index = B_SD.getFragment()->getParent()->getOrdinal() + 1;
597         IsExtern = 0;
598       }
599       Type = macho::RIT_X86_64_Subtractor;
600     } else {
601       const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
602       MCSymbolData &SD = Asm.getSymbolData(*Symbol);
603       const MCSymbolData *Base = Asm.getAtom(&SD);
604
605       // Relocations inside debug sections always use local relocations when
606       // possible. This seems to be done because the debugger doesn't fully
607       // understand x86_64 relocation entries, and expects to find values that
608       // have already been fixed up.
609       if (Symbol->isInSection()) {
610         const MCSectionMachO &Section = static_cast<const MCSectionMachO&>(
611           Fragment->getParent()->getSection());
612         if (Section.hasAttribute(MCSectionMachO::S_ATTR_DEBUG))
613           Base = 0;
614       }
615
616       // x86_64 almost always uses external relocations, except when there is no
617       // symbol to use as a base address (a local symbol with no preceeding
618       // non-local symbol).
619       if (Base) {
620         Index = Base->getIndex();
621         IsExtern = 1;
622
623         // Add the local offset, if needed.
624         if (Base != &SD)
625           Value += Layout.getSymbolOffset(&SD) - Layout.getSymbolOffset(Base);
626       } else if (Symbol->isInSection()) {
627         // The index is the section ordinal (1-based).
628         Index = SD.getFragment()->getParent()->getOrdinal() + 1;
629         IsExtern = 0;
630         Value += getSymbolAddress(&SD, Layout);
631
632         if (IsPCRel)
633           Value -= FixupAddress + (1 << Log2Size);
634       } else if (Symbol->isVariable()) {
635         const MCExpr *Value = Symbol->getVariableValue();
636         int64_t Res;
637         bool isAbs = Value->EvaluateAsAbsolute(Res, Layout, SectionAddress);
638         if (isAbs) {
639           FixedValue = Res;
640           return;
641         } else {
642           report_fatal_error("unsupported relocation of variable '" +
643                              Symbol->getName() + "'");
644         }
645       } else {
646         report_fatal_error("unsupported relocation of undefined symbol '" +
647                            Symbol->getName() + "'");
648       }
649
650       MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
651       if (IsPCRel) {
652         if (IsRIPRel) {
653           if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
654             // x86_64 distinguishes movq foo@GOTPCREL so that the linker can
655             // rewrite the movq to an leaq at link time if the symbol ends up in
656             // the same linkage unit.
657             if (unsigned(Fixup.getKind()) == X86::reloc_riprel_4byte_movq_load)
658               Type = macho::RIT_X86_64_GOTLoad;
659             else
660               Type = macho::RIT_X86_64_GOT;
661           }  else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
662             Type = macho::RIT_X86_64_TLV;
663           }  else if (Modifier != MCSymbolRefExpr::VK_None) {
664             report_fatal_error("unsupported symbol modifier in relocation");
665           } else {
666             Type = macho::RIT_X86_64_Signed;
667
668             // The Darwin x86_64 relocation format has a problem where it cannot
669             // encode an address (L<foo> + <constant>) which is outside the atom
670             // containing L<foo>. Generally, this shouldn't occur but it does
671             // happen when we have a RIPrel instruction with data following the
672             // relocation entry (e.g., movb $012, L0(%rip)). Even with the PCrel
673             // adjustment Darwin x86_64 uses, the offset is still negative and
674             // the linker has no way to recognize this.
675             //
676             // To work around this, Darwin uses several special relocation types
677             // to indicate the offsets. However, the specification or
678             // implementation of these seems to also be incomplete; they should
679             // adjust the addend as well based on the actual encoded instruction
680             // (the additional bias), but instead appear to just look at the
681             // final offset.
682             switch (-(Target.getConstant() + (1LL << Log2Size))) {
683             case 1: Type = macho::RIT_X86_64_Signed1; break;
684             case 2: Type = macho::RIT_X86_64_Signed2; break;
685             case 4: Type = macho::RIT_X86_64_Signed4; break;
686             }
687           }
688         } else {
689           if (Modifier != MCSymbolRefExpr::VK_None)
690             report_fatal_error("unsupported symbol modifier in branch "
691                               "relocation");
692
693           Type = macho::RIT_X86_64_Branch;
694         }
695       } else {
696         if (Modifier == MCSymbolRefExpr::VK_GOT) {
697           Type = macho::RIT_X86_64_GOT;
698         } else if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
699           // GOTPCREL is allowed as a modifier on non-PCrel instructions, in
700           // which case all we do is set the PCrel bit in the relocation entry;
701           // this is used with exception handling, for example. The source is
702           // required to include any necessary offset directly.
703           Type = macho::RIT_X86_64_GOT;
704           IsPCRel = 1;
705         } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
706           report_fatal_error("TLVP symbol modifier should have been rip-rel");
707         } else if (Modifier != MCSymbolRefExpr::VK_None)
708           report_fatal_error("unsupported symbol modifier in relocation");
709         else
710           Type = macho::RIT_X86_64_Unsigned;
711       }
712     }
713
714     // x86_64 always writes custom values into the fixups.
715     FixedValue = Value;
716
717     // struct relocation_info (8 bytes)
718     macho::RelocationEntry MRE;
719     MRE.Word0 = FixupOffset;
720     MRE.Word1 = ((Index     <<  0) |
721                  (IsPCRel   << 24) |
722                  (Log2Size  << 25) |
723                  (IsExtern  << 27) |
724                  (Type      << 28));
725     Relocations[Fragment->getParent()].push_back(MRE);
726   }
727
728   void RecordScatteredRelocation(const MCAssembler &Asm,
729                                  const MCAsmLayout &Layout,
730                                  const MCFragment *Fragment,
731                                  const MCFixup &Fixup, MCValue Target,
732                                  uint64_t &FixedValue) {
733     uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
734     unsigned IsPCRel = isFixupKindPCRel(Fixup.getKind());
735     unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
736     unsigned Type = macho::RIT_Vanilla;
737
738     // See <reloc.h>.
739     const MCSymbol *A = &Target.getSymA()->getSymbol();
740     MCSymbolData *A_SD = &Asm.getSymbolData(*A);
741
742     if (!A_SD->getFragment())
743       report_fatal_error("symbol '" + A->getName() +
744                         "' can not be undefined in a subtraction expression");
745
746     uint32_t Value = getSymbolAddress(A_SD, Layout);
747     uint64_t SecAddr = getSectionAddress(A_SD->getFragment()->getParent());
748     FixedValue += SecAddr;
749     uint32_t Value2 = 0;
750
751     if (const MCSymbolRefExpr *B = Target.getSymB()) {
752       MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
753
754       if (!B_SD->getFragment())
755         report_fatal_error("symbol '" + B->getSymbol().getName() +
756                           "' can not be undefined in a subtraction expression");
757
758       // Select the appropriate difference relocation type.
759       //
760       // Note that there is no longer any semantic difference between these two
761       // relocation types from the linkers point of view, this is done solely
762       // for pedantic compatibility with 'as'.
763       Type = A_SD->isExternal() ? macho::RIT_Difference :
764         macho::RIT_LocalDifference;
765       Value2 = getSymbolAddress(B_SD, Layout);
766       FixedValue -= getSectionAddress(B_SD->getFragment()->getParent());
767     }
768
769     // Relocations are written out in reverse order, so the PAIR comes first.
770     if (Type == macho::RIT_Difference || Type == macho::RIT_LocalDifference) {
771       macho::RelocationEntry MRE;
772       MRE.Word0 = ((0         <<  0) |
773                    (macho::RIT_Pair  << 24) |
774                    (Log2Size  << 28) |
775                    (IsPCRel   << 30) |
776                    macho::RF_Scattered);
777       MRE.Word1 = Value2;
778       Relocations[Fragment->getParent()].push_back(MRE);
779     }
780
781     macho::RelocationEntry MRE;
782     MRE.Word0 = ((FixupOffset <<  0) |
783                  (Type        << 24) |
784                  (Log2Size    << 28) |
785                  (IsPCRel     << 30) |
786                  macho::RF_Scattered);
787     MRE.Word1 = Value;
788     Relocations[Fragment->getParent()].push_back(MRE);
789   }
790
791   void RecordTLVPRelocation(const MCAssembler &Asm,
792                             const MCAsmLayout &Layout,
793                             const MCFragment *Fragment,
794                             const MCFixup &Fixup, MCValue Target,
795                             uint64_t &FixedValue) {
796     assert(Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP &&
797            !Is64Bit &&
798            "Should only be called with a 32-bit TLVP relocation!");
799
800     unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
801     uint32_t Value = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
802     unsigned IsPCRel = 0;
803
804     // Get the symbol data.
805     MCSymbolData *SD_A = &Asm.getSymbolData(Target.getSymA()->getSymbol());
806     unsigned Index = SD_A->getIndex();
807
808     // We're only going to have a second symbol in pic mode and it'll be a
809     // subtraction from the picbase. For 32-bit pic the addend is the difference
810     // between the picbase and the next address.  For 32-bit static the addend
811     // is zero.
812     if (Target.getSymB()) {
813       // If this is a subtraction then we're pcrel.
814       uint32_t FixupAddress =
815         getFragmentAddress(Fragment, Layout) + Fixup.getOffset();
816       MCSymbolData *SD_B = &Asm.getSymbolData(Target.getSymB()->getSymbol());
817       IsPCRel = 1;
818       FixedValue = (FixupAddress - getSymbolAddress(SD_B, Layout) +
819                     Target.getConstant());
820       FixedValue += 1ULL << Log2Size;
821     } else {
822       FixedValue = 0;
823     }
824
825     // struct relocation_info (8 bytes)
826     macho::RelocationEntry MRE;
827     MRE.Word0 = Value;
828     MRE.Word1 = ((Index     <<  0) |
829                  (IsPCRel   << 24) |
830                  (Log2Size  << 25) |
831                  (1         << 27) | // Extern
832                  (macho::RIT_TLV   << 28)); // Type
833     Relocations[Fragment->getParent()].push_back(MRE);
834   }
835
836   void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
837                         const MCFragment *Fragment, const MCFixup &Fixup,
838                         MCValue Target, uint64_t &FixedValue) {
839     if (Is64Bit) {
840       RecordX86_64Relocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
841       return;
842     }
843
844     unsigned IsPCRel = isFixupKindPCRel(Fixup.getKind());
845     unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
846
847     // If this is a 32-bit TLVP reloc it's handled a bit differently.
848     if (Target.getSymA() &&
849         Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP) {
850       RecordTLVPRelocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
851       return;
852     }
853
854     // If this is a difference or a defined symbol plus an offset, then we need
855     // a scattered relocation entry.
856     // Differences always require scattered relocations.
857     if (Target.getSymB())
858         return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
859                                          Target, FixedValue);
860
861     // Get the symbol data, if any.
862     MCSymbolData *SD = 0;
863     if (Target.getSymA())
864       SD = &Asm.getSymbolData(Target.getSymA()->getSymbol());
865
866     // If this is an internal relocation with an offset, it also needs a
867     // scattered relocation entry.
868     uint32_t Offset = Target.getConstant();
869     if (IsPCRel)
870       Offset += 1 << Log2Size;
871     if (Offset && SD && !doesSymbolRequireExternRelocation(SD))
872       return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
873                                        Target, FixedValue);
874
875     // See <reloc.h>.
876     uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
877     unsigned Index = 0;
878     unsigned IsExtern = 0;
879     unsigned Type = 0;
880
881     if (Target.isAbsolute()) { // constant
882       // SymbolNum of 0 indicates the absolute section.
883       //
884       // FIXME: Currently, these are never generated (see code below). I cannot
885       // find a case where they are actually emitted.
886       Type = macho::RIT_Vanilla;
887     } else if (SD->getSymbol().isVariable()) {
888       const MCExpr *Value = SD->getSymbol().getVariableValue();
889       int64_t Res;
890       bool isAbs = Value->EvaluateAsAbsolute(Res, Layout, SectionAddress);
891       if (isAbs) {
892         FixedValue = Res;
893         return;
894       } else {
895         report_fatal_error("unsupported relocation of variable '" +
896                            SD->getSymbol().getName() + "'");
897       }
898     } else {
899       // Check whether we need an external or internal relocation.
900       if (doesSymbolRequireExternRelocation(SD)) {
901         IsExtern = 1;
902         Index = SD->getIndex();
903         // For external relocations, make sure to offset the fixup value to
904         // compensate for the addend of the symbol address, if it was
905         // undefined. This occurs with weak definitions, for example.
906         if (!SD->Symbol->isUndefined())
907           FixedValue -= Layout.getSymbolOffset(SD);
908       } else {
909         // The index is the section ordinal (1-based).
910         Index = SD->getFragment()->getParent()->getOrdinal() + 1;
911         FixedValue += getSectionAddress(SD->getFragment()->getParent());
912       }
913       if (IsPCRel)
914         FixedValue -= getSectionAddress(Fragment->getParent());
915
916       Type = macho::RIT_Vanilla;
917     }
918
919     // struct relocation_info (8 bytes)
920     macho::RelocationEntry MRE;
921     MRE.Word0 = FixupOffset;
922     MRE.Word1 = ((Index     <<  0) |
923                  (IsPCRel   << 24) |
924                  (Log2Size  << 25) |
925                  (IsExtern  << 27) |
926                  (Type      << 28));
927     Relocations[Fragment->getParent()].push_back(MRE);
928   }
929
930   void BindIndirectSymbols(MCAssembler &Asm) {
931     // This is the point where 'as' creates actual symbols for indirect symbols
932     // (in the following two passes). It would be easier for us to do this
933     // sooner when we see the attribute, but that makes getting the order in the
934     // symbol table much more complicated than it is worth.
935     //
936     // FIXME: Revisit this when the dust settles.
937
938     // Bind non lazy symbol pointers first.
939     unsigned IndirectIndex = 0;
940     for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
941            ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
942       const MCSectionMachO &Section =
943         cast<MCSectionMachO>(it->SectionData->getSection());
944
945       if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
946         continue;
947
948       // Initialize the section indirect symbol base, if necessary.
949       if (!IndirectSymBase.count(it->SectionData))
950         IndirectSymBase[it->SectionData] = IndirectIndex;
951
952       Asm.getOrCreateSymbolData(*it->Symbol);
953     }
954
955     // Then lazy symbol pointers and symbol stubs.
956     IndirectIndex = 0;
957     for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
958            ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
959       const MCSectionMachO &Section =
960         cast<MCSectionMachO>(it->SectionData->getSection());
961
962       if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
963           Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
964         continue;
965
966       // Initialize the section indirect symbol base, if necessary.
967       if (!IndirectSymBase.count(it->SectionData))
968         IndirectSymBase[it->SectionData] = IndirectIndex;
969
970       // Set the symbol type to undefined lazy, but only on construction.
971       //
972       // FIXME: Do not hardcode.
973       bool Created;
974       MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
975       if (Created)
976         Entry.setFlags(Entry.getFlags() | 0x0001);
977     }
978   }
979
980   /// ComputeSymbolTable - Compute the symbol table data
981   ///
982   /// \param StringTable [out] - The string table data.
983   /// \param StringIndexMap [out] - Map from symbol names to offsets in the
984   /// string table.
985   void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
986                           std::vector<MachSymbolData> &LocalSymbolData,
987                           std::vector<MachSymbolData> &ExternalSymbolData,
988                           std::vector<MachSymbolData> &UndefinedSymbolData) {
989     // Build section lookup table.
990     DenseMap<const MCSection*, uint8_t> SectionIndexMap;
991     unsigned Index = 1;
992     for (MCAssembler::iterator it = Asm.begin(),
993            ie = Asm.end(); it != ie; ++it, ++Index)
994       SectionIndexMap[&it->getSection()] = Index;
995     assert(Index <= 256 && "Too many sections!");
996
997     // Index 0 is always the empty string.
998     StringMap<uint64_t> StringIndexMap;
999     StringTable += '\x00';
1000
1001     // Build the symbol arrays and the string table, but only for non-local
1002     // symbols.
1003     //
1004     // The particular order that we collect the symbols and create the string
1005     // table, then sort the symbols is chosen to match 'as'. Even though it
1006     // doesn't matter for correctness, this is important for letting us diff .o
1007     // files.
1008     for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
1009            ie = Asm.symbol_end(); it != ie; ++it) {
1010       const MCSymbol &Symbol = it->getSymbol();
1011
1012       // Ignore non-linker visible symbols.
1013       if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
1014         continue;
1015
1016       if (!it->isExternal() && !Symbol.isUndefined())
1017         continue;
1018
1019       uint64_t &Entry = StringIndexMap[Symbol.getName()];
1020       if (!Entry) {
1021         Entry = StringTable.size();
1022         StringTable += Symbol.getName();
1023         StringTable += '\x00';
1024       }
1025
1026       MachSymbolData MSD;
1027       MSD.SymbolData = it;
1028       MSD.StringIndex = Entry;
1029
1030       if (Symbol.isUndefined()) {
1031         MSD.SectionIndex = 0;
1032         UndefinedSymbolData.push_back(MSD);
1033       } else if (Symbol.isAbsolute()) {
1034         MSD.SectionIndex = 0;
1035         ExternalSymbolData.push_back(MSD);
1036       } else {
1037         MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1038         assert(MSD.SectionIndex && "Invalid section index!");
1039         ExternalSymbolData.push_back(MSD);
1040       }
1041     }
1042
1043     // Now add the data for local symbols.
1044     for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
1045            ie = Asm.symbol_end(); it != ie; ++it) {
1046       const MCSymbol &Symbol = it->getSymbol();
1047
1048       // Ignore non-linker visible symbols.
1049       if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
1050         continue;
1051
1052       if (it->isExternal() || Symbol.isUndefined())
1053         continue;
1054
1055       uint64_t &Entry = StringIndexMap[Symbol.getName()];
1056       if (!Entry) {
1057         Entry = StringTable.size();
1058         StringTable += Symbol.getName();
1059         StringTable += '\x00';
1060       }
1061
1062       MachSymbolData MSD;
1063       MSD.SymbolData = it;
1064       MSD.StringIndex = Entry;
1065
1066       if (Symbol.isAbsolute()) {
1067         MSD.SectionIndex = 0;
1068         LocalSymbolData.push_back(MSD);
1069       } else {
1070         MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1071         assert(MSD.SectionIndex && "Invalid section index!");
1072         LocalSymbolData.push_back(MSD);
1073       }
1074     }
1075
1076     // External and undefined symbols are required to be in lexicographic order.
1077     std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1078     std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1079
1080     // Set the symbol indices.
1081     Index = 0;
1082     for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1083       LocalSymbolData[i].SymbolData->setIndex(Index++);
1084     for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1085       ExternalSymbolData[i].SymbolData->setIndex(Index++);
1086     for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1087       UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1088
1089     // The string table is padded to a multiple of 4.
1090     while (StringTable.size() % 4)
1091       StringTable += '\x00';
1092   }
1093
1094   void computeSectionAddresses(const MCAssembler &Asm,
1095                                const MCAsmLayout &Layout) {
1096     uint64_t StartAddress = 0;
1097     const SmallVectorImpl<MCSectionData*> &Order = Layout.getSectionOrder();
1098     for (int i = 0, n = Order.size(); i != n ; ++i) {
1099       const MCSectionData *SD = Order[i];
1100       StartAddress = RoundUpToAlignment(StartAddress, SD->getAlignment());
1101       SectionAddress[SD] = StartAddress;
1102       StartAddress += Layout.getSectionAddressSize(SD);
1103       // Explicitly pad the section to match the alignment requirements of the
1104       // following one. This is for 'gas' compatibility, it shouldn't
1105       /// strictly be necessary.
1106       StartAddress += getPaddingSize(SD, Layout);
1107     }
1108   }
1109
1110   void ExecutePostLayoutBinding(MCAssembler &Asm, const MCAsmLayout &Layout) {
1111     computeSectionAddresses(Asm, Layout);
1112
1113     // Create symbol data for any indirect symbols.
1114     BindIndirectSymbols(Asm);
1115
1116     // Compute symbol table information and bind symbol indices.
1117     ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
1118                        UndefinedSymbolData);
1119   }
1120
1121
1122   bool IsFixupFullyResolved(const MCAssembler &Asm,
1123                             const MCValue Target,
1124                             bool IsPCRel,
1125                             const MCFragment *DF) const {
1126     // If we aren't using scattered symbols, the fixup is fully resolved.
1127     if (!Asm.getBackend().hasScatteredSymbols())
1128       return true;
1129
1130     // Otherwise, determine whether this value is actually resolved; scattering
1131     // may cause atoms to move.
1132
1133     // Check if we are using the "simple" resolution algorithm (e.g.,
1134     // i386).
1135     if (!Asm.getBackend().hasReliableSymbolDifference()) {
1136       const MCSection *BaseSection = 0;
1137       if (IsPCRel)
1138         BaseSection = &DF->getParent()->getSection();
1139
1140       return isScatteredFixupFullyResolvedSimple(Asm, Target, BaseSection);
1141     }
1142
1143     // Otherwise, compute the proper answer as reliably as possible.
1144
1145     // If this is a PCrel relocation, find the base atom (identified by its
1146     // symbol) that the fixup value is relative to.
1147     const MCSymbolData *BaseSymbol = 0;
1148     if (IsPCRel) {
1149       BaseSymbol = DF->getAtom();
1150       if (!BaseSymbol)
1151         return false;
1152     }
1153
1154     return isScatteredFixupFullyResolved(Asm, Target, BaseSymbol);
1155   }
1156
1157   void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) {
1158     unsigned NumSections = Asm.size();
1159
1160     // The section data starts after the header, the segment load command (and
1161     // section headers) and the symbol table.
1162     unsigned NumLoadCommands = 1;
1163     uint64_t LoadCommandsSize = Is64Bit ?
1164       macho::SegmentLoadCommand64Size + NumSections * macho::Section64Size :
1165       macho::SegmentLoadCommand32Size + NumSections * macho::Section32Size;
1166
1167     // Add the symbol table load command sizes, if used.
1168     unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
1169       UndefinedSymbolData.size();
1170     if (NumSymbols) {
1171       NumLoadCommands += 2;
1172       LoadCommandsSize += (macho::SymtabLoadCommandSize +
1173                            macho::DysymtabLoadCommandSize);
1174     }
1175
1176     // Compute the total size of the section data, as well as its file size and
1177     // vm size.
1178     uint64_t SectionDataStart = (Is64Bit ? macho::Header64Size :
1179                                  macho::Header32Size) + LoadCommandsSize;
1180     uint64_t SectionDataSize = 0;
1181     uint64_t SectionDataFileSize = 0;
1182     uint64_t VMSize = 0;
1183     for (MCAssembler::const_iterator it = Asm.begin(),
1184            ie = Asm.end(); it != ie; ++it) {
1185       const MCSectionData &SD = *it;
1186       uint64_t Address = getSectionAddress(&SD);
1187       uint64_t Size = Layout.getSectionAddressSize(&SD);
1188       uint64_t FileSize = Layout.getSectionFileSize(&SD);
1189       FileSize += getPaddingSize(&SD, Layout);
1190
1191       VMSize = std::max(VMSize, Address + Size);
1192
1193       if (SD.getSection().isVirtualSection())
1194         continue;
1195
1196       SectionDataSize = std::max(SectionDataSize, Address + Size);
1197       SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
1198     }
1199
1200     // The section data is padded to 4 bytes.
1201     //
1202     // FIXME: Is this machine dependent?
1203     unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
1204     SectionDataFileSize += SectionDataPadding;
1205
1206     // Write the prolog, starting with the header and load command...
1207     WriteHeader(NumLoadCommands, LoadCommandsSize,
1208                 Asm.getSubsectionsViaSymbols());
1209     WriteSegmentLoadCommand(NumSections, VMSize,
1210                             SectionDataStart, SectionDataSize);
1211
1212     // ... and then the section headers.
1213     uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
1214     for (MCAssembler::const_iterator it = Asm.begin(),
1215            ie = Asm.end(); it != ie; ++it) {
1216       std::vector<macho::RelocationEntry> &Relocs = Relocations[it];
1217       unsigned NumRelocs = Relocs.size();
1218       uint64_t SectionStart = SectionDataStart + getSectionAddress(it);
1219       WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
1220       RelocTableEnd += NumRelocs * macho::RelocationInfoSize;
1221     }
1222
1223     // Write the symbol table load command, if used.
1224     if (NumSymbols) {
1225       unsigned FirstLocalSymbol = 0;
1226       unsigned NumLocalSymbols = LocalSymbolData.size();
1227       unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
1228       unsigned NumExternalSymbols = ExternalSymbolData.size();
1229       unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
1230       unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
1231       unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
1232       unsigned NumSymTabSymbols =
1233         NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
1234       uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
1235       uint64_t IndirectSymbolOffset = 0;
1236
1237       // If used, the indirect symbols are written after the section data.
1238       if (NumIndirectSymbols)
1239         IndirectSymbolOffset = RelocTableEnd;
1240
1241       // The symbol table is written after the indirect symbol data.
1242       uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
1243
1244       // The string table is written after symbol table.
1245       uint64_t StringTableOffset =
1246         SymbolTableOffset + NumSymTabSymbols * (Is64Bit ? macho::Nlist64Size :
1247                                                 macho::Nlist32Size);
1248       WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
1249                              StringTableOffset, StringTable.size());
1250
1251       WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
1252                                FirstExternalSymbol, NumExternalSymbols,
1253                                FirstUndefinedSymbol, NumUndefinedSymbols,
1254                                IndirectSymbolOffset, NumIndirectSymbols);
1255     }
1256
1257     // Write the actual section data.
1258     for (MCAssembler::const_iterator it = Asm.begin(),
1259            ie = Asm.end(); it != ie; ++it) {
1260       Asm.WriteSectionData(it, Layout, this);
1261
1262       uint64_t Pad = getPaddingSize(it, Layout);
1263       for (unsigned int i = 0; i < Pad; ++i)
1264         Write8(0);
1265     }
1266
1267     // Write the extra padding.
1268     WriteZeros(SectionDataPadding);
1269
1270     // Write the relocation entries.
1271     for (MCAssembler::const_iterator it = Asm.begin(),
1272            ie = Asm.end(); it != ie; ++it) {
1273       // Write the section relocation entries, in reverse order to match 'as'
1274       // (approximately, the exact algorithm is more complicated than this).
1275       std::vector<macho::RelocationEntry> &Relocs = Relocations[it];
1276       for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1277         Write32(Relocs[e - i - 1].Word0);
1278         Write32(Relocs[e - i - 1].Word1);
1279       }
1280     }
1281
1282     // Write the symbol table data, if used.
1283     if (NumSymbols) {
1284       // Write the indirect symbol entries.
1285       for (MCAssembler::const_indirect_symbol_iterator
1286              it = Asm.indirect_symbol_begin(),
1287              ie = Asm.indirect_symbol_end(); it != ie; ++it) {
1288         // Indirect symbols in the non lazy symbol pointer section have some
1289         // special handling.
1290         const MCSectionMachO &Section =
1291           static_cast<const MCSectionMachO&>(it->SectionData->getSection());
1292         if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
1293           // If this symbol is defined and internal, mark it as such.
1294           if (it->Symbol->isDefined() &&
1295               !Asm.getSymbolData(*it->Symbol).isExternal()) {
1296             uint32_t Flags = macho::ISF_Local;
1297             if (it->Symbol->isAbsolute())
1298               Flags |= macho::ISF_Absolute;
1299             Write32(Flags);
1300             continue;
1301           }
1302         }
1303
1304         Write32(Asm.getSymbolData(*it->Symbol).getIndex());
1305       }
1306
1307       // FIXME: Check that offsets match computed ones.
1308
1309       // Write the symbol table entries.
1310       for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1311         WriteNlist(LocalSymbolData[i], Layout);
1312       for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1313         WriteNlist(ExternalSymbolData[i], Layout);
1314       for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1315         WriteNlist(UndefinedSymbolData[i], Layout);
1316
1317       // Write the string table.
1318       OS << StringTable.str();
1319     }
1320   }
1321 };
1322
1323 }
1324
1325 MCObjectWriter *llvm::createMachObjectWriter(raw_ostream &OS, bool is64Bit,
1326                                              uint32_t CPUType,
1327                                              uint32_t CPUSubtype,
1328                                              bool IsLittleEndian) {
1329   return new MachObjectWriter(OS, is64Bit, CPUType, CPUSubtype, IsLittleEndian);
1330 }