MC/Mach-O: Resolve a FIXME; these relocation types are no longer semanticaly different.
[oota-llvm.git] / lib / MC / MCAssembler.cpp
1 //===- lib/MC/MCAssembler.cpp - Assembler Backend Implementation ----------===//
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 #define DEBUG_TYPE "assembler"
11 #include "llvm/MC/MCAssembler.h"
12 #include "llvm/MC/MCExpr.h"
13 #include "llvm/MC/MCSectionMachO.h"
14 #include "llvm/MC/MCSymbol.h"
15 #include "llvm/MC/MCValue.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/MachO.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/Support/Debug.h"
26
27 // FIXME: Gross.
28 #include "../Target/X86/X86FixupKinds.h"
29
30 #include <vector>
31 using namespace llvm;
32
33 class MachObjectWriter;
34
35 STATISTIC(EmittedFragments, "Number of emitted assembler fragments");
36
37 // FIXME FIXME FIXME: There are number of places in this file where we convert
38 // what is a 64-bit assembler value used for computation into a value in the
39 // object file, which may truncate it. We should detect that truncation where
40 // invalid and report errors back.
41
42 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
43                           MachObjectWriter &MOW);
44
45 static uint64_t WriteNopData(uint64_t Count, MachObjectWriter &MOW);
46
47 /// isVirtualSection - Check if this is a section which does not actually exist
48 /// in the object file.
49 static bool isVirtualSection(const MCSection &Section) {
50   // FIXME: Lame.
51   const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
52   unsigned Type = SMO.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
53   return (Type == MCSectionMachO::S_ZEROFILL);
54 }
55
56 static unsigned getFixupKindLog2Size(unsigned Kind) {
57   switch (Kind) {
58   default: llvm_unreachable("invalid fixup kind!");
59   case X86::reloc_pcrel_1byte:
60   case FK_Data_1: return 0;
61   case FK_Data_2: return 1;
62   case X86::reloc_pcrel_4byte:
63   case X86::reloc_riprel_4byte:
64   case FK_Data_4: return 2;
65   case FK_Data_8: return 3;
66   }
67 }
68
69 static bool isFixupKindPCRel(unsigned Kind) {
70   switch (Kind) {
71   default:
72     return false;
73   case X86::reloc_pcrel_1byte:
74   case X86::reloc_pcrel_4byte:
75   case X86::reloc_riprel_4byte:
76     return true;
77   }
78 }
79
80 class MachObjectWriter {
81   // See <mach-o/loader.h>.
82   enum {
83     Header_Magic32 = 0xFEEDFACE,
84     Header_Magic64 = 0xFEEDFACF
85   };
86
87   static const unsigned Header32Size = 28;
88   static const unsigned Header64Size = 32;
89   static const unsigned SegmentLoadCommand32Size = 56;
90   static const unsigned Section32Size = 68;
91   static const unsigned SymtabLoadCommandSize = 24;
92   static const unsigned DysymtabLoadCommandSize = 80;
93   static const unsigned Nlist32Size = 12;
94   static const unsigned RelocationInfoSize = 8;
95
96   enum HeaderFileType {
97     HFT_Object = 0x1
98   };
99
100   enum HeaderFlags {
101     HF_SubsectionsViaSymbols = 0x2000
102   };
103
104   enum LoadCommandType {
105     LCT_Segment = 0x1,
106     LCT_Symtab = 0x2,
107     LCT_Dysymtab = 0xb
108   };
109
110   // See <mach-o/nlist.h>.
111   enum SymbolTypeType {
112     STT_Undefined = 0x00,
113     STT_Absolute  = 0x02,
114     STT_Section   = 0x0e
115   };
116
117   enum SymbolTypeFlags {
118     // If any of these bits are set, then the entry is a stab entry number (see
119     // <mach-o/stab.h>. Otherwise the other masks apply.
120     STF_StabsEntryMask = 0xe0,
121
122     STF_TypeMask       = 0x0e,
123     STF_External       = 0x01,
124     STF_PrivateExtern  = 0x10
125   };
126
127   /// IndirectSymbolFlags - Flags for encoding special values in the indirect
128   /// symbol entry.
129   enum IndirectSymbolFlags {
130     ISF_Local    = 0x80000000,
131     ISF_Absolute = 0x40000000
132   };
133
134   /// RelocationFlags - Special flags for addresses.
135   enum RelocationFlags {
136     RF_Scattered = 0x80000000
137   };
138
139   enum RelocationInfoType {
140     RIT_Vanilla             = 0,
141     RIT_Pair                = 1,
142     RIT_Difference          = 2,
143     RIT_PreboundLazyPointer = 3,
144     RIT_LocalDifference     = 4
145   };
146
147   /// MachSymbolData - Helper struct for containing some precomputed information
148   /// on symbols.
149   struct MachSymbolData {
150     MCSymbolData *SymbolData;
151     uint64_t StringIndex;
152     uint8_t SectionIndex;
153
154     // Support lexicographic sorting.
155     bool operator<(const MachSymbolData &RHS) const {
156       const std::string &Name = SymbolData->getSymbol().getName();
157       return Name < RHS.SymbolData->getSymbol().getName();
158     }
159   };
160
161   raw_ostream &OS;
162   bool IsLSB;
163
164 public:
165   MachObjectWriter(raw_ostream &_OS, bool _IsLSB = true)
166     : OS(_OS), IsLSB(_IsLSB) {
167   }
168
169   /// @name Helper Methods
170   /// @{
171
172   void Write8(uint8_t Value) {
173     OS << char(Value);
174   }
175
176   void Write16(uint16_t Value) {
177     if (IsLSB) {
178       Write8(uint8_t(Value >> 0));
179       Write8(uint8_t(Value >> 8));
180     } else {
181       Write8(uint8_t(Value >> 8));
182       Write8(uint8_t(Value >> 0));
183     }
184   }
185
186   void Write32(uint32_t Value) {
187     if (IsLSB) {
188       Write16(uint16_t(Value >> 0));
189       Write16(uint16_t(Value >> 16));
190     } else {
191       Write16(uint16_t(Value >> 16));
192       Write16(uint16_t(Value >> 0));
193     }
194   }
195
196   void Write64(uint64_t Value) {
197     if (IsLSB) {
198       Write32(uint32_t(Value >> 0));
199       Write32(uint32_t(Value >> 32));
200     } else {
201       Write32(uint32_t(Value >> 32));
202       Write32(uint32_t(Value >> 0));
203     }
204   }
205
206   void WriteZeros(unsigned N) {
207     const char Zeros[16] = { 0 };
208
209     for (unsigned i = 0, e = N / 16; i != e; ++i)
210       OS << StringRef(Zeros, 16);
211
212     OS << StringRef(Zeros, N % 16);
213   }
214
215   void WriteString(StringRef Str, unsigned ZeroFillSize = 0) {
216     OS << Str;
217     if (ZeroFillSize)
218       WriteZeros(ZeroFillSize - Str.size());
219   }
220
221   /// @}
222
223   void WriteHeader32(unsigned NumLoadCommands, unsigned LoadCommandsSize,
224                      bool SubsectionsViaSymbols) {
225     uint32_t Flags = 0;
226
227     if (SubsectionsViaSymbols)
228       Flags |= HF_SubsectionsViaSymbols;
229
230     // struct mach_header (28 bytes)
231
232     uint64_t Start = OS.tell();
233     (void) Start;
234
235     Write32(Header_Magic32);
236
237     // FIXME: Support cputype.
238     Write32(MachO::CPUTypeI386);
239     // FIXME: Support cpusubtype.
240     Write32(MachO::CPUSubType_I386_ALL);
241     Write32(HFT_Object);
242     Write32(NumLoadCommands);    // Object files have a single load command, the
243                                  // segment.
244     Write32(LoadCommandsSize);
245     Write32(Flags);
246
247     assert(OS.tell() - Start == Header32Size);
248   }
249
250   /// WriteSegmentLoadCommand32 - Write a 32-bit segment load command.
251   ///
252   /// \arg NumSections - The number of sections in this segment.
253   /// \arg SectionDataSize - The total size of the sections.
254   void WriteSegmentLoadCommand32(unsigned NumSections,
255                                  uint64_t VMSize,
256                                  uint64_t SectionDataStartOffset,
257                                  uint64_t SectionDataSize) {
258     // struct segment_command (56 bytes)
259
260     uint64_t Start = OS.tell();
261     (void) Start;
262
263     Write32(LCT_Segment);
264     Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
265
266     WriteString("", 16);
267     Write32(0); // vmaddr
268     Write32(VMSize); // vmsize
269     Write32(SectionDataStartOffset); // file offset
270     Write32(SectionDataSize); // file size
271     Write32(0x7); // maxprot
272     Write32(0x7); // initprot
273     Write32(NumSections);
274     Write32(0); // flags
275
276     assert(OS.tell() - Start == SegmentLoadCommand32Size);
277   }
278
279   void WriteSection32(const MCSectionData &SD, uint64_t FileOffset,
280                       uint64_t RelocationsStart, unsigned NumRelocations) {
281     // The offset is unused for virtual sections.
282     if (isVirtualSection(SD.getSection())) {
283       assert(SD.getFileSize() == 0 && "Invalid file size!");
284       FileOffset = 0;
285     }
286
287     // struct section (68 bytes)
288
289     uint64_t Start = OS.tell();
290     (void) Start;
291
292     // FIXME: cast<> support!
293     const MCSectionMachO &Section =
294       static_cast<const MCSectionMachO&>(SD.getSection());
295     WriteString(Section.getSectionName(), 16);
296     WriteString(Section.getSegmentName(), 16);
297     Write32(SD.getAddress()); // address
298     Write32(SD.getSize()); // size
299     Write32(FileOffset);
300
301     unsigned Flags = Section.getTypeAndAttributes();
302     if (SD.hasInstructions())
303       Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
304
305     assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
306     Write32(Log2_32(SD.getAlignment()));
307     Write32(NumRelocations ? RelocationsStart : 0);
308     Write32(NumRelocations);
309     Write32(Flags);
310     Write32(0); // reserved1
311     Write32(Section.getStubSize()); // reserved2
312
313     assert(OS.tell() - Start == Section32Size);
314   }
315
316   void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
317                               uint32_t StringTableOffset,
318                               uint32_t StringTableSize) {
319     // struct symtab_command (24 bytes)
320
321     uint64_t Start = OS.tell();
322     (void) Start;
323
324     Write32(LCT_Symtab);
325     Write32(SymtabLoadCommandSize);
326     Write32(SymbolOffset);
327     Write32(NumSymbols);
328     Write32(StringTableOffset);
329     Write32(StringTableSize);
330
331     assert(OS.tell() - Start == SymtabLoadCommandSize);
332   }
333
334   void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
335                                 uint32_t NumLocalSymbols,
336                                 uint32_t FirstExternalSymbol,
337                                 uint32_t NumExternalSymbols,
338                                 uint32_t FirstUndefinedSymbol,
339                                 uint32_t NumUndefinedSymbols,
340                                 uint32_t IndirectSymbolOffset,
341                                 uint32_t NumIndirectSymbols) {
342     // struct dysymtab_command (80 bytes)
343
344     uint64_t Start = OS.tell();
345     (void) Start;
346
347     Write32(LCT_Dysymtab);
348     Write32(DysymtabLoadCommandSize);
349     Write32(FirstLocalSymbol);
350     Write32(NumLocalSymbols);
351     Write32(FirstExternalSymbol);
352     Write32(NumExternalSymbols);
353     Write32(FirstUndefinedSymbol);
354     Write32(NumUndefinedSymbols);
355     Write32(0); // tocoff
356     Write32(0); // ntoc
357     Write32(0); // modtaboff
358     Write32(0); // nmodtab
359     Write32(0); // extrefsymoff
360     Write32(0); // nextrefsyms
361     Write32(IndirectSymbolOffset);
362     Write32(NumIndirectSymbols);
363     Write32(0); // extreloff
364     Write32(0); // nextrel
365     Write32(0); // locreloff
366     Write32(0); // nlocrel
367
368     assert(OS.tell() - Start == DysymtabLoadCommandSize);
369   }
370
371   void WriteNlist32(MachSymbolData &MSD) {
372     MCSymbolData &Data = *MSD.SymbolData;
373     const MCSymbol &Symbol = Data.getSymbol();
374     uint8_t Type = 0;
375     uint16_t Flags = Data.getFlags();
376     uint32_t Address = 0;
377
378     // Set the N_TYPE bits. See <mach-o/nlist.h>.
379     //
380     // FIXME: Are the prebound or indirect fields possible here?
381     if (Symbol.isUndefined())
382       Type = STT_Undefined;
383     else if (Symbol.isAbsolute())
384       Type = STT_Absolute;
385     else
386       Type = STT_Section;
387
388     // FIXME: Set STAB bits.
389
390     if (Data.isPrivateExtern())
391       Type |= STF_PrivateExtern;
392
393     // Set external bit.
394     if (Data.isExternal() || Symbol.isUndefined())
395       Type |= STF_External;
396
397     // Compute the symbol address.
398     if (Symbol.isDefined()) {
399       if (Symbol.isAbsolute()) {
400         llvm_unreachable("FIXME: Not yet implemented!");
401       } else {
402         Address = Data.getFragment()->getAddress() + Data.getOffset();
403       }
404     } else if (Data.isCommon()) {
405       // Common symbols are encoded with the size in the address
406       // field, and their alignment in the flags.
407       Address = Data.getCommonSize();
408
409       // Common alignment is packed into the 'desc' bits.
410       if (unsigned Align = Data.getCommonAlignment()) {
411         unsigned Log2Size = Log2_32(Align);
412         assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
413         if (Log2Size > 15)
414           llvm_report_error("invalid 'common' alignment '" +
415                             Twine(Align) + "'");
416         // FIXME: Keep this mask with the SymbolFlags enumeration.
417         Flags = (Flags & 0xF0FF) | (Log2Size << 8);
418       }
419     }
420
421     // struct nlist (12 bytes)
422
423     Write32(MSD.StringIndex);
424     Write8(Type);
425     Write8(MSD.SectionIndex);
426
427     // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
428     // value.
429     Write16(Flags);
430     Write32(Address);
431   }
432
433   struct MachRelocationEntry {
434     uint32_t Word0;
435     uint32_t Word1;
436   };
437   void ComputeScatteredRelocationInfo(MCAssembler &Asm, MCFragment &Fragment,
438                                       MCAsmFixup &Fixup,
439                                       const MCValue &Target,
440                              DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap,
441                                      std::vector<MachRelocationEntry> &Relocs) {
442     uint32_t Address = Fragment.getOffset() + Fixup.Offset;
443     unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
444     unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
445     unsigned Type = RIT_Vanilla;
446
447     // See <reloc.h>.
448     const MCSymbol *A = Target.getSymA();
449     MCSymbolData *A_SD = SymbolMap.lookup(A);
450
451     if (!A_SD->getFragment())
452       llvm_report_error("symbol '" + A->getName() +
453                         "' can not be undefined in a subtraction expression");
454
455     uint32_t Value = A_SD->getFragment()->getAddress() + A_SD->getOffset();
456     uint32_t Value2 = 0;
457
458     if (const MCSymbol *B = Target.getSymB()) {
459       MCSymbolData *B_SD = SymbolMap.lookup(B);
460
461       if (!B_SD->getFragment())
462         llvm_report_error("symbol '" + B->getName() +
463                           "' can not be undefined in a subtraction expression");
464
465       // Select the appropriate difference relocation type.
466       //
467       // Note that there is no longer any semantic difference between these two
468       // relocation types from the linkers point of view, this is done solely
469       // for pedantic compatibility with 'as'.
470       Type = A_SD->isExternal() ? RIT_Difference : RIT_LocalDifference;
471       Value2 = B_SD->getFragment()->getAddress() + B_SD->getOffset();
472     }
473
474     // The value which goes in the fixup is current value of the expression.
475     Fixup.FixedValue = Value - Value2 + Target.getConstant();
476     if (IsPCRel)
477       Fixup.FixedValue -= Address;
478
479     // If this fixup is a vanilla PC relative relocation for a local label, we
480     // don't need a relocation.
481     //
482     // FIXME: Implement proper atom support.
483     if (IsPCRel && Target.getSymA() && Target.getSymA()->isTemporary() &&
484         !Target.getSymB())
485       return;
486
487     MachRelocationEntry MRE;
488     MRE.Word0 = ((Address   <<  0) |
489                  (Type      << 24) |
490                  (Log2Size  << 28) |
491                  (IsPCRel   << 30) |
492                  RF_Scattered);
493     MRE.Word1 = Value;
494     Relocs.push_back(MRE);
495
496     if (Type == RIT_Difference || Type == RIT_LocalDifference) {
497       MachRelocationEntry MRE;
498       MRE.Word0 = ((0         <<  0) |
499                    (RIT_Pair  << 24) |
500                    (Log2Size  << 28) |
501                    (IsPCRel   << 30) |
502                    RF_Scattered);
503       MRE.Word1 = Value2;
504       Relocs.push_back(MRE);
505     }
506   }
507
508   void ComputeRelocationInfo(MCAssembler &Asm, MCDataFragment &Fragment,
509                              MCAsmFixup &Fixup,
510                              DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap,
511                              std::vector<MachRelocationEntry> &Relocs) {
512     unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
513     unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
514
515     MCValue Target;
516     if (!Fixup.Value->EvaluateAsRelocatable(Target))
517       llvm_report_error("expected relocatable expression");
518
519     // If this is a difference or a defined symbol plus an offset, then we need
520     // a scattered relocation entry.
521     uint32_t Offset = Target.getConstant();
522     if (IsPCRel)
523       Offset += 1 << Log2Size;
524     if (Target.getSymB() ||
525         (Target.getSymA() && !Target.getSymA()->isUndefined() &&
526          Offset))
527       return ComputeScatteredRelocationInfo(Asm, Fragment, Fixup, Target,
528                                             SymbolMap, Relocs);
529
530     // See <reloc.h>.
531     uint32_t Address = Fragment.getOffset() + Fixup.Offset;
532     uint32_t Value = 0;
533     unsigned Index = 0;
534     unsigned IsExtern = 0;
535     unsigned Type = 0;
536
537     if (Target.isAbsolute()) { // constant
538       // SymbolNum of 0 indicates the absolute section.
539       //
540       // FIXME: When is this generated?
541       Type = RIT_Vanilla;
542       Value = 0;
543       llvm_unreachable("FIXME: Not yet implemented!");
544     } else {
545       const MCSymbol *Symbol = Target.getSymA();
546       MCSymbolData *SD = SymbolMap.lookup(Symbol);
547
548       if (Symbol->isUndefined()) {
549         IsExtern = 1;
550         Index = SD->getIndex();
551         Value = 0;
552       } else {
553         // The index is the section ordinal.
554         //
555         // FIXME: O(N)
556         Index = 1;
557         MCAssembler::iterator it = Asm.begin(), ie = Asm.end();
558         for (; it != ie; ++it, ++Index)
559           if (&*it == SD->getFragment()->getParent())
560             break;
561         assert(it != ie && "Unable to find section index!");
562         Value = SD->getFragment()->getAddress() + SD->getOffset();
563       }
564
565       Type = RIT_Vanilla;
566     }
567
568     // The value which goes in the fixup is current value of the expression.
569     Fixup.FixedValue = Value + Target.getConstant();
570     if (IsPCRel)
571       Fixup.FixedValue -= Address;
572
573     // If this fixup is a vanilla PC relative relocation for a local label, we
574     // don't need a relocation.
575     //
576     // FIXME: Implement proper atom support.
577     if (IsPCRel && Target.getSymA() && Target.getSymA()->isTemporary())
578       return;
579
580     // struct relocation_info (8 bytes)
581     MachRelocationEntry MRE;
582     MRE.Word0 = Address;
583     MRE.Word1 = ((Index     <<  0) |
584                  (IsPCRel   << 24) |
585                  (Log2Size  << 25) |
586                  (IsExtern  << 27) |
587                  (Type      << 28));
588     Relocs.push_back(MRE);
589   }
590
591   void BindIndirectSymbols(MCAssembler &Asm,
592                            DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap) {
593     // This is the point where 'as' creates actual symbols for indirect symbols
594     // (in the following two passes). It would be easier for us to do this
595     // sooner when we see the attribute, but that makes getting the order in the
596     // symbol table much more complicated than it is worth.
597     //
598     // FIXME: Revisit this when the dust settles.
599
600     // Bind non lazy symbol pointers first.
601     for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
602            ie = Asm.indirect_symbol_end(); it != ie; ++it) {
603       // FIXME: cast<> support!
604       const MCSectionMachO &Section =
605         static_cast<const MCSectionMachO&>(it->SectionData->getSection());
606
607       unsigned Type =
608         Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
609       if (Type != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
610         continue;
611
612       MCSymbolData *&Entry = SymbolMap[it->Symbol];
613       if (!Entry)
614         Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
615     }
616
617     // Then lazy symbol pointers and symbol stubs.
618     for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
619            ie = Asm.indirect_symbol_end(); it != ie; ++it) {
620       // FIXME: cast<> support!
621       const MCSectionMachO &Section =
622         static_cast<const MCSectionMachO&>(it->SectionData->getSection());
623
624       unsigned Type =
625         Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
626       if (Type != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
627           Type != MCSectionMachO::S_SYMBOL_STUBS)
628         continue;
629
630       MCSymbolData *&Entry = SymbolMap[it->Symbol];
631       if (!Entry) {
632         Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
633
634         // Set the symbol type to undefined lazy, but only on construction.
635         //
636         // FIXME: Do not hardcode.
637         Entry->setFlags(Entry->getFlags() | 0x0001);
638       }
639     }
640   }
641
642   /// ComputeSymbolTable - Compute the symbol table data
643   ///
644   /// \param StringTable [out] - The string table data.
645   /// \param StringIndexMap [out] - Map from symbol names to offsets in the
646   /// string table.
647   void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
648                           std::vector<MachSymbolData> &LocalSymbolData,
649                           std::vector<MachSymbolData> &ExternalSymbolData,
650                           std::vector<MachSymbolData> &UndefinedSymbolData) {
651     // Build section lookup table.
652     DenseMap<const MCSection*, uint8_t> SectionIndexMap;
653     unsigned Index = 1;
654     for (MCAssembler::iterator it = Asm.begin(),
655            ie = Asm.end(); it != ie; ++it, ++Index)
656       SectionIndexMap[&it->getSection()] = Index;
657     assert(Index <= 256 && "Too many sections!");
658
659     // Index 0 is always the empty string.
660     StringMap<uint64_t> StringIndexMap;
661     StringTable += '\x00';
662
663     // Build the symbol arrays and the string table, but only for non-local
664     // symbols.
665     //
666     // The particular order that we collect the symbols and create the string
667     // table, then sort the symbols is chosen to match 'as'. Even though it
668     // doesn't matter for correctness, this is important for letting us diff .o
669     // files.
670     for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
671            ie = Asm.symbol_end(); it != ie; ++it) {
672       const MCSymbol &Symbol = it->getSymbol();
673
674       // Ignore assembler temporaries.
675       if (it->getSymbol().isTemporary())
676         continue;
677
678       if (!it->isExternal() && !Symbol.isUndefined())
679         continue;
680
681       uint64_t &Entry = StringIndexMap[Symbol.getName()];
682       if (!Entry) {
683         Entry = StringTable.size();
684         StringTable += Symbol.getName();
685         StringTable += '\x00';
686       }
687
688       MachSymbolData MSD;
689       MSD.SymbolData = it;
690       MSD.StringIndex = Entry;
691
692       if (Symbol.isUndefined()) {
693         MSD.SectionIndex = 0;
694         UndefinedSymbolData.push_back(MSD);
695       } else if (Symbol.isAbsolute()) {
696         MSD.SectionIndex = 0;
697         ExternalSymbolData.push_back(MSD);
698       } else {
699         MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
700         assert(MSD.SectionIndex && "Invalid section index!");
701         ExternalSymbolData.push_back(MSD);
702       }
703     }
704
705     // Now add the data for local symbols.
706     for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
707            ie = Asm.symbol_end(); it != ie; ++it) {
708       const MCSymbol &Symbol = it->getSymbol();
709
710       // Ignore assembler temporaries.
711       if (it->getSymbol().isTemporary())
712         continue;
713
714       if (it->isExternal() || Symbol.isUndefined())
715         continue;
716
717       uint64_t &Entry = StringIndexMap[Symbol.getName()];
718       if (!Entry) {
719         Entry = StringTable.size();
720         StringTable += Symbol.getName();
721         StringTable += '\x00';
722       }
723
724       MachSymbolData MSD;
725       MSD.SymbolData = it;
726       MSD.StringIndex = Entry;
727
728       if (Symbol.isAbsolute()) {
729         MSD.SectionIndex = 0;
730         LocalSymbolData.push_back(MSD);
731       } else {
732         MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
733         assert(MSD.SectionIndex && "Invalid section index!");
734         LocalSymbolData.push_back(MSD);
735       }
736     }
737
738     // External and undefined symbols are required to be in lexicographic order.
739     std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
740     std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
741
742     // Set the symbol indices.
743     Index = 0;
744     for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
745       LocalSymbolData[i].SymbolData->setIndex(Index++);
746     for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
747       ExternalSymbolData[i].SymbolData->setIndex(Index++);
748     for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
749       UndefinedSymbolData[i].SymbolData->setIndex(Index++);
750
751     // The string table is padded to a multiple of 4.
752     while (StringTable.size() % 4)
753       StringTable += '\x00';
754   }
755
756   void WriteObject(MCAssembler &Asm) {
757     unsigned NumSections = Asm.size();
758
759     // Compute the symbol -> symbol data map.
760     //
761     // FIXME: This should not be here.
762     DenseMap<const MCSymbol*, MCSymbolData *> SymbolMap;
763     for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
764            ie = Asm.symbol_end(); it != ie; ++it)
765       SymbolMap[&it->getSymbol()] = it;
766
767     // Create symbol data for any indirect symbols.
768     BindIndirectSymbols(Asm, SymbolMap);
769
770     // Compute symbol table information.
771     SmallString<256> StringTable;
772     std::vector<MachSymbolData> LocalSymbolData;
773     std::vector<MachSymbolData> ExternalSymbolData;
774     std::vector<MachSymbolData> UndefinedSymbolData;
775     unsigned NumSymbols = Asm.symbol_size();
776
777     // No symbol table command is written if there are no symbols.
778     if (NumSymbols)
779       ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
780                          UndefinedSymbolData);
781
782     // The section data starts after the header, the segment load command (and
783     // section headers) and the symbol table.
784     unsigned NumLoadCommands = 1;
785     uint64_t LoadCommandsSize =
786       SegmentLoadCommand32Size + NumSections * Section32Size;
787
788     // Add the symbol table load command sizes, if used.
789     if (NumSymbols) {
790       NumLoadCommands += 2;
791       LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
792     }
793
794     // Compute the total size of the section data, as well as its file size and
795     // vm size.
796     uint64_t SectionDataStart = Header32Size + LoadCommandsSize;
797     uint64_t SectionDataSize = 0;
798     uint64_t SectionDataFileSize = 0;
799     uint64_t VMSize = 0;
800     for (MCAssembler::iterator it = Asm.begin(),
801            ie = Asm.end(); it != ie; ++it) {
802       MCSectionData &SD = *it;
803
804       VMSize = std::max(VMSize, SD.getAddress() + SD.getSize());
805
806       if (isVirtualSection(SD.getSection()))
807         continue;
808
809       SectionDataSize = std::max(SectionDataSize,
810                                  SD.getAddress() + SD.getSize());
811       SectionDataFileSize = std::max(SectionDataFileSize,
812                                      SD.getAddress() + SD.getFileSize());
813     }
814
815     // The section data is padded to 4 bytes.
816     //
817     // FIXME: Is this machine dependent?
818     unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
819     SectionDataFileSize += SectionDataPadding;
820
821     // Write the prolog, starting with the header and load command...
822     WriteHeader32(NumLoadCommands, LoadCommandsSize,
823                   Asm.getSubsectionsViaSymbols());
824     WriteSegmentLoadCommand32(NumSections, VMSize,
825                               SectionDataStart, SectionDataSize);
826
827     // ... and then the section headers.
828     //
829     // We also compute the section relocations while we do this. Note that
830     // computing relocation info will also update the fixup to have the correct
831     // value; this will overwrite the appropriate data in the fragment when it
832     // is written.
833     std::vector<MachRelocationEntry> RelocInfos;
834     uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
835     for (MCAssembler::iterator it = Asm.begin(),
836            ie = Asm.end(); it != ie; ++it) {
837       MCSectionData &SD = *it;
838
839       // The assembler writes relocations in the reverse order they were seen.
840       //
841       // FIXME: It is probably more complicated than this.
842       unsigned NumRelocsStart = RelocInfos.size();
843       for (MCSectionData::reverse_iterator it2 = SD.rbegin(),
844              ie2 = SD.rend(); it2 != ie2; ++it2)
845         if (MCDataFragment *DF = dyn_cast<MCDataFragment>(&*it2))
846           for (unsigned i = 0, e = DF->fixup_size(); i != e; ++i)
847             ComputeRelocationInfo(Asm, *DF, DF->getFixups()[e - i - 1],
848                                   SymbolMap, RelocInfos);
849
850       unsigned NumRelocs = RelocInfos.size() - NumRelocsStart;
851       uint64_t SectionStart = SectionDataStart + SD.getAddress();
852       WriteSection32(SD, SectionStart, RelocTableEnd, NumRelocs);
853       RelocTableEnd += NumRelocs * RelocationInfoSize;
854     }
855
856     // Write the symbol table load command, if used.
857     if (NumSymbols) {
858       unsigned FirstLocalSymbol = 0;
859       unsigned NumLocalSymbols = LocalSymbolData.size();
860       unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
861       unsigned NumExternalSymbols = ExternalSymbolData.size();
862       unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
863       unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
864       unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
865       unsigned NumSymTabSymbols =
866         NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
867       uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
868       uint64_t IndirectSymbolOffset = 0;
869
870       // If used, the indirect symbols are written after the section data.
871       if (NumIndirectSymbols)
872         IndirectSymbolOffset = RelocTableEnd;
873
874       // The symbol table is written after the indirect symbol data.
875       uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
876
877       // The string table is written after symbol table.
878       uint64_t StringTableOffset =
879         SymbolTableOffset + NumSymTabSymbols * Nlist32Size;
880       WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
881                              StringTableOffset, StringTable.size());
882
883       WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
884                                FirstExternalSymbol, NumExternalSymbols,
885                                FirstUndefinedSymbol, NumUndefinedSymbols,
886                                IndirectSymbolOffset, NumIndirectSymbols);
887     }
888
889     // Write the actual section data.
890     for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
891       WriteFileData(OS, *it, *this);
892
893     // Write the extra padding.
894     WriteZeros(SectionDataPadding);
895
896     // Write the relocation entries.
897     for (unsigned i = 0, e = RelocInfos.size(); i != e; ++i) {
898       Write32(RelocInfos[i].Word0);
899       Write32(RelocInfos[i].Word1);
900     }
901
902     // Write the symbol table data, if used.
903     if (NumSymbols) {
904       // Write the indirect symbol entries.
905       for (MCAssembler::indirect_symbol_iterator
906              it = Asm.indirect_symbol_begin(),
907              ie = Asm.indirect_symbol_end(); it != ie; ++it) {
908         // Indirect symbols in the non lazy symbol pointer section have some
909         // special handling.
910         const MCSectionMachO &Section =
911           static_cast<const MCSectionMachO&>(it->SectionData->getSection());
912         unsigned Type =
913           Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
914         if (Type == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
915           // If this symbol is defined and internal, mark it as such.
916           if (it->Symbol->isDefined() &&
917               !SymbolMap.lookup(it->Symbol)->isExternal()) {
918             uint32_t Flags = ISF_Local;
919             if (it->Symbol->isAbsolute())
920               Flags |= ISF_Absolute;
921             Write32(Flags);
922             continue;
923           }
924         }
925
926         Write32(SymbolMap[it->Symbol]->getIndex());
927       }
928
929       // FIXME: Check that offsets match computed ones.
930
931       // Write the symbol table entries.
932       for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
933         WriteNlist32(LocalSymbolData[i]);
934       for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
935         WriteNlist32(ExternalSymbolData[i]);
936       for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
937         WriteNlist32(UndefinedSymbolData[i]);
938
939       // Write the string table.
940       OS << StringTable.str();
941     }
942   }
943
944   void ApplyFixup(const MCAsmFixup &Fixup, MCDataFragment &DF) {
945     unsigned Size = 1 << getFixupKindLog2Size(Fixup.Kind);
946
947     // FIXME: Endianness assumption.
948     assert(Fixup.Offset + Size <= DF.getContents().size() &&
949            "Invalid fixup offset!");
950     for (unsigned i = 0; i != Size; ++i)
951       DF.getContents()[Fixup.Offset + i] = uint8_t(Fixup.FixedValue >> (i * 8));
952   }
953 };
954
955 /* *** */
956
957 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
958 }
959
960 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
961   : Kind(_Kind),
962     Parent(_Parent),
963     FileSize(~UINT64_C(0))
964 {
965   if (Parent)
966     Parent->getFragmentList().push_back(this);
967 }
968
969 MCFragment::~MCFragment() {
970 }
971
972 uint64_t MCFragment::getAddress() const {
973   assert(getParent() && "Missing Section!");
974   return getParent()->getAddress() + Offset;
975 }
976
977 /* *** */
978
979 MCSectionData::MCSectionData() : Section(0) {}
980
981 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
982   : Section(&_Section),
983     Alignment(1),
984     Address(~UINT64_C(0)),
985     Size(~UINT64_C(0)),
986     FileSize(~UINT64_C(0)),
987     HasInstructions(false)
988 {
989   if (A)
990     A->getSectionList().push_back(this);
991 }
992
993 /* *** */
994
995 MCSymbolData::MCSymbolData() : Symbol(0) {}
996
997 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
998                            uint64_t _Offset, MCAssembler *A)
999   : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
1000     IsExternal(false), IsPrivateExtern(false),
1001     CommonSize(0), CommonAlign(0), Flags(0), Index(0)
1002 {
1003   if (A)
1004     A->getSymbolList().push_back(this);
1005 }
1006
1007 /* *** */
1008
1009 MCAssembler::MCAssembler(MCContext &_Context, raw_ostream &_OS)
1010   : Context(_Context), OS(_OS), SubsectionsViaSymbols(false)
1011 {
1012 }
1013
1014 MCAssembler::~MCAssembler() {
1015 }
1016
1017 void MCAssembler::LayoutSection(MCSectionData &SD) {
1018   uint64_t Address = SD.getAddress();
1019
1020   for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
1021     MCFragment &F = *it;
1022
1023     F.setOffset(Address - SD.getAddress());
1024
1025     // Evaluate fragment size.
1026     switch (F.getKind()) {
1027     case MCFragment::FT_Align: {
1028       MCAlignFragment &AF = cast<MCAlignFragment>(F);
1029
1030       uint64_t Size = OffsetToAlignment(Address, AF.getAlignment());
1031       if (Size > AF.getMaxBytesToEmit())
1032         AF.setFileSize(0);
1033       else
1034         AF.setFileSize(Size);
1035       break;
1036     }
1037
1038     case MCFragment::FT_Data:
1039     case MCFragment::FT_Fill:
1040       F.setFileSize(F.getMaxFileSize());
1041       break;
1042
1043     case MCFragment::FT_Org: {
1044       MCOrgFragment &OF = cast<MCOrgFragment>(F);
1045
1046       MCValue Target;
1047       if (!OF.getOffset().EvaluateAsRelocatable(Target))
1048         llvm_report_error("expected relocatable expression");
1049
1050       if (!Target.isAbsolute())
1051         llvm_unreachable("FIXME: Not yet implemented!");
1052       uint64_t OrgOffset = Target.getConstant();
1053       uint64_t Offset = Address - SD.getAddress();
1054
1055       // FIXME: We need a way to communicate this error.
1056       if (OrgOffset < Offset)
1057         llvm_report_error("invalid .org offset '" + Twine(OrgOffset) +
1058                           "' (at offset '" + Twine(Offset) + "'");
1059
1060       F.setFileSize(OrgOffset - Offset);
1061       break;
1062     }
1063
1064     case MCFragment::FT_ZeroFill: {
1065       MCZeroFillFragment &ZFF = cast<MCZeroFillFragment>(F);
1066
1067       // Align the fragment offset; it is safe to adjust the offset freely since
1068       // this is only in virtual sections.
1069       Address = RoundUpToAlignment(Address, ZFF.getAlignment());
1070       F.setOffset(Address - SD.getAddress());
1071
1072       // FIXME: This is misnamed.
1073       F.setFileSize(ZFF.getSize());
1074       break;
1075     }
1076     }
1077
1078     Address += F.getFileSize();
1079   }
1080
1081   // Set the section sizes.
1082   SD.setSize(Address - SD.getAddress());
1083   if (isVirtualSection(SD.getSection()))
1084     SD.setFileSize(0);
1085   else
1086     SD.setFileSize(Address - SD.getAddress());
1087 }
1088
1089 /// WriteNopData - Write optimal nops to the output file for the \arg Count
1090 /// bytes.  This returns the number of bytes written.  It may return 0 if
1091 /// the \arg Count is more than the maximum optimal nops.
1092 ///
1093 /// FIXME this is X86 32-bit specific and should move to a better place.
1094 static uint64_t WriteNopData(uint64_t Count, MachObjectWriter &MOW) {
1095   static const uint8_t Nops[16][16] = {
1096     // nop
1097     {0x90},
1098     // xchg %ax,%ax
1099     {0x66, 0x90},
1100     // nopl (%[re]ax)
1101     {0x0f, 0x1f, 0x00},
1102     // nopl 0(%[re]ax)
1103     {0x0f, 0x1f, 0x40, 0x00},
1104     // nopl 0(%[re]ax,%[re]ax,1)
1105     {0x0f, 0x1f, 0x44, 0x00, 0x00},
1106     // nopw 0(%[re]ax,%[re]ax,1)
1107     {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1108     // nopl 0L(%[re]ax)
1109     {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1110     // nopl 0L(%[re]ax,%[re]ax,1)
1111     {0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1112     // nopw 0L(%[re]ax,%[re]ax,1)
1113     {0x66, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1114     // nopw %cs:0L(%[re]ax,%[re]ax,1)
1115     {0x66, 0x2e, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1116     // nopl 0(%[re]ax,%[re]ax,1)
1117     // nopw 0(%[re]ax,%[re]ax,1)
1118     {0x0f, 0x1f, 0x44, 0x00, 0x00,
1119      0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1120     // nopw 0(%[re]ax,%[re]ax,1)
1121     // nopw 0(%[re]ax,%[re]ax,1)
1122     {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00,
1123      0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1124     // nopw 0(%[re]ax,%[re]ax,1)
1125     // nopl 0L(%[re]ax) */
1126     {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00,
1127      0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1128     // nopl 0L(%[re]ax)
1129     // nopl 0L(%[re]ax)
1130     {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00,
1131      0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1132     // nopl 0L(%[re]ax)
1133     // nopl 0L(%[re]ax,%[re]ax,1)
1134     {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00,
1135      0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00}
1136   };
1137
1138   if (Count > 15)
1139     return 0;
1140
1141   for (uint64_t i = 0; i < Count; i++)
1142     MOW.Write8 (uint8_t(Nops[Count - 1][i]));
1143
1144   return Count;
1145 }
1146
1147 /// WriteFileData - Write the \arg F data to the output file.
1148 static void WriteFileData(raw_ostream &OS, const MCFragment &F,
1149                           MachObjectWriter &MOW) {
1150   uint64_t Start = OS.tell();
1151   (void) Start;
1152
1153   ++EmittedFragments;
1154
1155   // FIXME: Embed in fragments instead?
1156   switch (F.getKind()) {
1157   case MCFragment::FT_Align: {
1158     MCAlignFragment &AF = cast<MCAlignFragment>(F);
1159     uint64_t Count = AF.getFileSize() / AF.getValueSize();
1160
1161     // FIXME: This error shouldn't actually occur (the front end should emit
1162     // multiple .align directives to enforce the semantics it wants), but is
1163     // severe enough that we want to report it. How to handle this?
1164     if (Count * AF.getValueSize() != AF.getFileSize())
1165       llvm_report_error("undefined .align directive, value size '" +
1166                         Twine(AF.getValueSize()) +
1167                         "' is not a divisor of padding size '" +
1168                         Twine(AF.getFileSize()) + "'");
1169
1170     // See if we are aligning with nops, and if so do that first to try to fill
1171     // the Count bytes.  Then if that did not fill any bytes or there are any
1172     // bytes left to fill use the the Value and ValueSize to fill the rest.
1173     if (AF.getEmitNops()) {
1174       uint64_t NopByteCount = WriteNopData(Count, MOW);
1175       Count -= NopByteCount;
1176     }
1177
1178     for (uint64_t i = 0; i != Count; ++i) {
1179       switch (AF.getValueSize()) {
1180       default:
1181         assert(0 && "Invalid size!");
1182       case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
1183       case 2: MOW.Write16(uint16_t(AF.getValue())); break;
1184       case 4: MOW.Write32(uint32_t(AF.getValue())); break;
1185       case 8: MOW.Write64(uint64_t(AF.getValue())); break;
1186       }
1187     }
1188     break;
1189   }
1190
1191   case MCFragment::FT_Data: {
1192     MCDataFragment &DF = cast<MCDataFragment>(F);
1193
1194     // Apply the fixups.
1195     //
1196     // FIXME: Move elsewhere.
1197     for (MCDataFragment::const_fixup_iterator it = DF.fixup_begin(),
1198            ie = DF.fixup_end(); it != ie; ++it)
1199       MOW.ApplyFixup(*it, DF);
1200
1201     OS << cast<MCDataFragment>(F).getContents().str();
1202     break;
1203   }
1204
1205   case MCFragment::FT_Fill: {
1206     MCFillFragment &FF = cast<MCFillFragment>(F);
1207     for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
1208       switch (FF.getValueSize()) {
1209       default:
1210         assert(0 && "Invalid size!");
1211       case 1: MOW.Write8 (uint8_t (FF.getValue())); break;
1212       case 2: MOW.Write16(uint16_t(FF.getValue())); break;
1213       case 4: MOW.Write32(uint32_t(FF.getValue())); break;
1214       case 8: MOW.Write64(uint64_t(FF.getValue())); break;
1215       }
1216     }
1217     break;
1218   }
1219
1220   case MCFragment::FT_Org: {
1221     MCOrgFragment &OF = cast<MCOrgFragment>(F);
1222
1223     for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
1224       MOW.Write8(uint8_t(OF.getValue()));
1225
1226     break;
1227   }
1228
1229   case MCFragment::FT_ZeroFill: {
1230     assert(0 && "Invalid zero fill fragment in concrete section!");
1231     break;
1232   }
1233   }
1234
1235   assert(OS.tell() - Start == F.getFileSize());
1236 }
1237
1238 /// WriteFileData - Write the \arg SD data to the output file.
1239 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
1240                           MachObjectWriter &MOW) {
1241   // Ignore virtual sections.
1242   if (isVirtualSection(SD.getSection())) {
1243     assert(SD.getFileSize() == 0);
1244     return;
1245   }
1246
1247   uint64_t Start = OS.tell();
1248   (void) Start;
1249
1250   for (MCSectionData::const_iterator it = SD.begin(),
1251          ie = SD.end(); it != ie; ++it)
1252     WriteFileData(OS, *it, MOW);
1253
1254   // Add section padding.
1255   assert(SD.getFileSize() >= SD.getSize() && "Invalid section sizes!");
1256   MOW.WriteZeros(SD.getFileSize() - SD.getSize());
1257
1258   assert(OS.tell() - Start == SD.getFileSize());
1259 }
1260
1261 void MCAssembler::Finish() {
1262   DEBUG_WITH_TYPE("mc-dump", {
1263       llvm::errs() << "assembler backend - pre-layout\n--\n";
1264       dump(); });
1265
1266   // Layout the concrete sections and fragments.
1267   uint64_t Address = 0;
1268   MCSectionData *Prev = 0;
1269   for (iterator it = begin(), ie = end(); it != ie; ++it) {
1270     MCSectionData &SD = *it;
1271
1272     // Skip virtual sections.
1273     if (isVirtualSection(SD.getSection()))
1274       continue;
1275
1276     // Align this section if necessary by adding padding bytes to the previous
1277     // section.
1278     if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment())) {
1279       assert(Prev && "Missing prev section!");
1280       Prev->setFileSize(Prev->getFileSize() + Pad);
1281       Address += Pad;
1282     }
1283
1284     // Layout the section fragments and its size.
1285     SD.setAddress(Address);
1286     LayoutSection(SD);
1287     Address += SD.getFileSize();
1288
1289     Prev = &SD;
1290   }
1291
1292   // Layout the virtual sections.
1293   for (iterator it = begin(), ie = end(); it != ie; ++it) {
1294     MCSectionData &SD = *it;
1295
1296     if (!isVirtualSection(SD.getSection()))
1297       continue;
1298
1299     // Align this section if necessary by adding padding bytes to the previous
1300     // section.
1301     if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment()))
1302       Address += Pad;
1303
1304     SD.setAddress(Address);
1305     LayoutSection(SD);
1306     Address += SD.getSize();
1307
1308   }
1309
1310   DEBUG_WITH_TYPE("mc-dump", {
1311       llvm::errs() << "assembler backend - post-layout\n--\n";
1312       dump(); });
1313
1314   // Write the object file.
1315   MachObjectWriter MOW(OS);
1316   MOW.WriteObject(*this);
1317
1318   OS.flush();
1319 }
1320
1321
1322 // Debugging methods
1323
1324 namespace llvm {
1325
1326 raw_ostream &operator<<(raw_ostream &OS, const MCAsmFixup &AF) {
1327   OS << "<MCAsmFixup" << " Offset:" << AF.Offset << " Value:" << *AF.Value
1328      << " Kind:" << AF.Kind << ">";
1329   return OS;
1330 }
1331
1332 }
1333
1334 void MCFragment::dump() {
1335   raw_ostream &OS = llvm::errs();
1336
1337   OS << "<MCFragment " << (void*) this << " Offset:" << Offset
1338      << " FileSize:" << FileSize;
1339
1340   OS << ">";
1341 }
1342
1343 void MCAlignFragment::dump() {
1344   raw_ostream &OS = llvm::errs();
1345
1346   OS << "<MCAlignFragment ";
1347   this->MCFragment::dump();
1348   OS << "\n       ";
1349   OS << " Alignment:" << getAlignment()
1350      << " Value:" << getValue() << " ValueSize:" << getValueSize()
1351      << " MaxBytesToEmit:" << getMaxBytesToEmit() << ">";
1352 }
1353
1354 void MCDataFragment::dump() {
1355   raw_ostream &OS = llvm::errs();
1356
1357   OS << "<MCDataFragment ";
1358   this->MCFragment::dump();
1359   OS << "\n       ";
1360   OS << " Contents:[";
1361   for (unsigned i = 0, e = getContents().size(); i != e; ++i) {
1362     if (i) OS << ",";
1363     OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1364   }
1365   OS << "] (" << getContents().size() << " bytes)";
1366
1367   if (!getFixups().empty()) {
1368     OS << ",\n       ";
1369     OS << " Fixups:[";
1370     for (fixup_iterator it = fixup_begin(), ie = fixup_end(); it != ie; ++it) {
1371       if (it != fixup_begin()) OS << ",\n                ";
1372       OS << *it;
1373     }
1374     OS << "]";
1375   }
1376
1377   OS << ">";
1378 }
1379
1380 void MCFillFragment::dump() {
1381   raw_ostream &OS = llvm::errs();
1382
1383   OS << "<MCFillFragment ";
1384   this->MCFragment::dump();
1385   OS << "\n       ";
1386   OS << " Value:" << getValue() << " ValueSize:" << getValueSize()
1387      << " Count:" << getCount() << ">";
1388 }
1389
1390 void MCOrgFragment::dump() {
1391   raw_ostream &OS = llvm::errs();
1392
1393   OS << "<MCOrgFragment ";
1394   this->MCFragment::dump();
1395   OS << "\n       ";
1396   OS << " Offset:" << getOffset() << " Value:" << getValue() << ">";
1397 }
1398
1399 void MCZeroFillFragment::dump() {
1400   raw_ostream &OS = llvm::errs();
1401
1402   OS << "<MCZeroFillFragment ";
1403   this->MCFragment::dump();
1404   OS << "\n       ";
1405   OS << " Size:" << getSize() << " Alignment:" << getAlignment() << ">";
1406 }
1407
1408 void MCSectionData::dump() {
1409   raw_ostream &OS = llvm::errs();
1410
1411   OS << "<MCSectionData";
1412   OS << " Alignment:" << getAlignment() << " Address:" << Address
1413      << " Size:" << Size << " FileSize:" << FileSize
1414      << " Fragments:[\n      ";
1415   for (iterator it = begin(), ie = end(); it != ie; ++it) {
1416     if (it != begin()) OS << ",\n      ";
1417     it->dump();
1418   }
1419   OS << "]>";
1420 }
1421
1422 void MCSymbolData::dump() {
1423   raw_ostream &OS = llvm::errs();
1424
1425   OS << "<MCSymbolData Symbol:" << getSymbol()
1426      << " Fragment:" << getFragment() << " Offset:" << getOffset()
1427      << " Flags:" << getFlags() << " Index:" << getIndex();
1428   if (isCommon())
1429     OS << " (common, size:" << getCommonSize()
1430        << " align: " << getCommonAlignment() << ")";
1431   if (isExternal())
1432     OS << " (external)";
1433   if (isPrivateExtern())
1434     OS << " (private extern)";
1435   OS << ">";
1436 }
1437
1438 void MCAssembler::dump() {
1439   raw_ostream &OS = llvm::errs();
1440
1441   OS << "<MCAssembler\n";
1442   OS << "  Sections:[\n    ";
1443   for (iterator it = begin(), ie = end(); it != ie; ++it) {
1444     if (it != begin()) OS << ",\n    ";
1445     it->dump();
1446   }
1447   OS << "],\n";
1448   OS << "  Symbols:[";
1449
1450   for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1451     if (it != symbol_begin()) OS << ",\n           ";
1452     it->dump();
1453   }
1454   OS << "]>\n";
1455 }