b44cd1e6987855900532ec66ec59de69d1ae9509
[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       // FIXME: This change of type based on the external bit doesn't make much
466       // sense, it seems to be redundant with the other information in the
467       // relocation entry.
468       Type = A_SD->isExternal() ? RIT_Difference : RIT_LocalDifference;
469       Value2 = B_SD->getFragment()->getAddress() + B_SD->getOffset();
470     }
471
472     // The value which goes in the fixup is current value of the expression.
473     Fixup.FixedValue = Value - Value2 + Target.getConstant();
474     if (IsPCRel)
475       Fixup.FixedValue -= Address;
476
477     // If this fixup is a vanilla PC relative relocation for a local label, we
478     // don't need a relocation.
479     //
480     // FIXME: Implement proper atom support.
481     if (IsPCRel && Target.getSymA() && Target.getSymA()->isTemporary() &&
482         !Target.getSymB())
483       return;
484
485     MachRelocationEntry MRE;
486     MRE.Word0 = ((Address   <<  0) |
487                  (Type      << 24) |
488                  (Log2Size  << 28) |
489                  (IsPCRel   << 30) |
490                  RF_Scattered);
491     MRE.Word1 = Value;
492     Relocs.push_back(MRE);
493
494     if (Type == RIT_Difference || Type == RIT_LocalDifference) {
495       MachRelocationEntry MRE;
496       MRE.Word0 = ((0         <<  0) |
497                    (RIT_Pair  << 24) |
498                    (Log2Size  << 28) |
499                    (IsPCRel   << 30) |
500                    RF_Scattered);
501       MRE.Word1 = Value2;
502       Relocs.push_back(MRE);
503     }
504   }
505
506   void ComputeRelocationInfo(MCAssembler &Asm, MCDataFragment &Fragment,
507                              MCAsmFixup &Fixup,
508                              DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap,
509                              std::vector<MachRelocationEntry> &Relocs) {
510     unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
511     unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
512
513     MCValue Target;
514     if (!Fixup.Value->EvaluateAsRelocatable(Target))
515       llvm_report_error("expected relocatable expression");
516
517     // If this is a difference or a defined symbol plus an offset, then we need
518     // a scattered relocation entry.
519     uint32_t Offset = Target.getConstant();
520     if (IsPCRel)
521       Offset += 1 << Log2Size;
522     if (Target.getSymB() ||
523         (Target.getSymA() && !Target.getSymA()->isUndefined() &&
524          Offset))
525       return ComputeScatteredRelocationInfo(Asm, Fragment, Fixup, Target,
526                                             SymbolMap, Relocs);
527
528     // See <reloc.h>.
529     uint32_t Address = Fragment.getOffset() + Fixup.Offset;
530     uint32_t Value = 0;
531     unsigned Index = 0;
532     unsigned IsExtern = 0;
533     unsigned Type = 0;
534
535     if (Target.isAbsolute()) { // constant
536       // SymbolNum of 0 indicates the absolute section.
537       //
538       // FIXME: When is this generated?
539       Type = RIT_Vanilla;
540       Value = 0;
541       llvm_unreachable("FIXME: Not yet implemented!");
542     } else {
543       const MCSymbol *Symbol = Target.getSymA();
544       MCSymbolData *SD = SymbolMap.lookup(Symbol);
545
546       if (Symbol->isUndefined()) {
547         IsExtern = 1;
548         Index = SD->getIndex();
549         Value = 0;
550       } else {
551         // The index is the section ordinal.
552         //
553         // FIXME: O(N)
554         Index = 1;
555         MCAssembler::iterator it = Asm.begin(), ie = Asm.end();
556         for (; it != ie; ++it, ++Index)
557           if (&*it == SD->getFragment()->getParent())
558             break;
559         assert(it != ie && "Unable to find section index!");
560         Value = SD->getFragment()->getAddress() + SD->getOffset();
561       }
562
563       Type = RIT_Vanilla;
564     }
565
566     // The value which goes in the fixup is current value of the expression.
567     Fixup.FixedValue = Value + Target.getConstant();
568     if (IsPCRel)
569       Fixup.FixedValue -= Address;
570
571     // If this fixup is a vanilla PC relative relocation for a local label, we
572     // don't need a relocation.
573     //
574     // FIXME: Implement proper atom support.
575     if (IsPCRel && Target.getSymA() && Target.getSymA()->isTemporary())
576       return;
577
578     // struct relocation_info (8 bytes)
579     MachRelocationEntry MRE;
580     MRE.Word0 = Address;
581     MRE.Word1 = ((Index     <<  0) |
582                  (IsPCRel   << 24) |
583                  (Log2Size  << 25) |
584                  (IsExtern  << 27) |
585                  (Type      << 28));
586     Relocs.push_back(MRE);
587   }
588
589   void BindIndirectSymbols(MCAssembler &Asm,
590                            DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap) {
591     // This is the point where 'as' creates actual symbols for indirect symbols
592     // (in the following two passes). It would be easier for us to do this
593     // sooner when we see the attribute, but that makes getting the order in the
594     // symbol table much more complicated than it is worth.
595     //
596     // FIXME: Revisit this when the dust settles.
597
598     // Bind non lazy symbol pointers first.
599     for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
600            ie = Asm.indirect_symbol_end(); it != ie; ++it) {
601       // FIXME: cast<> support!
602       const MCSectionMachO &Section =
603         static_cast<const MCSectionMachO&>(it->SectionData->getSection());
604
605       unsigned Type =
606         Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
607       if (Type != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
608         continue;
609
610       MCSymbolData *&Entry = SymbolMap[it->Symbol];
611       if (!Entry)
612         Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
613     }
614
615     // Then lazy symbol pointers and symbol stubs.
616     for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
617            ie = Asm.indirect_symbol_end(); it != ie; ++it) {
618       // FIXME: cast<> support!
619       const MCSectionMachO &Section =
620         static_cast<const MCSectionMachO&>(it->SectionData->getSection());
621
622       unsigned Type =
623         Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
624       if (Type != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
625           Type != MCSectionMachO::S_SYMBOL_STUBS)
626         continue;
627
628       MCSymbolData *&Entry = SymbolMap[it->Symbol];
629       if (!Entry) {
630         Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
631
632         // Set the symbol type to undefined lazy, but only on construction.
633         //
634         // FIXME: Do not hardcode.
635         Entry->setFlags(Entry->getFlags() | 0x0001);
636       }
637     }
638   }
639
640   /// ComputeSymbolTable - Compute the symbol table data
641   ///
642   /// \param StringTable [out] - The string table data.
643   /// \param StringIndexMap [out] - Map from symbol names to offsets in the
644   /// string table.
645   void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
646                           std::vector<MachSymbolData> &LocalSymbolData,
647                           std::vector<MachSymbolData> &ExternalSymbolData,
648                           std::vector<MachSymbolData> &UndefinedSymbolData) {
649     // Build section lookup table.
650     DenseMap<const MCSection*, uint8_t> SectionIndexMap;
651     unsigned Index = 1;
652     for (MCAssembler::iterator it = Asm.begin(),
653            ie = Asm.end(); it != ie; ++it, ++Index)
654       SectionIndexMap[&it->getSection()] = Index;
655     assert(Index <= 256 && "Too many sections!");
656
657     // Index 0 is always the empty string.
658     StringMap<uint64_t> StringIndexMap;
659     StringTable += '\x00';
660
661     // Build the symbol arrays and the string table, but only for non-local
662     // symbols.
663     //
664     // The particular order that we collect the symbols and create the string
665     // table, then sort the symbols is chosen to match 'as'. Even though it
666     // doesn't matter for correctness, this is important for letting us diff .o
667     // files.
668     for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
669            ie = Asm.symbol_end(); it != ie; ++it) {
670       const MCSymbol &Symbol = it->getSymbol();
671
672       // Ignore assembler temporaries.
673       if (it->getSymbol().isTemporary())
674         continue;
675
676       if (!it->isExternal() && !Symbol.isUndefined())
677         continue;
678
679       uint64_t &Entry = StringIndexMap[Symbol.getName()];
680       if (!Entry) {
681         Entry = StringTable.size();
682         StringTable += Symbol.getName();
683         StringTable += '\x00';
684       }
685
686       MachSymbolData MSD;
687       MSD.SymbolData = it;
688       MSD.StringIndex = Entry;
689
690       if (Symbol.isUndefined()) {
691         MSD.SectionIndex = 0;
692         UndefinedSymbolData.push_back(MSD);
693       } else if (Symbol.isAbsolute()) {
694         MSD.SectionIndex = 0;
695         ExternalSymbolData.push_back(MSD);
696       } else {
697         MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
698         assert(MSD.SectionIndex && "Invalid section index!");
699         ExternalSymbolData.push_back(MSD);
700       }
701     }
702
703     // Now add the data for local symbols.
704     for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
705            ie = Asm.symbol_end(); it != ie; ++it) {
706       const MCSymbol &Symbol = it->getSymbol();
707
708       // Ignore assembler temporaries.
709       if (it->getSymbol().isTemporary())
710         continue;
711
712       if (it->isExternal() || Symbol.isUndefined())
713         continue;
714
715       uint64_t &Entry = StringIndexMap[Symbol.getName()];
716       if (!Entry) {
717         Entry = StringTable.size();
718         StringTable += Symbol.getName();
719         StringTable += '\x00';
720       }
721
722       MachSymbolData MSD;
723       MSD.SymbolData = it;
724       MSD.StringIndex = Entry;
725
726       if (Symbol.isAbsolute()) {
727         MSD.SectionIndex = 0;
728         LocalSymbolData.push_back(MSD);
729       } else {
730         MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
731         assert(MSD.SectionIndex && "Invalid section index!");
732         LocalSymbolData.push_back(MSD);
733       }
734     }
735
736     // External and undefined symbols are required to be in lexicographic order.
737     std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
738     std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
739
740     // Set the symbol indices.
741     Index = 0;
742     for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
743       LocalSymbolData[i].SymbolData->setIndex(Index++);
744     for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
745       ExternalSymbolData[i].SymbolData->setIndex(Index++);
746     for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
747       UndefinedSymbolData[i].SymbolData->setIndex(Index++);
748
749     // The string table is padded to a multiple of 4.
750     while (StringTable.size() % 4)
751       StringTable += '\x00';
752   }
753
754   void WriteObject(MCAssembler &Asm) {
755     unsigned NumSections = Asm.size();
756
757     // Compute the symbol -> symbol data map.
758     //
759     // FIXME: This should not be here.
760     DenseMap<const MCSymbol*, MCSymbolData *> SymbolMap;
761     for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
762            ie = Asm.symbol_end(); it != ie; ++it)
763       SymbolMap[&it->getSymbol()] = it;
764
765     // Create symbol data for any indirect symbols.
766     BindIndirectSymbols(Asm, SymbolMap);
767
768     // Compute symbol table information.
769     SmallString<256> StringTable;
770     std::vector<MachSymbolData> LocalSymbolData;
771     std::vector<MachSymbolData> ExternalSymbolData;
772     std::vector<MachSymbolData> UndefinedSymbolData;
773     unsigned NumSymbols = Asm.symbol_size();
774
775     // No symbol table command is written if there are no symbols.
776     if (NumSymbols)
777       ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
778                          UndefinedSymbolData);
779
780     // The section data starts after the header, the segment load command (and
781     // section headers) and the symbol table.
782     unsigned NumLoadCommands = 1;
783     uint64_t LoadCommandsSize =
784       SegmentLoadCommand32Size + NumSections * Section32Size;
785
786     // Add the symbol table load command sizes, if used.
787     if (NumSymbols) {
788       NumLoadCommands += 2;
789       LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
790     }
791
792     // Compute the total size of the section data, as well as its file size and
793     // vm size.
794     uint64_t SectionDataStart = Header32Size + LoadCommandsSize;
795     uint64_t SectionDataSize = 0;
796     uint64_t SectionDataFileSize = 0;
797     uint64_t VMSize = 0;
798     for (MCAssembler::iterator it = Asm.begin(),
799            ie = Asm.end(); it != ie; ++it) {
800       MCSectionData &SD = *it;
801
802       VMSize = std::max(VMSize, SD.getAddress() + SD.getSize());
803
804       if (isVirtualSection(SD.getSection()))
805         continue;
806
807       SectionDataSize = std::max(SectionDataSize,
808                                  SD.getAddress() + SD.getSize());
809       SectionDataFileSize = std::max(SectionDataFileSize,
810                                      SD.getAddress() + SD.getFileSize());
811     }
812
813     // The section data is padded to 4 bytes.
814     //
815     // FIXME: Is this machine dependent?
816     unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
817     SectionDataFileSize += SectionDataPadding;
818
819     // Write the prolog, starting with the header and load command...
820     WriteHeader32(NumLoadCommands, LoadCommandsSize,
821                   Asm.getSubsectionsViaSymbols());
822     WriteSegmentLoadCommand32(NumSections, VMSize,
823                               SectionDataStart, SectionDataSize);
824
825     // ... and then the section headers.
826     //
827     // We also compute the section relocations while we do this. Note that
828     // computing relocation info will also update the fixup to have the correct
829     // value; this will overwrite the appropriate data in the fragment when it
830     // is written.
831     std::vector<MachRelocationEntry> RelocInfos;
832     uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
833     for (MCAssembler::iterator it = Asm.begin(),
834            ie = Asm.end(); it != ie; ++it) {
835       MCSectionData &SD = *it;
836
837       // The assembler writes relocations in the reverse order they were seen.
838       //
839       // FIXME: It is probably more complicated than this.
840       unsigned NumRelocsStart = RelocInfos.size();
841       for (MCSectionData::reverse_iterator it2 = SD.rbegin(),
842              ie2 = SD.rend(); it2 != ie2; ++it2)
843         if (MCDataFragment *DF = dyn_cast<MCDataFragment>(&*it2))
844           for (unsigned i = 0, e = DF->fixup_size(); i != e; ++i)
845             ComputeRelocationInfo(Asm, *DF, DF->getFixups()[e - i - 1],
846                                   SymbolMap, RelocInfos);
847
848       unsigned NumRelocs = RelocInfos.size() - NumRelocsStart;
849       uint64_t SectionStart = SectionDataStart + SD.getAddress();
850       WriteSection32(SD, SectionStart, RelocTableEnd, NumRelocs);
851       RelocTableEnd += NumRelocs * RelocationInfoSize;
852     }
853
854     // Write the symbol table load command, if used.
855     if (NumSymbols) {
856       unsigned FirstLocalSymbol = 0;
857       unsigned NumLocalSymbols = LocalSymbolData.size();
858       unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
859       unsigned NumExternalSymbols = ExternalSymbolData.size();
860       unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
861       unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
862       unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
863       unsigned NumSymTabSymbols =
864         NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
865       uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
866       uint64_t IndirectSymbolOffset = 0;
867
868       // If used, the indirect symbols are written after the section data.
869       if (NumIndirectSymbols)
870         IndirectSymbolOffset = RelocTableEnd;
871
872       // The symbol table is written after the indirect symbol data.
873       uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
874
875       // The string table is written after symbol table.
876       uint64_t StringTableOffset =
877         SymbolTableOffset + NumSymTabSymbols * Nlist32Size;
878       WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
879                              StringTableOffset, StringTable.size());
880
881       WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
882                                FirstExternalSymbol, NumExternalSymbols,
883                                FirstUndefinedSymbol, NumUndefinedSymbols,
884                                IndirectSymbolOffset, NumIndirectSymbols);
885     }
886
887     // Write the actual section data.
888     for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
889       WriteFileData(OS, *it, *this);
890
891     // Write the extra padding.
892     WriteZeros(SectionDataPadding);
893
894     // Write the relocation entries.
895     for (unsigned i = 0, e = RelocInfos.size(); i != e; ++i) {
896       Write32(RelocInfos[i].Word0);
897       Write32(RelocInfos[i].Word1);
898     }
899
900     // Write the symbol table data, if used.
901     if (NumSymbols) {
902       // Write the indirect symbol entries.
903       for (MCAssembler::indirect_symbol_iterator
904              it = Asm.indirect_symbol_begin(),
905              ie = Asm.indirect_symbol_end(); it != ie; ++it) {
906         // Indirect symbols in the non lazy symbol pointer section have some
907         // special handling.
908         const MCSectionMachO &Section =
909           static_cast<const MCSectionMachO&>(it->SectionData->getSection());
910         unsigned Type =
911           Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
912         if (Type == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
913           // If this symbol is defined and internal, mark it as such.
914           if (it->Symbol->isDefined() &&
915               !SymbolMap.lookup(it->Symbol)->isExternal()) {
916             uint32_t Flags = ISF_Local;
917             if (it->Symbol->isAbsolute())
918               Flags |= ISF_Absolute;
919             Write32(Flags);
920             continue;
921           }
922         }
923
924         Write32(SymbolMap[it->Symbol]->getIndex());
925       }
926
927       // FIXME: Check that offsets match computed ones.
928
929       // Write the symbol table entries.
930       for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
931         WriteNlist32(LocalSymbolData[i]);
932       for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
933         WriteNlist32(ExternalSymbolData[i]);
934       for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
935         WriteNlist32(UndefinedSymbolData[i]);
936
937       // Write the string table.
938       OS << StringTable.str();
939     }
940   }
941
942   void ApplyFixup(const MCAsmFixup &Fixup, MCDataFragment &DF) {
943     unsigned Size = 1 << getFixupKindLog2Size(Fixup.Kind);
944
945     // FIXME: Endianness assumption.
946     assert(Fixup.Offset + Size <= DF.getContents().size() &&
947            "Invalid fixup offset!");
948     for (unsigned i = 0; i != Size; ++i)
949       DF.getContents()[Fixup.Offset + i] = uint8_t(Fixup.FixedValue >> (i * 8));
950   }
951 };
952
953 /* *** */
954
955 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
956 }
957
958 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
959   : Kind(_Kind),
960     Parent(_Parent),
961     FileSize(~UINT64_C(0))
962 {
963   if (Parent)
964     Parent->getFragmentList().push_back(this);
965 }
966
967 MCFragment::~MCFragment() {
968 }
969
970 uint64_t MCFragment::getAddress() const {
971   assert(getParent() && "Missing Section!");
972   return getParent()->getAddress() + Offset;
973 }
974
975 /* *** */
976
977 MCSectionData::MCSectionData() : Section(0) {}
978
979 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
980   : Section(&_Section),
981     Alignment(1),
982     Address(~UINT64_C(0)),
983     Size(~UINT64_C(0)),
984     FileSize(~UINT64_C(0)),
985     HasInstructions(false)
986 {
987   if (A)
988     A->getSectionList().push_back(this);
989 }
990
991 /* *** */
992
993 MCSymbolData::MCSymbolData() : Symbol(0) {}
994
995 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
996                            uint64_t _Offset, MCAssembler *A)
997   : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
998     IsExternal(false), IsPrivateExtern(false),
999     CommonSize(0), CommonAlign(0), Flags(0), Index(0)
1000 {
1001   if (A)
1002     A->getSymbolList().push_back(this);
1003 }
1004
1005 /* *** */
1006
1007 MCAssembler::MCAssembler(MCContext &_Context, raw_ostream &_OS)
1008   : Context(_Context), OS(_OS), SubsectionsViaSymbols(false)
1009 {
1010 }
1011
1012 MCAssembler::~MCAssembler() {
1013 }
1014
1015 void MCAssembler::LayoutSection(MCSectionData &SD) {
1016   uint64_t Address = SD.getAddress();
1017
1018   for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
1019     MCFragment &F = *it;
1020
1021     F.setOffset(Address - SD.getAddress());
1022
1023     // Evaluate fragment size.
1024     switch (F.getKind()) {
1025     case MCFragment::FT_Align: {
1026       MCAlignFragment &AF = cast<MCAlignFragment>(F);
1027
1028       uint64_t Size = OffsetToAlignment(Address, AF.getAlignment());
1029       if (Size > AF.getMaxBytesToEmit())
1030         AF.setFileSize(0);
1031       else
1032         AF.setFileSize(Size);
1033       break;
1034     }
1035
1036     case MCFragment::FT_Data:
1037     case MCFragment::FT_Fill:
1038       F.setFileSize(F.getMaxFileSize());
1039       break;
1040
1041     case MCFragment::FT_Org: {
1042       MCOrgFragment &OF = cast<MCOrgFragment>(F);
1043
1044       MCValue Target;
1045       if (!OF.getOffset().EvaluateAsRelocatable(Target))
1046         llvm_report_error("expected relocatable expression");
1047
1048       if (!Target.isAbsolute())
1049         llvm_unreachable("FIXME: Not yet implemented!");
1050       uint64_t OrgOffset = Target.getConstant();
1051       uint64_t Offset = Address - SD.getAddress();
1052
1053       // FIXME: We need a way to communicate this error.
1054       if (OrgOffset < Offset)
1055         llvm_report_error("invalid .org offset '" + Twine(OrgOffset) +
1056                           "' (at offset '" + Twine(Offset) + "'");
1057
1058       F.setFileSize(OrgOffset - Offset);
1059       break;
1060     }
1061
1062     case MCFragment::FT_ZeroFill: {
1063       MCZeroFillFragment &ZFF = cast<MCZeroFillFragment>(F);
1064
1065       // Align the fragment offset; it is safe to adjust the offset freely since
1066       // this is only in virtual sections.
1067       Address = RoundUpToAlignment(Address, ZFF.getAlignment());
1068       F.setOffset(Address - SD.getAddress());
1069
1070       // FIXME: This is misnamed.
1071       F.setFileSize(ZFF.getSize());
1072       break;
1073     }
1074     }
1075
1076     Address += F.getFileSize();
1077   }
1078
1079   // Set the section sizes.
1080   SD.setSize(Address - SD.getAddress());
1081   if (isVirtualSection(SD.getSection()))
1082     SD.setFileSize(0);
1083   else
1084     SD.setFileSize(Address - SD.getAddress());
1085 }
1086
1087 /// WriteNopData - Write optimal nops to the output file for the \arg Count
1088 /// bytes.  This returns the number of bytes written.  It may return 0 if
1089 /// the \arg Count is more than the maximum optimal nops.
1090 ///
1091 /// FIXME this is X86 32-bit specific and should move to a better place.
1092 static uint64_t WriteNopData(uint64_t Count, MachObjectWriter &MOW) {
1093   static const uint8_t Nops[16][16] = {
1094     // nop
1095     {0x90},
1096     // xchg %ax,%ax
1097     {0x66, 0x90},
1098     // nopl (%[re]ax)
1099     {0x0f, 0x1f, 0x00},
1100     // nopl 0(%[re]ax)
1101     {0x0f, 0x1f, 0x40, 0x00},
1102     // nopl 0(%[re]ax,%[re]ax,1)
1103     {0x0f, 0x1f, 0x44, 0x00, 0x00},
1104     // nopw 0(%[re]ax,%[re]ax,1)
1105     {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1106     // nopl 0L(%[re]ax)
1107     {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1108     // nopl 0L(%[re]ax,%[re]ax,1)
1109     {0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1110     // nopw 0L(%[re]ax,%[re]ax,1)
1111     {0x66, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1112     // nopw %cs:0L(%[re]ax,%[re]ax,1)
1113     {0x66, 0x2e, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1114     // nopl 0(%[re]ax,%[re]ax,1)
1115     // nopw 0(%[re]ax,%[re]ax,1)
1116     {0x0f, 0x1f, 0x44, 0x00, 0x00,
1117      0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1118     // nopw 0(%[re]ax,%[re]ax,1)
1119     // nopw 0(%[re]ax,%[re]ax,1)
1120     {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00,
1121      0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1122     // nopw 0(%[re]ax,%[re]ax,1)
1123     // nopl 0L(%[re]ax) */
1124     {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00,
1125      0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1126     // nopl 0L(%[re]ax)
1127     // nopl 0L(%[re]ax)
1128     {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00,
1129      0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1130     // nopl 0L(%[re]ax)
1131     // nopl 0L(%[re]ax,%[re]ax,1)
1132     {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00,
1133      0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00}
1134   };
1135
1136   if (Count > 15)
1137     return 0;
1138
1139   for (uint64_t i = 0; i < Count; i++)
1140     MOW.Write8 (uint8_t(Nops[Count - 1][i]));
1141
1142   return Count;
1143 }
1144
1145 /// WriteFileData - Write the \arg F data to the output file.
1146 static void WriteFileData(raw_ostream &OS, const MCFragment &F,
1147                           MachObjectWriter &MOW) {
1148   uint64_t Start = OS.tell();
1149   (void) Start;
1150
1151   ++EmittedFragments;
1152
1153   // FIXME: Embed in fragments instead?
1154   switch (F.getKind()) {
1155   case MCFragment::FT_Align: {
1156     MCAlignFragment &AF = cast<MCAlignFragment>(F);
1157     uint64_t Count = AF.getFileSize() / AF.getValueSize();
1158
1159     // FIXME: This error shouldn't actually occur (the front end should emit
1160     // multiple .align directives to enforce the semantics it wants), but is
1161     // severe enough that we want to report it. How to handle this?
1162     if (Count * AF.getValueSize() != AF.getFileSize())
1163       llvm_report_error("undefined .align directive, value size '" +
1164                         Twine(AF.getValueSize()) +
1165                         "' is not a divisor of padding size '" +
1166                         Twine(AF.getFileSize()) + "'");
1167
1168     // See if we are aligning with nops, and if so do that first to try to fill
1169     // the Count bytes.  Then if that did not fill any bytes or there are any
1170     // bytes left to fill use the the Value and ValueSize to fill the rest.
1171     if (AF.getEmitNops()) {
1172       uint64_t NopByteCount = WriteNopData(Count, MOW);
1173       Count -= NopByteCount;
1174     }
1175
1176     for (uint64_t i = 0; i != Count; ++i) {
1177       switch (AF.getValueSize()) {
1178       default:
1179         assert(0 && "Invalid size!");
1180       case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
1181       case 2: MOW.Write16(uint16_t(AF.getValue())); break;
1182       case 4: MOW.Write32(uint32_t(AF.getValue())); break;
1183       case 8: MOW.Write64(uint64_t(AF.getValue())); break;
1184       }
1185     }
1186     break;
1187   }
1188
1189   case MCFragment::FT_Data: {
1190     MCDataFragment &DF = cast<MCDataFragment>(F);
1191
1192     // Apply the fixups.
1193     //
1194     // FIXME: Move elsewhere.
1195     for (MCDataFragment::const_fixup_iterator it = DF.fixup_begin(),
1196            ie = DF.fixup_end(); it != ie; ++it)
1197       MOW.ApplyFixup(*it, DF);
1198
1199     OS << cast<MCDataFragment>(F).getContents().str();
1200     break;
1201   }
1202
1203   case MCFragment::FT_Fill: {
1204     MCFillFragment &FF = cast<MCFillFragment>(F);
1205     for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
1206       switch (FF.getValueSize()) {
1207       default:
1208         assert(0 && "Invalid size!");
1209       case 1: MOW.Write8 (uint8_t (FF.getValue())); break;
1210       case 2: MOW.Write16(uint16_t(FF.getValue())); break;
1211       case 4: MOW.Write32(uint32_t(FF.getValue())); break;
1212       case 8: MOW.Write64(uint64_t(FF.getValue())); break;
1213       }
1214     }
1215     break;
1216   }
1217
1218   case MCFragment::FT_Org: {
1219     MCOrgFragment &OF = cast<MCOrgFragment>(F);
1220
1221     for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
1222       MOW.Write8(uint8_t(OF.getValue()));
1223
1224     break;
1225   }
1226
1227   case MCFragment::FT_ZeroFill: {
1228     assert(0 && "Invalid zero fill fragment in concrete section!");
1229     break;
1230   }
1231   }
1232
1233   assert(OS.tell() - Start == F.getFileSize());
1234 }
1235
1236 /// WriteFileData - Write the \arg SD data to the output file.
1237 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
1238                           MachObjectWriter &MOW) {
1239   // Ignore virtual sections.
1240   if (isVirtualSection(SD.getSection())) {
1241     assert(SD.getFileSize() == 0);
1242     return;
1243   }
1244
1245   uint64_t Start = OS.tell();
1246   (void) Start;
1247
1248   for (MCSectionData::const_iterator it = SD.begin(),
1249          ie = SD.end(); it != ie; ++it)
1250     WriteFileData(OS, *it, MOW);
1251
1252   // Add section padding.
1253   assert(SD.getFileSize() >= SD.getSize() && "Invalid section sizes!");
1254   MOW.WriteZeros(SD.getFileSize() - SD.getSize());
1255
1256   assert(OS.tell() - Start == SD.getFileSize());
1257 }
1258
1259 void MCAssembler::Finish() {
1260   DEBUG_WITH_TYPE("mc-dump", {
1261       llvm::errs() << "assembler backend - pre-layout\n--\n";
1262       dump(); });
1263
1264   // Layout the concrete sections and fragments.
1265   uint64_t Address = 0;
1266   MCSectionData *Prev = 0;
1267   for (iterator it = begin(), ie = end(); it != ie; ++it) {
1268     MCSectionData &SD = *it;
1269
1270     // Skip virtual sections.
1271     if (isVirtualSection(SD.getSection()))
1272       continue;
1273
1274     // Align this section if necessary by adding padding bytes to the previous
1275     // section.
1276     if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment())) {
1277       assert(Prev && "Missing prev section!");
1278       Prev->setFileSize(Prev->getFileSize() + Pad);
1279       Address += Pad;
1280     }
1281
1282     // Layout the section fragments and its size.
1283     SD.setAddress(Address);
1284     LayoutSection(SD);
1285     Address += SD.getFileSize();
1286
1287     Prev = &SD;
1288   }
1289
1290   // Layout the virtual sections.
1291   for (iterator it = begin(), ie = end(); it != ie; ++it) {
1292     MCSectionData &SD = *it;
1293
1294     if (!isVirtualSection(SD.getSection()))
1295       continue;
1296
1297     // Align this section if necessary by adding padding bytes to the previous
1298     // section.
1299     if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment()))
1300       Address += Pad;
1301
1302     SD.setAddress(Address);
1303     LayoutSection(SD);
1304     Address += SD.getSize();
1305
1306   }
1307
1308   DEBUG_WITH_TYPE("mc-dump", {
1309       llvm::errs() << "assembler backend - post-layout\n--\n";
1310       dump(); });
1311
1312   // Write the object file.
1313   MachObjectWriter MOW(OS);
1314   MOW.WriteObject(*this);
1315
1316   OS.flush();
1317 }
1318
1319
1320 // Debugging methods
1321
1322 namespace llvm {
1323
1324 raw_ostream &operator<<(raw_ostream &OS, const MCAsmFixup &AF) {
1325   OS << "<MCAsmFixup" << " Offset:" << AF.Offset << " Value:" << *AF.Value
1326      << " Kind:" << AF.Kind << ">";
1327   return OS;
1328 }
1329
1330 }
1331
1332 void MCFragment::dump() {
1333   raw_ostream &OS = llvm::errs();
1334
1335   OS << "<MCFragment " << (void*) this << " Offset:" << Offset
1336      << " FileSize:" << FileSize;
1337
1338   OS << ">";
1339 }
1340
1341 void MCAlignFragment::dump() {
1342   raw_ostream &OS = llvm::errs();
1343
1344   OS << "<MCAlignFragment ";
1345   this->MCFragment::dump();
1346   OS << "\n       ";
1347   OS << " Alignment:" << getAlignment()
1348      << " Value:" << getValue() << " ValueSize:" << getValueSize()
1349      << " MaxBytesToEmit:" << getMaxBytesToEmit() << ">";
1350 }
1351
1352 void MCDataFragment::dump() {
1353   raw_ostream &OS = llvm::errs();
1354
1355   OS << "<MCDataFragment ";
1356   this->MCFragment::dump();
1357   OS << "\n       ";
1358   OS << " Contents:[";
1359   for (unsigned i = 0, e = getContents().size(); i != e; ++i) {
1360     if (i) OS << ",";
1361     OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1362   }
1363   OS << "] (" << getContents().size() << " bytes)";
1364
1365   if (!getFixups().empty()) {
1366     OS << ",\n       ";
1367     OS << " Fixups:[";
1368     for (fixup_iterator it = fixup_begin(), ie = fixup_end(); it != ie; ++it) {
1369       if (it != fixup_begin()) OS << ",\n                ";
1370       OS << *it;
1371     }
1372     OS << "]";
1373   }
1374
1375   OS << ">";
1376 }
1377
1378 void MCFillFragment::dump() {
1379   raw_ostream &OS = llvm::errs();
1380
1381   OS << "<MCFillFragment ";
1382   this->MCFragment::dump();
1383   OS << "\n       ";
1384   OS << " Value:" << getValue() << " ValueSize:" << getValueSize()
1385      << " Count:" << getCount() << ">";
1386 }
1387
1388 void MCOrgFragment::dump() {
1389   raw_ostream &OS = llvm::errs();
1390
1391   OS << "<MCOrgFragment ";
1392   this->MCFragment::dump();
1393   OS << "\n       ";
1394   OS << " Offset:" << getOffset() << " Value:" << getValue() << ">";
1395 }
1396
1397 void MCZeroFillFragment::dump() {
1398   raw_ostream &OS = llvm::errs();
1399
1400   OS << "<MCZeroFillFragment ";
1401   this->MCFragment::dump();
1402   OS << "\n       ";
1403   OS << " Size:" << getSize() << " Alignment:" << getAlignment() << ">";
1404 }
1405
1406 void MCSectionData::dump() {
1407   raw_ostream &OS = llvm::errs();
1408
1409   OS << "<MCSectionData";
1410   OS << " Alignment:" << getAlignment() << " Address:" << Address
1411      << " Size:" << Size << " FileSize:" << FileSize
1412      << " Fragments:[\n      ";
1413   for (iterator it = begin(), ie = end(); it != ie; ++it) {
1414     if (it != begin()) OS << ",\n      ";
1415     it->dump();
1416   }
1417   OS << "]>";
1418 }
1419
1420 void MCSymbolData::dump() {
1421   raw_ostream &OS = llvm::errs();
1422
1423   OS << "<MCSymbolData Symbol:" << getSymbol()
1424      << " Fragment:" << getFragment() << " Offset:" << getOffset()
1425      << " Flags:" << getFlags() << " Index:" << getIndex();
1426   if (isCommon())
1427     OS << " (common, size:" << getCommonSize()
1428        << " align: " << getCommonAlignment() << ")";
1429   if (isExternal())
1430     OS << " (external)";
1431   if (isPrivateExtern())
1432     OS << " (private extern)";
1433   OS << ">";
1434 }
1435
1436 void MCAssembler::dump() {
1437   raw_ostream &OS = llvm::errs();
1438
1439   OS << "<MCAssembler\n";
1440   OS << "  Sections:[\n    ";
1441   for (iterator it = begin(), ie = end(); it != ie; ++it) {
1442     if (it != begin()) OS << ",\n    ";
1443     it->dump();
1444   }
1445   OS << "],\n";
1446   OS << "  Symbols:[";
1447
1448   for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1449     if (it != symbol_begin()) OS << ",\n           ";
1450     it->dump();
1451   }
1452   OS << "]>\n";
1453 }