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