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/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"
28 #include "../Target/X86/X86FixupKinds.h"
33 class MachObjectWriter;
35 STATISTIC(EmittedFragments, "Number of emitted assembler fragments");
37 // FIXME FIXME FIXME: There are number of places in this file where we convert
38 // what is a 64-bit assembler value used for computation into a value in the
39 // object file, which may truncate it. We should detect that truncation where
40 // invalid and report errors back.
42 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
43 MachObjectWriter &MOW);
45 /// isVirtualSection - Check if this is a section which does not actually exist
46 /// in the object file.
47 static bool isVirtualSection(const MCSection &Section) {
49 const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
50 unsigned Type = SMO.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
51 return (Type == MCSectionMachO::S_ZEROFILL);
54 static unsigned getFixupKindLog2Size(MCFixupKind Kind) {
56 default: llvm_unreachable("invalid fixup kind!");
57 case X86::reloc_pcrel_1byte:
58 case FK_Data_1: return 0;
59 case FK_Data_2: return 1;
60 case X86::reloc_pcrel_4byte:
61 case X86::reloc_riprel_4byte:
62 case FK_Data_4: return 2;
63 case FK_Data_8: return 3;
67 class MachObjectWriter {
68 // See <mach-o/loader.h>.
70 Header_Magic32 = 0xFEEDFACE,
71 Header_Magic64 = 0xFEEDFACF
74 static const unsigned Header32Size = 28;
75 static const unsigned Header64Size = 32;
76 static const unsigned SegmentLoadCommand32Size = 56;
77 static const unsigned Section32Size = 68;
78 static const unsigned SymtabLoadCommandSize = 24;
79 static const unsigned DysymtabLoadCommandSize = 80;
80 static const unsigned Nlist32Size = 12;
81 static const unsigned RelocationInfoSize = 8;
88 HF_SubsectionsViaSymbols = 0x2000
91 enum LoadCommandType {
97 // See <mach-o/nlist.h>.
104 enum SymbolTypeFlags {
105 // If any of these bits are set, then the entry is a stab entry number (see
106 // <mach-o/stab.h>. Otherwise the other masks apply.
107 STF_StabsEntryMask = 0xe0,
111 STF_PrivateExtern = 0x10
114 /// IndirectSymbolFlags - Flags for encoding special values in the indirect
116 enum IndirectSymbolFlags {
117 ISF_Local = 0x80000000,
118 ISF_Absolute = 0x40000000
121 /// RelocationFlags - Special flags for addresses.
122 enum RelocationFlags {
123 RF_Scattered = 0x80000000
126 enum RelocationInfoType {
130 RIT_PreboundLazyPointer = 3,
131 RIT_LocalDifference = 4
134 /// MachSymbolData - Helper struct for containing some precomputed information
136 struct MachSymbolData {
137 MCSymbolData *SymbolData;
138 uint64_t StringIndex;
139 uint8_t SectionIndex;
141 // Support lexicographic sorting.
142 bool operator<(const MachSymbolData &RHS) const {
143 const std::string &Name = SymbolData->getSymbol().getName();
144 return Name < RHS.SymbolData->getSymbol().getName();
152 MachObjectWriter(raw_ostream &_OS, bool _IsLSB = true)
153 : OS(_OS), IsLSB(_IsLSB) {
156 /// @name Helper Methods
159 void Write8(uint8_t Value) {
163 void Write16(uint16_t Value) {
165 Write8(uint8_t(Value >> 0));
166 Write8(uint8_t(Value >> 8));
168 Write8(uint8_t(Value >> 8));
169 Write8(uint8_t(Value >> 0));
173 void Write32(uint32_t Value) {
175 Write16(uint16_t(Value >> 0));
176 Write16(uint16_t(Value >> 16));
178 Write16(uint16_t(Value >> 16));
179 Write16(uint16_t(Value >> 0));
183 void Write64(uint64_t Value) {
185 Write32(uint32_t(Value >> 0));
186 Write32(uint32_t(Value >> 32));
188 Write32(uint32_t(Value >> 32));
189 Write32(uint32_t(Value >> 0));
193 void WriteZeros(unsigned N) {
194 const char Zeros[16] = { 0 };
196 for (unsigned i = 0, e = N / 16; i != e; ++i)
197 OS << StringRef(Zeros, 16);
199 OS << StringRef(Zeros, N % 16);
202 void WriteString(StringRef Str, unsigned ZeroFillSize = 0) {
205 WriteZeros(ZeroFillSize - Str.size());
210 void WriteHeader32(unsigned NumLoadCommands, unsigned LoadCommandsSize,
211 bool SubsectionsViaSymbols) {
214 if (SubsectionsViaSymbols)
215 Flags |= HF_SubsectionsViaSymbols;
217 // struct mach_header (28 bytes)
219 uint64_t Start = OS.tell();
222 Write32(Header_Magic32);
224 // FIXME: Support cputype.
225 Write32(MachO::CPUTypeI386);
226 // FIXME: Support cpusubtype.
227 Write32(MachO::CPUSubType_I386_ALL);
229 Write32(NumLoadCommands); // Object files have a single load command, the
231 Write32(LoadCommandsSize);
234 assert(OS.tell() - Start == Header32Size);
237 /// WriteSegmentLoadCommand32 - Write a 32-bit segment load command.
239 /// \arg NumSections - The number of sections in this segment.
240 /// \arg SectionDataSize - The total size of the sections.
241 void WriteSegmentLoadCommand32(unsigned NumSections,
243 uint64_t SectionDataStartOffset,
244 uint64_t SectionDataSize) {
245 // struct segment_command (56 bytes)
247 uint64_t Start = OS.tell();
250 Write32(LCT_Segment);
251 Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
254 Write32(0); // vmaddr
255 Write32(VMSize); // vmsize
256 Write32(SectionDataStartOffset); // file offset
257 Write32(SectionDataSize); // file size
258 Write32(0x7); // maxprot
259 Write32(0x7); // initprot
260 Write32(NumSections);
263 assert(OS.tell() - Start == SegmentLoadCommand32Size);
266 void WriteSection32(const MCSectionData &SD, uint64_t FileOffset,
267 uint64_t RelocationsStart, unsigned NumRelocations) {
268 // The offset is unused for virtual sections.
269 if (isVirtualSection(SD.getSection())) {
270 assert(SD.getFileSize() == 0 && "Invalid file size!");
274 // struct section (68 bytes)
276 uint64_t Start = OS.tell();
279 // FIXME: cast<> support!
280 const MCSectionMachO &Section =
281 static_cast<const MCSectionMachO&>(SD.getSection());
282 WriteString(Section.getSectionName(), 16);
283 WriteString(Section.getSegmentName(), 16);
284 Write32(SD.getAddress()); // address
285 Write32(SD.getSize()); // size
288 unsigned Flags = Section.getTypeAndAttributes();
289 if (SD.hasInstructions())
290 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
292 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
293 Write32(Log2_32(SD.getAlignment()));
294 Write32(NumRelocations ? RelocationsStart : 0);
295 Write32(NumRelocations);
297 Write32(0); // reserved1
298 Write32(Section.getStubSize()); // reserved2
300 assert(OS.tell() - Start == Section32Size);
303 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
304 uint32_t StringTableOffset,
305 uint32_t StringTableSize) {
306 // struct symtab_command (24 bytes)
308 uint64_t Start = OS.tell();
312 Write32(SymtabLoadCommandSize);
313 Write32(SymbolOffset);
315 Write32(StringTableOffset);
316 Write32(StringTableSize);
318 assert(OS.tell() - Start == SymtabLoadCommandSize);
321 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
322 uint32_t NumLocalSymbols,
323 uint32_t FirstExternalSymbol,
324 uint32_t NumExternalSymbols,
325 uint32_t FirstUndefinedSymbol,
326 uint32_t NumUndefinedSymbols,
327 uint32_t IndirectSymbolOffset,
328 uint32_t NumIndirectSymbols) {
329 // struct dysymtab_command (80 bytes)
331 uint64_t Start = OS.tell();
334 Write32(LCT_Dysymtab);
335 Write32(DysymtabLoadCommandSize);
336 Write32(FirstLocalSymbol);
337 Write32(NumLocalSymbols);
338 Write32(FirstExternalSymbol);
339 Write32(NumExternalSymbols);
340 Write32(FirstUndefinedSymbol);
341 Write32(NumUndefinedSymbols);
342 Write32(0); // tocoff
344 Write32(0); // modtaboff
345 Write32(0); // nmodtab
346 Write32(0); // extrefsymoff
347 Write32(0); // nextrefsyms
348 Write32(IndirectSymbolOffset);
349 Write32(NumIndirectSymbols);
350 Write32(0); // extreloff
351 Write32(0); // nextrel
352 Write32(0); // locreloff
353 Write32(0); // nlocrel
355 assert(OS.tell() - Start == DysymtabLoadCommandSize);
358 void WriteNlist32(MachSymbolData &MSD) {
359 MCSymbolData &Data = *MSD.SymbolData;
360 const MCSymbol &Symbol = Data.getSymbol();
362 uint16_t Flags = Data.getFlags();
363 uint32_t Address = 0;
365 // Set the N_TYPE bits. See <mach-o/nlist.h>.
367 // FIXME: Are the prebound or indirect fields possible here?
368 if (Symbol.isUndefined())
369 Type = STT_Undefined;
370 else if (Symbol.isAbsolute())
375 // FIXME: Set STAB bits.
377 if (Data.isPrivateExtern())
378 Type |= STF_PrivateExtern;
381 if (Data.isExternal() || Symbol.isUndefined())
382 Type |= STF_External;
384 // Compute the symbol address.
385 if (Symbol.isDefined()) {
386 if (Symbol.isAbsolute()) {
387 llvm_unreachable("FIXME: Not yet implemented!");
389 Address = Data.getFragment()->getAddress() + Data.getOffset();
391 } else if (Data.isCommon()) {
392 // Common symbols are encoded with the size in the address
393 // field, and their alignment in the flags.
394 Address = Data.getCommonSize();
396 // Common alignment is packed into the 'desc' bits.
397 if (unsigned Align = Data.getCommonAlignment()) {
398 unsigned Log2Size = Log2_32(Align);
399 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
401 llvm_report_error("invalid 'common' alignment '" +
403 // FIXME: Keep this mask with the SymbolFlags enumeration.
404 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
408 // struct nlist (12 bytes)
410 Write32(MSD.StringIndex);
412 Write8(MSD.SectionIndex);
414 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
420 struct MachRelocationEntry {
424 void ComputeScatteredRelocationInfo(MCAssembler &Asm, MCFragment &Fragment,
426 const MCValue &Target,
427 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap,
428 std::vector<MachRelocationEntry> &Relocs) {
429 uint32_t Address = Fragment.getOffset() + Fixup.Offset;
430 unsigned IsPCRel = 0;
431 unsigned Type = RIT_Vanilla;
434 const MCSymbol *A = Target.getSymA();
435 MCSymbolData *SD = SymbolMap.lookup(A);
436 uint32_t Value = SD->getFragment()->getAddress() + SD->getOffset();
439 if (const MCSymbol *B = Target.getSymB()) {
440 Type = RIT_LocalDifference;
442 MCSymbolData *SD = SymbolMap.lookup(B);
443 Value2 = SD->getFragment()->getAddress() + SD->getOffset();
446 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
448 // The value which goes in the fixup is current value of the expression.
449 Fixup.FixedValue = Value - Value2 + Target.getConstant();
451 MachRelocationEntry MRE;
452 MRE.Word0 = ((Address << 0) |
458 Relocs.push_back(MRE);
460 if (Type == RIT_LocalDifference) {
463 MachRelocationEntry MRE;
464 MRE.Word0 = ((0 << 0) |
470 Relocs.push_back(MRE);
474 void ComputeRelocationInfo(MCAssembler &Asm, MCDataFragment &Fragment,
476 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap,
477 std::vector<MachRelocationEntry> &Relocs) {
479 if (!Fixup.Value->EvaluateAsRelocatable(Target))
480 llvm_report_error("expected relocatable expression");
482 // If this is a difference or a local symbol plus an offset, then we need a
483 // scattered relocation entry.
484 if (Target.getSymB() ||
485 (Target.getSymA() && !Target.getSymA()->isUndefined() &&
486 Target.getConstant()))
487 return ComputeScatteredRelocationInfo(Asm, Fragment, Fixup, Target,
491 uint32_t Address = Fragment.getOffset() + Fixup.Offset;
494 unsigned IsPCRel = 0;
495 unsigned IsExtern = 0;
498 if (Target.isAbsolute()) { // constant
499 // SymbolNum of 0 indicates the absolute section.
501 // FIXME: When is this generated?
504 llvm_unreachable("FIXME: Not yet implemented!");
506 const MCSymbol *Symbol = Target.getSymA();
507 MCSymbolData *SD = SymbolMap.lookup(Symbol);
509 if (Symbol->isUndefined()) {
511 Index = SD->getIndex();
514 // The index is the section ordinal.
518 for (MCAssembler::iterator it = Asm.begin(),
519 ie = Asm.end(); it != ie; ++it, ++Index)
520 if (&*it == SD->getFragment()->getParent())
522 Value = SD->getFragment()->getAddress() + SD->getOffset();
528 // The value which goes in the fixup is current value of the expression.
529 Fixup.FixedValue = Value + Target.getConstant();
531 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
533 // struct relocation_info (8 bytes)
534 MachRelocationEntry MRE;
536 MRE.Word1 = ((Index << 0) |
541 Relocs.push_back(MRE);
544 void BindIndirectSymbols(MCAssembler &Asm,
545 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap) {
546 // This is the point where 'as' creates actual symbols for indirect symbols
547 // (in the following two passes). It would be easier for us to do this
548 // sooner when we see the attribute, but that makes getting the order in the
549 // symbol table much more complicated than it is worth.
551 // FIXME: Revisit this when the dust settles.
553 // Bind non lazy symbol pointers first.
554 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
555 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
556 // FIXME: cast<> support!
557 const MCSectionMachO &Section =
558 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
561 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
562 if (Type != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
565 MCSymbolData *&Entry = SymbolMap[it->Symbol];
567 Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
570 // Then lazy symbol pointers and symbol stubs.
571 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
572 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
573 // FIXME: cast<> support!
574 const MCSectionMachO &Section =
575 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
578 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
579 if (Type != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
580 Type != MCSectionMachO::S_SYMBOL_STUBS)
583 MCSymbolData *&Entry = SymbolMap[it->Symbol];
585 Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
587 // Set the symbol type to undefined lazy, but only on construction.
589 // FIXME: Do not hardcode.
590 Entry->setFlags(Entry->getFlags() | 0x0001);
595 /// ComputeSymbolTable - Compute the symbol table data
597 /// \param StringTable [out] - The string table data.
598 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
600 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
601 std::vector<MachSymbolData> &LocalSymbolData,
602 std::vector<MachSymbolData> &ExternalSymbolData,
603 std::vector<MachSymbolData> &UndefinedSymbolData) {
604 // Build section lookup table.
605 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
607 for (MCAssembler::iterator it = Asm.begin(),
608 ie = Asm.end(); it != ie; ++it, ++Index)
609 SectionIndexMap[&it->getSection()] = Index;
610 assert(Index <= 256 && "Too many sections!");
612 // Index 0 is always the empty string.
613 StringMap<uint64_t> StringIndexMap;
614 StringTable += '\x00';
616 // Build the symbol arrays and the string table, but only for non-local
619 // The particular order that we collect the symbols and create the string
620 // table, then sort the symbols is chosen to match 'as'. Even though it
621 // doesn't matter for correctness, this is important for letting us diff .o
623 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
624 ie = Asm.symbol_end(); it != ie; ++it) {
625 const MCSymbol &Symbol = it->getSymbol();
627 // Ignore assembler temporaries.
628 if (it->getSymbol().isTemporary())
631 if (!it->isExternal() && !Symbol.isUndefined())
634 uint64_t &Entry = StringIndexMap[Symbol.getName()];
636 Entry = StringTable.size();
637 StringTable += Symbol.getName();
638 StringTable += '\x00';
643 MSD.StringIndex = Entry;
645 if (Symbol.isUndefined()) {
646 MSD.SectionIndex = 0;
647 UndefinedSymbolData.push_back(MSD);
648 } else if (Symbol.isAbsolute()) {
649 MSD.SectionIndex = 0;
650 ExternalSymbolData.push_back(MSD);
652 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
653 assert(MSD.SectionIndex && "Invalid section index!");
654 ExternalSymbolData.push_back(MSD);
658 // Now add the data for local symbols.
659 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
660 ie = Asm.symbol_end(); it != ie; ++it) {
661 const MCSymbol &Symbol = it->getSymbol();
663 // Ignore assembler temporaries.
664 if (it->getSymbol().isTemporary())
667 if (it->isExternal() || Symbol.isUndefined())
670 uint64_t &Entry = StringIndexMap[Symbol.getName()];
672 Entry = StringTable.size();
673 StringTable += Symbol.getName();
674 StringTable += '\x00';
679 MSD.StringIndex = Entry;
681 if (Symbol.isAbsolute()) {
682 MSD.SectionIndex = 0;
683 LocalSymbolData.push_back(MSD);
685 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
686 assert(MSD.SectionIndex && "Invalid section index!");
687 LocalSymbolData.push_back(MSD);
691 // External and undefined symbols are required to be in lexicographic order.
692 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
693 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
695 // Set the symbol indices.
697 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
698 LocalSymbolData[i].SymbolData->setIndex(Index++);
699 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
700 ExternalSymbolData[i].SymbolData->setIndex(Index++);
701 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
702 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
704 // The string table is padded to a multiple of 4.
705 while (StringTable.size() % 4)
706 StringTable += '\x00';
709 void WriteObject(MCAssembler &Asm) {
710 unsigned NumSections = Asm.size();
712 // Compute the symbol -> symbol data map.
714 // FIXME: This should not be here.
715 DenseMap<const MCSymbol*, MCSymbolData *> SymbolMap;
716 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
717 ie = Asm.symbol_end(); it != ie; ++it)
718 SymbolMap[&it->getSymbol()] = it;
720 // Create symbol data for any indirect symbols.
721 BindIndirectSymbols(Asm, SymbolMap);
723 // Compute symbol table information.
724 SmallString<256> StringTable;
725 std::vector<MachSymbolData> LocalSymbolData;
726 std::vector<MachSymbolData> ExternalSymbolData;
727 std::vector<MachSymbolData> UndefinedSymbolData;
728 unsigned NumSymbols = Asm.symbol_size();
730 // No symbol table command is written if there are no symbols.
732 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
733 UndefinedSymbolData);
735 // The section data starts after the header, the segment load command (and
736 // section headers) and the symbol table.
737 unsigned NumLoadCommands = 1;
738 uint64_t LoadCommandsSize =
739 SegmentLoadCommand32Size + NumSections * Section32Size;
741 // Add the symbol table load command sizes, if used.
743 NumLoadCommands += 2;
744 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
747 // Compute the total size of the section data, as well as its file size and
749 uint64_t SectionDataStart = Header32Size + LoadCommandsSize;
750 uint64_t SectionDataSize = 0;
751 uint64_t SectionDataFileSize = 0;
753 for (MCAssembler::iterator it = Asm.begin(),
754 ie = Asm.end(); it != ie; ++it) {
755 MCSectionData &SD = *it;
757 VMSize = std::max(VMSize, SD.getAddress() + SD.getSize());
759 if (isVirtualSection(SD.getSection()))
762 SectionDataSize = std::max(SectionDataSize,
763 SD.getAddress() + SD.getSize());
764 SectionDataFileSize = std::max(SectionDataFileSize,
765 SD.getAddress() + SD.getFileSize());
768 // The section data is padded to 4 bytes.
770 // FIXME: Is this machine dependent?
771 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
772 SectionDataFileSize += SectionDataPadding;
774 // Write the prolog, starting with the header and load command...
775 WriteHeader32(NumLoadCommands, LoadCommandsSize,
776 Asm.getSubsectionsViaSymbols());
777 WriteSegmentLoadCommand32(NumSections, VMSize,
778 SectionDataStart, SectionDataSize);
780 // ... and then the section headers.
782 // We also compute the section relocations while we do this. Note that
783 // computing relocation info will also update the fixup to have the correct
784 // value; this will overwrite the appropriate data in the fragment when it
786 std::vector<MachRelocationEntry> RelocInfos;
787 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
788 for (MCAssembler::iterator it = Asm.begin(),
789 ie = Asm.end(); it != ie; ++it) {
790 MCSectionData &SD = *it;
792 // The assembler writes relocations in the reverse order they were seen.
794 // FIXME: It is probably more complicated than this.
795 unsigned NumRelocsStart = RelocInfos.size();
796 for (MCSectionData::reverse_iterator it2 = SD.rbegin(),
797 ie2 = SD.rend(); it2 != ie2; ++it2)
798 if (MCDataFragment *DF = dyn_cast<MCDataFragment>(&*it2))
799 for (unsigned i = 0, e = DF->fixup_size(); i != e; ++i)
800 ComputeRelocationInfo(Asm, *DF, DF->getFixups()[e - i - 1],
801 SymbolMap, RelocInfos);
803 unsigned NumRelocs = RelocInfos.size() - NumRelocsStart;
804 uint64_t SectionStart = SectionDataStart + SD.getAddress();
805 WriteSection32(SD, SectionStart, RelocTableEnd, NumRelocs);
806 RelocTableEnd += NumRelocs * RelocationInfoSize;
809 // Write the symbol table load command, if used.
811 unsigned FirstLocalSymbol = 0;
812 unsigned NumLocalSymbols = LocalSymbolData.size();
813 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
814 unsigned NumExternalSymbols = ExternalSymbolData.size();
815 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
816 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
817 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
818 unsigned NumSymTabSymbols =
819 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
820 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
821 uint64_t IndirectSymbolOffset = 0;
823 // If used, the indirect symbols are written after the section data.
824 if (NumIndirectSymbols)
825 IndirectSymbolOffset = RelocTableEnd;
827 // The symbol table is written after the indirect symbol data.
828 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
830 // The string table is written after symbol table.
831 uint64_t StringTableOffset =
832 SymbolTableOffset + NumSymTabSymbols * Nlist32Size;
833 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
834 StringTableOffset, StringTable.size());
836 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
837 FirstExternalSymbol, NumExternalSymbols,
838 FirstUndefinedSymbol, NumUndefinedSymbols,
839 IndirectSymbolOffset, NumIndirectSymbols);
842 // Write the actual section data.
843 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
844 WriteFileData(OS, *it, *this);
846 // Write the extra padding.
847 WriteZeros(SectionDataPadding);
849 // Write the relocation entries.
850 for (unsigned i = 0, e = RelocInfos.size(); i != e; ++i) {
851 Write32(RelocInfos[i].Word0);
852 Write32(RelocInfos[i].Word1);
855 // Write the symbol table data, if used.
857 // Write the indirect symbol entries.
858 for (MCAssembler::indirect_symbol_iterator
859 it = Asm.indirect_symbol_begin(),
860 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
861 // Indirect symbols in the non lazy symbol pointer section have some
863 const MCSectionMachO &Section =
864 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
866 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
867 if (Type == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
868 // If this symbol is defined and internal, mark it as such.
869 if (it->Symbol->isDefined() &&
870 !SymbolMap.lookup(it->Symbol)->isExternal()) {
871 uint32_t Flags = ISF_Local;
872 if (it->Symbol->isAbsolute())
873 Flags |= ISF_Absolute;
879 Write32(SymbolMap[it->Symbol]->getIndex());
882 // FIXME: Check that offsets match computed ones.
884 // Write the symbol table entries.
885 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
886 WriteNlist32(LocalSymbolData[i]);
887 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
888 WriteNlist32(ExternalSymbolData[i]);
889 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
890 WriteNlist32(UndefinedSymbolData[i]);
892 // Write the string table.
893 OS << StringTable.str();
897 void ApplyFixup(const MCAsmFixup &Fixup, MCDataFragment &DF) {
898 unsigned Size = 1 << getFixupKindLog2Size(Fixup.Kind);
900 // FIXME: Endianness assumption.
901 assert(Fixup.Offset + Size <= DF.getContents().size() &&
902 "Invalid fixup offset!");
903 for (unsigned i = 0; i != Size; ++i)
904 DF.getContents()[Fixup.Offset + i] = uint8_t(Fixup.FixedValue >> (i * 8));
910 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
913 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
916 FileSize(~UINT64_C(0))
919 Parent->getFragmentList().push_back(this);
922 MCFragment::~MCFragment() {
925 uint64_t MCFragment::getAddress() const {
926 assert(getParent() && "Missing Section!");
927 return getParent()->getAddress() + Offset;
932 MCSectionData::MCSectionData() : Section(0) {}
934 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
935 : Section(&_Section),
937 Address(~UINT64_C(0)),
939 FileSize(~UINT64_C(0)),
940 HasInstructions(false)
943 A->getSectionList().push_back(this);
948 MCSymbolData::MCSymbolData() : Symbol(0) {}
950 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
951 uint64_t _Offset, MCAssembler *A)
952 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
953 IsExternal(false), IsPrivateExtern(false),
954 CommonSize(0), CommonAlign(0), Flags(0), Index(0)
957 A->getSymbolList().push_back(this);
962 MCAssembler::MCAssembler(MCContext &_Context, raw_ostream &_OS)
963 : Context(_Context), OS(_OS), SubsectionsViaSymbols(false)
967 MCAssembler::~MCAssembler() {
970 void MCAssembler::LayoutSection(MCSectionData &SD) {
971 uint64_t Address = SD.getAddress();
973 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
976 F.setOffset(Address - SD.getAddress());
978 // Evaluate fragment size.
979 switch (F.getKind()) {
980 case MCFragment::FT_Align: {
981 MCAlignFragment &AF = cast<MCAlignFragment>(F);
983 uint64_t Size = OffsetToAlignment(Address, AF.getAlignment());
984 if (Size > AF.getMaxBytesToEmit())
987 AF.setFileSize(Size);
991 case MCFragment::FT_Data:
992 case MCFragment::FT_Fill:
993 F.setFileSize(F.getMaxFileSize());
996 case MCFragment::FT_Org: {
997 MCOrgFragment &OF = cast<MCOrgFragment>(F);
1000 if (!OF.getOffset().EvaluateAsRelocatable(Target))
1001 llvm_report_error("expected relocatable expression");
1003 if (!Target.isAbsolute())
1004 llvm_unreachable("FIXME: Not yet implemented!");
1005 uint64_t OrgOffset = Target.getConstant();
1006 uint64_t Offset = Address - SD.getAddress();
1008 // FIXME: We need a way to communicate this error.
1009 if (OrgOffset < Offset)
1010 llvm_report_error("invalid .org offset '" + Twine(OrgOffset) +
1011 "' (at offset '" + Twine(Offset) + "'");
1013 F.setFileSize(OrgOffset - Offset);
1017 case MCFragment::FT_ZeroFill: {
1018 MCZeroFillFragment &ZFF = cast<MCZeroFillFragment>(F);
1020 // Align the fragment offset; it is safe to adjust the offset freely since
1021 // this is only in virtual sections.
1022 uint64_t Aligned = RoundUpToAlignment(Address, ZFF.getAlignment());
1023 F.setOffset(Aligned - SD.getAddress());
1025 // FIXME: This is misnamed.
1026 F.setFileSize(ZFF.getSize());
1031 Address += F.getFileSize();
1034 // Set the section sizes.
1035 SD.setSize(Address - SD.getAddress());
1036 if (isVirtualSection(SD.getSection()))
1039 SD.setFileSize(Address - SD.getAddress());
1042 /// WriteFileData - Write the \arg F data to the output file.
1043 static void WriteFileData(raw_ostream &OS, const MCFragment &F,
1044 MachObjectWriter &MOW) {
1045 uint64_t Start = OS.tell();
1050 // FIXME: Embed in fragments instead?
1051 switch (F.getKind()) {
1052 case MCFragment::FT_Align: {
1053 MCAlignFragment &AF = cast<MCAlignFragment>(F);
1054 uint64_t Count = AF.getFileSize() / AF.getValueSize();
1056 // FIXME: This error shouldn't actually occur (the front end should emit
1057 // multiple .align directives to enforce the semantics it wants), but is
1058 // severe enough that we want to report it. How to handle this?
1059 if (Count * AF.getValueSize() != AF.getFileSize())
1060 llvm_report_error("undefined .align directive, value size '" +
1061 Twine(AF.getValueSize()) +
1062 "' is not a divisor of padding size '" +
1063 Twine(AF.getFileSize()) + "'");
1065 for (uint64_t i = 0; i != Count; ++i) {
1066 switch (AF.getValueSize()) {
1068 assert(0 && "Invalid size!");
1069 case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
1070 case 2: MOW.Write16(uint16_t(AF.getValue())); break;
1071 case 4: MOW.Write32(uint32_t(AF.getValue())); break;
1072 case 8: MOW.Write64(uint64_t(AF.getValue())); break;
1078 case MCFragment::FT_Data: {
1079 MCDataFragment &DF = cast<MCDataFragment>(F);
1081 // Apply the fixups.
1083 // FIXME: Move elsewhere.
1084 for (MCDataFragment::const_fixup_iterator it = DF.fixup_begin(),
1085 ie = DF.fixup_end(); it != ie; ++it)
1086 MOW.ApplyFixup(*it, DF);
1088 OS << cast<MCDataFragment>(F).getContents().str();
1092 case MCFragment::FT_Fill: {
1093 MCFillFragment &FF = cast<MCFillFragment>(F);
1094 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
1095 switch (FF.getValueSize()) {
1097 assert(0 && "Invalid size!");
1098 case 1: MOW.Write8 (uint8_t (FF.getValue())); break;
1099 case 2: MOW.Write16(uint16_t(FF.getValue())); break;
1100 case 4: MOW.Write32(uint32_t(FF.getValue())); break;
1101 case 8: MOW.Write64(uint64_t(FF.getValue())); break;
1107 case MCFragment::FT_Org: {
1108 MCOrgFragment &OF = cast<MCOrgFragment>(F);
1110 for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
1111 MOW.Write8(uint8_t(OF.getValue()));
1116 case MCFragment::FT_ZeroFill: {
1117 assert(0 && "Invalid zero fill fragment in concrete section!");
1122 assert(OS.tell() - Start == F.getFileSize());
1125 /// WriteFileData - Write the \arg SD data to the output file.
1126 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
1127 MachObjectWriter &MOW) {
1128 // Ignore virtual sections.
1129 if (isVirtualSection(SD.getSection())) {
1130 assert(SD.getFileSize() == 0);
1134 uint64_t Start = OS.tell();
1137 for (MCSectionData::const_iterator it = SD.begin(),
1138 ie = SD.end(); it != ie; ++it)
1139 WriteFileData(OS, *it, MOW);
1141 // Add section padding.
1142 assert(SD.getFileSize() >= SD.getSize() && "Invalid section sizes!");
1143 MOW.WriteZeros(SD.getFileSize() - SD.getSize());
1145 assert(OS.tell() - Start == SD.getFileSize());
1148 void MCAssembler::Finish() {
1149 DEBUG_WITH_TYPE("mc-dump", {
1150 llvm::errs() << "assembler backend - pre-layout\n--\n";
1153 // Layout the concrete sections and fragments.
1154 uint64_t Address = 0;
1155 MCSectionData *Prev = 0;
1156 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1157 MCSectionData &SD = *it;
1159 // Skip virtual sections.
1160 if (isVirtualSection(SD.getSection()))
1163 // Align this section if necessary by adding padding bytes to the previous
1165 if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment())) {
1166 assert(Prev && "Missing prev section!");
1167 Prev->setFileSize(Prev->getFileSize() + Pad);
1171 // Layout the section fragments and its size.
1172 SD.setAddress(Address);
1174 Address += SD.getFileSize();
1179 // Layout the virtual sections.
1180 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1181 MCSectionData &SD = *it;
1183 if (!isVirtualSection(SD.getSection()))
1186 SD.setAddress(Address);
1188 Address += SD.getSize();
1191 DEBUG_WITH_TYPE("mc-dump", {
1192 llvm::errs() << "assembler backend - post-layout\n--\n";
1195 // Write the object file.
1196 MachObjectWriter MOW(OS);
1197 MOW.WriteObject(*this);
1203 // Debugging methods
1207 raw_ostream &operator<<(raw_ostream &OS, const MCAsmFixup &AF) {
1208 OS << "<MCAsmFixup" << " Offset:" << AF.Offset << " Value:" << *AF.Value
1209 << " Kind:" << AF.Kind << ">";
1215 void MCFragment::dump() {
1216 raw_ostream &OS = llvm::errs();
1218 OS << "<MCFragment " << (void*) this << " Offset:" << Offset
1219 << " FileSize:" << FileSize;
1224 void MCAlignFragment::dump() {
1225 raw_ostream &OS = llvm::errs();
1227 OS << "<MCAlignFragment ";
1228 this->MCFragment::dump();
1230 OS << " Alignment:" << getAlignment()
1231 << " Value:" << getValue() << " ValueSize:" << getValueSize()
1232 << " MaxBytesToEmit:" << getMaxBytesToEmit() << ">";
1235 void MCDataFragment::dump() {
1236 raw_ostream &OS = llvm::errs();
1238 OS << "<MCDataFragment ";
1239 this->MCFragment::dump();
1241 OS << " Contents:[";
1242 for (unsigned i = 0, e = getContents().size(); i != e; ++i) {
1244 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1246 OS << "] (" << getContents().size() << " bytes)";
1248 if (!getFixups().empty()) {
1251 for (fixup_iterator it = fixup_begin(), ie = fixup_end(); it != ie; ++it) {
1252 if (it != fixup_begin()) OS << ",\n ";
1261 void MCFillFragment::dump() {
1262 raw_ostream &OS = llvm::errs();
1264 OS << "<MCFillFragment ";
1265 this->MCFragment::dump();
1267 OS << " Value:" << getValue() << " ValueSize:" << getValueSize()
1268 << " Count:" << getCount() << ">";
1271 void MCOrgFragment::dump() {
1272 raw_ostream &OS = llvm::errs();
1274 OS << "<MCOrgFragment ";
1275 this->MCFragment::dump();
1277 OS << " Offset:" << getOffset() << " Value:" << getValue() << ">";
1280 void MCZeroFillFragment::dump() {
1281 raw_ostream &OS = llvm::errs();
1283 OS << "<MCZeroFillFragment ";
1284 this->MCFragment::dump();
1286 OS << " Size:" << getSize() << " Alignment:" << getAlignment() << ">";
1289 void MCSectionData::dump() {
1290 raw_ostream &OS = llvm::errs();
1292 OS << "<MCSectionData";
1293 OS << " Alignment:" << getAlignment() << " Address:" << Address
1294 << " Size:" << Size << " FileSize:" << FileSize
1296 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1297 if (it != begin()) OS << ",\n ";
1303 void MCSymbolData::dump() {
1304 raw_ostream &OS = llvm::errs();
1306 OS << "<MCSymbolData Symbol:" << getSymbol()
1307 << " Fragment:" << getFragment() << " Offset:" << getOffset()
1308 << " Flags:" << getFlags() << " Index:" << getIndex();
1310 OS << " (common, size:" << getCommonSize()
1311 << " align: " << getCommonAlignment() << ")";
1313 OS << " (external)";
1314 if (isPrivateExtern())
1315 OS << " (private extern)";
1319 void MCAssembler::dump() {
1320 raw_ostream &OS = llvm::errs();
1322 OS << "<MCAssembler\n";
1323 OS << " Sections:[";
1324 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1325 if (it != begin()) OS << ",\n ";
1331 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1332 if (it != symbol_begin()) OS << ",\n ";