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