1 //===- lib/MC/MCAssembler.cpp - Assembler Backend Implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #define DEBUG_TYPE "assembler"
11 #include "llvm/MC/MCAssembler.h"
12 #include "llvm/MC/MCSectionMachO.h"
13 #include "llvm/Target/TargetMachOWriterInfo.h"
14 #include "llvm/ADT/DenseMap.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/Support/ErrorHandling.h"
20 #include "llvm/Support/raw_ostream.h"
24 class MachObjectWriter;
26 STATISTIC(EmittedFragments, "Number of emitted assembler fragments");
28 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
29 MachObjectWriter &MOW);
31 class MachObjectWriter {
32 // See <mach-o/loader.h>.
34 Header_Magic32 = 0xFEEDFACE,
35 Header_Magic64 = 0xFEEDFACF
38 static const unsigned Header32Size = 28;
39 static const unsigned Header64Size = 32;
40 static const unsigned SegmentLoadCommand32Size = 56;
41 static const unsigned Section32Size = 68;
42 static const unsigned SymtabLoadCommandSize = 24;
43 static const unsigned DysymtabLoadCommandSize = 80;
44 static const unsigned Nlist32Size = 12;
50 enum LoadCommandType {
56 // See <mach-o/nlist.h>.
63 enum SymbolTypeFlags {
64 // If any of these bits are set, then the entry is a stab entry number (see
65 // <mach-o/stab.h>. Otherwise the other masks apply.
66 STF_StabsEntryMask = 0xe0,
70 STF_PrivateExtern = 0x10
73 /// IndirectSymbolFlags - Flags for encoding special values in the indirect
75 enum IndirectSymbolFlags {
76 ISF_Local = 0x80000000,
77 ISF_Absolute = 0x40000000
80 /// MachSymbolData - Helper struct for containing some precomputed information
82 struct MachSymbolData {
83 MCSymbolData *SymbolData;
87 // Support lexicographic sorting.
88 bool operator<(const MachSymbolData &RHS) const {
89 const std::string &Name = SymbolData->getSymbol().getName();
90 return Name < RHS.SymbolData->getSymbol().getName();
98 MachObjectWriter(raw_ostream &_OS, bool _IsLSB = true)
99 : OS(_OS), IsLSB(_IsLSB) {
102 /// @name Helper Methods
105 void Write8(uint8_t Value) {
109 void Write16(uint16_t Value) {
111 Write8(uint8_t(Value >> 0));
112 Write8(uint8_t(Value >> 8));
114 Write8(uint8_t(Value >> 8));
115 Write8(uint8_t(Value >> 0));
119 void Write32(uint32_t Value) {
121 Write16(uint16_t(Value >> 0));
122 Write16(uint16_t(Value >> 16));
124 Write16(uint16_t(Value >> 16));
125 Write16(uint16_t(Value >> 0));
129 void Write64(uint64_t Value) {
131 Write32(uint32_t(Value >> 0));
132 Write32(uint32_t(Value >> 32));
134 Write32(uint32_t(Value >> 32));
135 Write32(uint32_t(Value >> 0));
139 void WriteZeros(unsigned N) {
140 const char Zeros[16] = { 0 };
142 for (unsigned i = 0, e = N / 16; i != e; ++i)
143 OS << StringRef(Zeros, 16);
145 OS << StringRef(Zeros, N % 16);
148 void WriteString(const StringRef &Str, unsigned ZeroFillSize = 0) {
151 WriteZeros(ZeroFillSize - Str.size());
156 void WriteHeader32(unsigned NumLoadCommands, unsigned LoadCommandsSize) {
157 // struct mach_header (28 bytes)
159 uint64_t Start = OS.tell();
162 Write32(Header_Magic32);
164 // FIXME: Support cputype.
165 Write32(TargetMachOWriterInfo::HDR_CPU_TYPE_I386);
167 // FIXME: Support cpusubtype.
168 Write32(TargetMachOWriterInfo::HDR_CPU_SUBTYPE_I386_ALL);
172 // Object files have a single load command, the segment.
173 Write32(NumLoadCommands);
174 Write32(LoadCommandsSize);
177 assert(OS.tell() - Start == Header32Size);
180 /// WriteSegmentLoadCommand32 - Write a 32-bit segment load command.
182 /// \arg NumSections - The number of sections in this segment.
183 /// \arg SectionDataSize - The total size of the sections.
184 void WriteSegmentLoadCommand32(unsigned NumSections,
185 uint64_t SectionDataStartOffset,
186 uint64_t SectionDataSize) {
187 // struct segment_command (56 bytes)
189 uint64_t Start = OS.tell();
192 Write32(LCT_Segment);
193 Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
196 Write32(0); // vmaddr
197 Write32(SectionDataSize); // vmsize
198 Write32(SectionDataStartOffset); // file offset
199 Write32(SectionDataSize); // file size
200 Write32(0x7); // maxprot
201 Write32(0x7); // initprot
202 Write32(NumSections);
205 assert(OS.tell() - Start == SegmentLoadCommand32Size);
208 void WriteSection32(const MCSectionData &SD, uint64_t FileOffset) {
209 // struct section (68 bytes)
211 uint64_t Start = OS.tell();
214 // FIXME: cast<> support!
215 const MCSectionMachO &Section =
216 static_cast<const MCSectionMachO&>(SD.getSection());
217 WriteString(Section.getSectionName(), 16);
218 WriteString(Section.getSegmentName(), 16);
219 Write32(SD.getAddress()); // address
220 Write32(SD.getSize()); // size
223 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
224 Write32(Log2_32(SD.getAlignment()));
225 Write32(0); // file offset of relocation entries
226 Write32(0); // number of relocation entrions
227 Write32(Section.getTypeAndAttributes());
228 Write32(0); // reserved1
229 Write32(Section.getStubSize()); // reserved2
231 assert(OS.tell() - Start == Section32Size);
234 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
235 uint32_t StringTableOffset,
236 uint32_t StringTableSize) {
237 // struct symtab_command (24 bytes)
239 uint64_t Start = OS.tell();
243 Write32(SymtabLoadCommandSize);
244 Write32(SymbolOffset);
246 Write32(StringTableOffset);
247 Write32(StringTableSize);
249 assert(OS.tell() - Start == SymtabLoadCommandSize);
252 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
253 uint32_t NumLocalSymbols,
254 uint32_t FirstExternalSymbol,
255 uint32_t NumExternalSymbols,
256 uint32_t FirstUndefinedSymbol,
257 uint32_t NumUndefinedSymbols,
258 uint32_t IndirectSymbolOffset,
259 uint32_t NumIndirectSymbols) {
260 // struct dysymtab_command (80 bytes)
262 uint64_t Start = OS.tell();
265 Write32(LCT_Dysymtab);
266 Write32(DysymtabLoadCommandSize);
267 Write32(FirstLocalSymbol);
268 Write32(NumLocalSymbols);
269 Write32(FirstExternalSymbol);
270 Write32(NumExternalSymbols);
271 Write32(FirstUndefinedSymbol);
272 Write32(NumUndefinedSymbols);
273 Write32(0); // tocoff
275 Write32(0); // modtaboff
276 Write32(0); // nmodtab
277 Write32(0); // extrefsymoff
278 Write32(0); // nextrefsyms
279 Write32(IndirectSymbolOffset);
280 Write32(NumIndirectSymbols);
281 Write32(0); // extreloff
282 Write32(0); // nextrel
283 Write32(0); // locreloff
284 Write32(0); // nlocrel
286 assert(OS.tell() - Start == DysymtabLoadCommandSize);
289 void WriteNlist32(MachSymbolData &MSD) {
290 MCSymbolData &Data = *MSD.SymbolData;
291 MCSymbol &Symbol = Data.getSymbol();
294 // Set the N_TYPE bits. See <mach-o/nlist.h>.
296 // FIXME: Are the prebound or indirect fields possible here?
297 if (Symbol.isUndefined())
298 Type = STT_Undefined;
299 else if (Symbol.isAbsolute())
304 // FIXME: Set STAB bits.
306 if (Data.isPrivateExtern())
307 Type |= STF_PrivateExtern;
310 if (Data.isExternal() || Symbol.isUndefined())
311 Type |= STF_External;
313 // struct nlist (12 bytes)
315 Write32(MSD.StringIndex);
317 Write8(MSD.SectionIndex);
319 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
321 Write16(Data.getFlags() & 0xFFFF);
323 // Write the symbol address.
324 uint32_t Address = 0;
325 if (Symbol.isDefined()) {
326 if (Symbol.isAbsolute()) {
327 llvm_unreachable("FIXME: Not yet implemented!");
329 Address = Data.getFragment()->getAddress() + Data.getOffset();
335 void BindIndirectSymbols(MCAssembler &Asm,
336 DenseMap<MCSymbol*, MCSymbolData*> &SymbolMap) {
337 // This is the point where 'as' creates actual symbols for indirect symbols
338 // (in the following two passes). It would be easier for us to do this
339 // sooner when we see the attribute, but that makes getting the order in the
340 // symbol table much more complicated than it is worth.
342 // FIXME: Revisit this when the dust settles.
344 // Bind non lazy symbol pointers first.
345 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
346 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
347 // FIXME: cast<> support!
348 const MCSectionMachO &Section =
349 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
352 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
353 if (Type != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
356 MCSymbolData *&Entry = SymbolMap[it->Symbol];
358 Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
361 // Then lazy symbol pointers and symbol stubs.
362 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
363 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
364 // FIXME: cast<> support!
365 const MCSectionMachO &Section =
366 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
369 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
370 if (Type != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
371 Type != MCSectionMachO::S_SYMBOL_STUBS)
374 MCSymbolData *&Entry = SymbolMap[it->Symbol];
376 Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
378 // Set the symbol type to undefined lazy, but only on construction.
380 // FIXME: Do not hardcode.
381 Entry->setFlags(Entry->getFlags() | 0x0001);
386 /// ComputeSymbolTable - Compute the symbol table data
388 /// \param StringTable [out] - The string table data.
389 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
391 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
392 std::vector<MachSymbolData> &LocalSymbolData,
393 std::vector<MachSymbolData> &ExternalSymbolData,
394 std::vector<MachSymbolData> &UndefinedSymbolData) {
395 // Build section lookup table.
396 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
398 for (MCAssembler::iterator it = Asm.begin(),
399 ie = Asm.end(); it != ie; ++it, ++Index)
400 SectionIndexMap[&it->getSection()] = Index;
401 assert(Index <= 256 && "Too many sections!");
403 // Index 0 is always the empty string.
404 StringMap<uint64_t> StringIndexMap;
405 StringTable += '\x00';
407 // Build the symbol arrays and the string table, but only for non-local
410 // The particular order that we collect the symbols and create the string
411 // table, then sort the symbols is chosen to match 'as'. Even though it
412 // doesn't matter for correctness, this is important for letting us diff .o
414 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
415 ie = Asm.symbol_end(); it != ie; ++it) {
416 MCSymbol &Symbol = it->getSymbol();
418 if (!it->isExternal() && !Symbol.isUndefined())
421 uint64_t &Entry = StringIndexMap[Symbol.getName()];
423 Entry = StringTable.size();
424 StringTable += Symbol.getName();
425 StringTable += '\x00';
430 MSD.StringIndex = Entry;
432 if (Symbol.isUndefined()) {
433 MSD.SectionIndex = 0;
434 UndefinedSymbolData.push_back(MSD);
435 } else if (Symbol.isAbsolute()) {
436 MSD.SectionIndex = 0;
437 ExternalSymbolData.push_back(MSD);
439 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
440 assert(MSD.SectionIndex && "Invalid section index!");
441 ExternalSymbolData.push_back(MSD);
445 // Now add the data for local symbols.
446 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
447 ie = Asm.symbol_end(); it != ie; ++it) {
448 MCSymbol &Symbol = it->getSymbol();
450 if (it->isExternal() || Symbol.isUndefined())
453 uint64_t &Entry = StringIndexMap[Symbol.getName()];
455 Entry = StringTable.size();
456 StringTable += Symbol.getName();
457 StringTable += '\x00';
462 MSD.StringIndex = Entry;
464 if (Symbol.isAbsolute()) {
465 MSD.SectionIndex = 0;
466 LocalSymbolData.push_back(MSD);
468 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
469 assert(MSD.SectionIndex && "Invalid section index!");
470 LocalSymbolData.push_back(MSD);
474 // External and undefined symbols are required to be in lexicographic order.
475 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
476 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
478 // The string table is padded to a multiple of 4.
480 // FIXME: Check to see if this varies per arch.
481 while (StringTable.size() % 4)
482 StringTable += '\x00';
485 void WriteObject(MCAssembler &Asm) {
486 unsigned NumSections = Asm.size();
488 // Compute the symbol -> symbol data map.
490 // FIXME: This should not be here.
491 DenseMap<MCSymbol*, MCSymbolData *> SymbolMap;
492 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
493 ie = Asm.symbol_end(); it != ie; ++it)
494 SymbolMap[&it->getSymbol()] = it;
496 // Create symbol data for any indirect symbols.
497 BindIndirectSymbols(Asm, SymbolMap);
499 // Compute symbol table information.
500 SmallString<256> StringTable;
501 std::vector<MachSymbolData> LocalSymbolData;
502 std::vector<MachSymbolData> ExternalSymbolData;
503 std::vector<MachSymbolData> UndefinedSymbolData;
504 unsigned NumSymbols = Asm.symbol_size();
506 // No symbol table command is written if there are no symbols.
508 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
509 UndefinedSymbolData);
511 // The section data starts after the header, the segment load command (and
512 // section headers) and the symbol table.
513 unsigned NumLoadCommands = 1;
514 uint64_t LoadCommandsSize =
515 SegmentLoadCommand32Size + NumSections * Section32Size;
517 // Add the symbol table load command sizes, if used.
519 NumLoadCommands += 2;
520 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
523 uint64_t SectionDataStart = Header32Size + LoadCommandsSize;
524 uint64_t SectionDataEnd = SectionDataStart;
525 uint64_t SectionDataSize = 0;
526 if (!Asm.getSectionList().empty()) {
527 MCSectionData &SD = Asm.getSectionList().back();
528 SectionDataSize = SD.getAddress() + SD.getSize();
529 SectionDataEnd = SectionDataStart + SD.getAddress() + SD.getFileSize();
532 // Write the prolog, starting with the header and load command...
533 WriteHeader32(NumLoadCommands, LoadCommandsSize);
534 WriteSegmentLoadCommand32(NumSections, SectionDataStart, SectionDataSize);
536 // ... and then the section headers.
537 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
538 WriteSection32(*it, SectionDataStart + it->getAddress());
540 // Write the symbol table load command, if used.
542 unsigned FirstLocalSymbol = 0;
543 unsigned NumLocalSymbols = LocalSymbolData.size();
544 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
545 unsigned NumExternalSymbols = ExternalSymbolData.size();
546 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
547 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
548 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
549 unsigned NumSymTabSymbols =
550 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
551 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
552 uint64_t IndirectSymbolOffset = 0;
554 // If used, the indirect symbols are written after the section data.
555 if (NumIndirectSymbols)
556 IndirectSymbolOffset = SectionDataEnd;
558 // The symbol table is written after the indirect symbol data.
559 uint64_t SymbolTableOffset = SectionDataEnd + IndirectSymbolSize;
561 // The string table is written after symbol table.
562 uint64_t StringTableOffset =
563 SymbolTableOffset + NumSymTabSymbols * Nlist32Size;
564 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
565 StringTableOffset, StringTable.size());
567 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
568 FirstExternalSymbol, NumExternalSymbols,
569 FirstUndefinedSymbol, NumUndefinedSymbols,
570 IndirectSymbolOffset, NumIndirectSymbols);
573 // Write the actual section data.
574 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
575 WriteFileData(OS, *it, *this);
577 // Write the symbol table data, if used.
579 // FIXME: We shouldn't need this index table.
580 DenseMap<MCSymbol*, unsigned> SymbolIndexMap;
581 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
582 MCSymbol &Symbol = LocalSymbolData[i].SymbolData->getSymbol();
583 SymbolIndexMap.insert(std::make_pair(&Symbol, SymbolIndexMap.size()));
585 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
586 MCSymbol &Symbol = ExternalSymbolData[i].SymbolData->getSymbol();
587 SymbolIndexMap.insert(std::make_pair(&Symbol, SymbolIndexMap.size()));
589 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
590 MCSymbol &Symbol = UndefinedSymbolData[i].SymbolData->getSymbol();
591 SymbolIndexMap.insert(std::make_pair(&Symbol, SymbolIndexMap.size()));
594 // Write the indirect symbol entries.
596 // FIXME: We need the symbol index map for this.
597 for (MCAssembler::indirect_symbol_iterator
598 it = Asm.indirect_symbol_begin(),
599 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
600 // Indirect symbols in the non lazy symbol pointer section have some
602 const MCSectionMachO &Section =
603 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
605 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
606 if (Type == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
607 // If this symbol is defined and internal, mark it as such.
608 if (it->Symbol->isDefined() &&
609 !SymbolMap.lookup(it->Symbol)->isExternal()) {
610 uint32_t Flags = ISF_Local;
611 if (it->Symbol->isAbsolute())
612 Flags |= ISF_Absolute;
618 Write32(SymbolIndexMap[it->Symbol]);
621 // FIXME: Check that offsets match computed ones.
623 // Write the symbol table entries.
624 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
625 WriteNlist32(LocalSymbolData[i]);
626 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
627 WriteNlist32(ExternalSymbolData[i]);
628 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
629 WriteNlist32(UndefinedSymbolData[i]);
631 // Write the string table.
632 OS << StringTable.str();
639 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
642 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
645 FileSize(~UINT64_C(0))
648 Parent->getFragmentList().push_back(this);
651 MCFragment::~MCFragment() {
654 uint64_t MCFragment::getAddress() const {
655 assert(getParent() && "Missing Section!");
656 return getParent()->getAddress() + Offset;
661 MCSectionData::MCSectionData() : Section(*(MCSection*)0) {}
663 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
666 Address(~UINT64_C(0)),
668 FileSize(~UINT64_C(0))
671 A->getSectionList().push_back(this);
676 MCSymbolData::MCSymbolData() : Symbol(*(MCSymbol*)0) {}
678 MCSymbolData::MCSymbolData(MCSymbol &_Symbol, MCFragment *_Fragment,
679 uint64_t _Offset, MCAssembler *A)
680 : Symbol(_Symbol), Fragment(_Fragment), Offset(_Offset),
681 IsExternal(false), IsPrivateExtern(false), Flags(0)
684 A->getSymbolList().push_back(this);
689 MCAssembler::MCAssembler(raw_ostream &_OS) : OS(_OS) {}
691 MCAssembler::~MCAssembler() {
694 void MCAssembler::LayoutSection(MCSectionData &SD, unsigned NextAlign) {
695 uint64_t Address = SD.getAddress();
697 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
700 F.setOffset(Address - SD.getAddress());
702 // Evaluate fragment size.
703 switch (F.getKind()) {
704 case MCFragment::FT_Align: {
705 MCAlignFragment &AF = cast<MCAlignFragment>(F);
707 uint64_t Size = RoundUpToAlignment(Address, AF.getAlignment()) - Address;
708 if (Size > AF.getMaxBytesToEmit())
711 AF.setFileSize(Size);
715 case MCFragment::FT_Data:
716 case MCFragment::FT_Fill:
717 F.setFileSize(F.getMaxFileSize());
720 case MCFragment::FT_Org: {
721 MCOrgFragment &OF = cast<MCOrgFragment>(F);
723 if (!OF.getOffset().isAbsolute())
724 llvm_unreachable("FIXME: Not yet implemented!");
725 uint64_t OrgOffset = OF.getOffset().getConstant();
726 uint64_t Offset = Address - SD.getAddress();
728 // FIXME: We need a way to communicate this error.
729 if (OrgOffset < Offset)
730 llvm_report_error("invalid .org offset '" + Twine(OrgOffset) +
731 "' (at offset '" + Twine(Offset) + "'");
733 F.setFileSize(OrgOffset - Offset);
738 Address += F.getFileSize();
741 // Set the section sizes.
742 SD.setSize(Address - SD.getAddress());
743 SD.setFileSize(RoundUpToAlignment(Address, NextAlign) - SD.getAddress());
746 /// WriteFileData - Write the \arg F data to the output file.
747 static void WriteFileData(raw_ostream &OS, const MCFragment &F,
748 MachObjectWriter &MOW) {
749 uint64_t Start = OS.tell();
754 // FIXME: Embed in fragments instead?
755 switch (F.getKind()) {
756 case MCFragment::FT_Align: {
757 MCAlignFragment &AF = cast<MCAlignFragment>(F);
758 uint64_t Count = AF.getFileSize() / AF.getValueSize();
760 // FIXME: This error shouldn't actually occur (the front end should emit
761 // multiple .align directives to enforce the semantics it wants), but is
762 // severe enough that we want to report it. How to handle this?
763 if (Count * AF.getValueSize() != AF.getFileSize())
764 llvm_report_error("undefined .align directive, value size '" +
765 Twine(AF.getValueSize()) +
766 "' is not a divisor of padding size '" +
767 Twine(AF.getFileSize()) + "'");
769 for (uint64_t i = 0; i != Count; ++i) {
770 switch (AF.getValueSize()) {
772 assert(0 && "Invalid size!");
773 case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
774 case 2: MOW.Write16(uint16_t(AF.getValue())); break;
775 case 4: MOW.Write32(uint32_t(AF.getValue())); break;
776 case 8: MOW.Write64(uint64_t(AF.getValue())); break;
782 case MCFragment::FT_Data:
783 OS << cast<MCDataFragment>(F).getContents().str();
786 case MCFragment::FT_Fill: {
787 MCFillFragment &FF = cast<MCFillFragment>(F);
789 if (!FF.getValue().isAbsolute())
790 llvm_unreachable("FIXME: Not yet implemented!");
791 int64_t Value = FF.getValue().getConstant();
793 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
794 switch (FF.getValueSize()) {
796 assert(0 && "Invalid size!");
797 case 1: MOW.Write8 (uint8_t (Value)); break;
798 case 2: MOW.Write16(uint16_t(Value)); break;
799 case 4: MOW.Write32(uint32_t(Value)); break;
800 case 8: MOW.Write64(uint64_t(Value)); break;
806 case MCFragment::FT_Org: {
807 MCOrgFragment &OF = cast<MCOrgFragment>(F);
809 for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
810 MOW.Write8(uint8_t(OF.getValue()));
816 assert(OS.tell() - Start == F.getFileSize());
819 /// WriteFileData - Write the \arg SD data to the output file.
820 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
821 MachObjectWriter &MOW) {
822 uint64_t Start = OS.tell();
825 for (MCSectionData::const_iterator it = SD.begin(),
826 ie = SD.end(); it != ie; ++it)
827 WriteFileData(OS, *it, MOW);
829 // Add section padding.
830 assert(SD.getFileSize() >= SD.getSize() && "Invalid section sizes!");
831 MOW.WriteZeros(SD.getFileSize() - SD.getSize());
833 assert(OS.tell() - Start == SD.getFileSize());
836 void MCAssembler::Finish() {
837 // Layout the sections and fragments.
838 uint64_t Address = 0;
839 for (iterator it = begin(), ie = end(); it != ie;) {
840 MCSectionData &SD = *it;
842 // Select the amount of padding alignment we need, based on either the next
843 // sections alignment or the default alignment.
845 // FIXME: This should probably match the native word size.
846 unsigned NextAlign = 4;
849 NextAlign = it->getAlignment();
851 // Layout the section fragments and its size.
852 SD.setAddress(Address);
853 LayoutSection(SD, NextAlign);
854 Address += SD.getFileSize();
857 // Write the object file.
858 MachObjectWriter MOW(OS);
859 MOW.WriteObject(*this);