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