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/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/TargetAsmBackend.h"
30 #include "../Target/X86/X86FixupKinds.h"
35 class MachObjectWriter;
37 STATISTIC(EmittedFragments, "Number of emitted assembler fragments");
39 // FIXME FIXME FIXME: There are number of places in this file where we convert
40 // what is a 64-bit assembler value used for computation into a value in the
41 // object file, which may truncate it. We should detect that truncation where
42 // invalid and report errors back.
44 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
45 MachObjectWriter &MOW);
47 static uint64_t WriteNopData(uint64_t Count, MachObjectWriter &MOW);
49 /// isVirtualSection - Check if this is a section which does not actually exist
50 /// in the object file.
51 static bool isVirtualSection(const MCSection &Section) {
53 const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
54 unsigned Type = SMO.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
55 return (Type == MCSectionMachO::S_ZEROFILL);
58 static unsigned getFixupKindLog2Size(unsigned Kind) {
60 default: llvm_unreachable("invalid fixup kind!");
61 case X86::reloc_pcrel_1byte:
62 case FK_Data_1: return 0;
63 case FK_Data_2: return 1;
64 case X86::reloc_pcrel_4byte:
65 case X86::reloc_riprel_4byte:
66 case FK_Data_4: return 2;
67 case FK_Data_8: return 3;
71 static bool isFixupKindPCRel(unsigned Kind) {
75 case X86::reloc_pcrel_1byte:
76 case X86::reloc_pcrel_4byte:
77 case X86::reloc_riprel_4byte:
82 class MachObjectWriter {
83 // See <mach-o/loader.h>.
85 Header_Magic32 = 0xFEEDFACE,
86 Header_Magic64 = 0xFEEDFACF
89 static const unsigned Header32Size = 28;
90 static const unsigned Header64Size = 32;
91 static const unsigned SegmentLoadCommand32Size = 56;
92 static const unsigned Section32Size = 68;
93 static const unsigned SymtabLoadCommandSize = 24;
94 static const unsigned DysymtabLoadCommandSize = 80;
95 static const unsigned Nlist32Size = 12;
96 static const unsigned RelocationInfoSize = 8;
103 HF_SubsectionsViaSymbols = 0x2000
106 enum LoadCommandType {
112 // See <mach-o/nlist.h>.
113 enum SymbolTypeType {
114 STT_Undefined = 0x00,
119 enum SymbolTypeFlags {
120 // If any of these bits are set, then the entry is a stab entry number (see
121 // <mach-o/stab.h>. Otherwise the other masks apply.
122 STF_StabsEntryMask = 0xe0,
126 STF_PrivateExtern = 0x10
129 /// IndirectSymbolFlags - Flags for encoding special values in the indirect
131 enum IndirectSymbolFlags {
132 ISF_Local = 0x80000000,
133 ISF_Absolute = 0x40000000
136 /// RelocationFlags - Special flags for addresses.
137 enum RelocationFlags {
138 RF_Scattered = 0x80000000
141 enum RelocationInfoType {
145 RIT_PreboundLazyPointer = 3,
146 RIT_LocalDifference = 4
149 /// MachSymbolData - Helper struct for containing some precomputed information
151 struct MachSymbolData {
152 MCSymbolData *SymbolData;
153 uint64_t StringIndex;
154 uint8_t SectionIndex;
156 // Support lexicographic sorting.
157 bool operator<(const MachSymbolData &RHS) const {
158 const std::string &Name = SymbolData->getSymbol().getName();
159 return Name < RHS.SymbolData->getSymbol().getName();
167 MachObjectWriter(raw_ostream &_OS, bool _IsLSB = true)
168 : OS(_OS), IsLSB(_IsLSB) {
171 /// @name Helper Methods
174 void Write8(uint8_t Value) {
178 void Write16(uint16_t Value) {
180 Write8(uint8_t(Value >> 0));
181 Write8(uint8_t(Value >> 8));
183 Write8(uint8_t(Value >> 8));
184 Write8(uint8_t(Value >> 0));
188 void Write32(uint32_t Value) {
190 Write16(uint16_t(Value >> 0));
191 Write16(uint16_t(Value >> 16));
193 Write16(uint16_t(Value >> 16));
194 Write16(uint16_t(Value >> 0));
198 void Write64(uint64_t Value) {
200 Write32(uint32_t(Value >> 0));
201 Write32(uint32_t(Value >> 32));
203 Write32(uint32_t(Value >> 32));
204 Write32(uint32_t(Value >> 0));
208 void WriteZeros(unsigned N) {
209 const char Zeros[16] = { 0 };
211 for (unsigned i = 0, e = N / 16; i != e; ++i)
212 OS << StringRef(Zeros, 16);
214 OS << StringRef(Zeros, N % 16);
217 void WriteString(StringRef Str, unsigned ZeroFillSize = 0) {
220 WriteZeros(ZeroFillSize - Str.size());
225 void WriteHeader32(unsigned NumLoadCommands, unsigned LoadCommandsSize,
226 bool SubsectionsViaSymbols) {
229 if (SubsectionsViaSymbols)
230 Flags |= HF_SubsectionsViaSymbols;
232 // struct mach_header (28 bytes)
234 uint64_t Start = OS.tell();
237 Write32(Header_Magic32);
239 // FIXME: Support cputype.
240 Write32(MachO::CPUTypeI386);
241 // FIXME: Support cpusubtype.
242 Write32(MachO::CPUSubType_I386_ALL);
244 Write32(NumLoadCommands); // Object files have a single load command, the
246 Write32(LoadCommandsSize);
249 assert(OS.tell() - Start == Header32Size);
252 /// WriteSegmentLoadCommand32 - Write a 32-bit segment load command.
254 /// \arg NumSections - The number of sections in this segment.
255 /// \arg SectionDataSize - The total size of the sections.
256 void WriteSegmentLoadCommand32(unsigned NumSections,
258 uint64_t SectionDataStartOffset,
259 uint64_t SectionDataSize) {
260 // struct segment_command (56 bytes)
262 uint64_t Start = OS.tell();
265 Write32(LCT_Segment);
266 Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
269 Write32(0); // vmaddr
270 Write32(VMSize); // vmsize
271 Write32(SectionDataStartOffset); // file offset
272 Write32(SectionDataSize); // file size
273 Write32(0x7); // maxprot
274 Write32(0x7); // initprot
275 Write32(NumSections);
278 assert(OS.tell() - Start == SegmentLoadCommand32Size);
281 void WriteSection32(const MCSectionData &SD, uint64_t FileOffset,
282 uint64_t RelocationsStart, unsigned NumRelocations) {
283 // The offset is unused for virtual sections.
284 if (isVirtualSection(SD.getSection())) {
285 assert(SD.getFileSize() == 0 && "Invalid file size!");
289 // struct section (68 bytes)
291 uint64_t Start = OS.tell();
294 // FIXME: cast<> support!
295 const MCSectionMachO &Section =
296 static_cast<const MCSectionMachO&>(SD.getSection());
297 WriteString(Section.getSectionName(), 16);
298 WriteString(Section.getSegmentName(), 16);
299 Write32(SD.getAddress()); // address
300 Write32(SD.getSize()); // size
303 unsigned Flags = Section.getTypeAndAttributes();
304 if (SD.hasInstructions())
305 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
307 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
308 Write32(Log2_32(SD.getAlignment()));
309 Write32(NumRelocations ? RelocationsStart : 0);
310 Write32(NumRelocations);
312 Write32(0); // reserved1
313 Write32(Section.getStubSize()); // reserved2
315 assert(OS.tell() - Start == Section32Size);
318 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
319 uint32_t StringTableOffset,
320 uint32_t StringTableSize) {
321 // struct symtab_command (24 bytes)
323 uint64_t Start = OS.tell();
327 Write32(SymtabLoadCommandSize);
328 Write32(SymbolOffset);
330 Write32(StringTableOffset);
331 Write32(StringTableSize);
333 assert(OS.tell() - Start == SymtabLoadCommandSize);
336 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
337 uint32_t NumLocalSymbols,
338 uint32_t FirstExternalSymbol,
339 uint32_t NumExternalSymbols,
340 uint32_t FirstUndefinedSymbol,
341 uint32_t NumUndefinedSymbols,
342 uint32_t IndirectSymbolOffset,
343 uint32_t NumIndirectSymbols) {
344 // struct dysymtab_command (80 bytes)
346 uint64_t Start = OS.tell();
349 Write32(LCT_Dysymtab);
350 Write32(DysymtabLoadCommandSize);
351 Write32(FirstLocalSymbol);
352 Write32(NumLocalSymbols);
353 Write32(FirstExternalSymbol);
354 Write32(NumExternalSymbols);
355 Write32(FirstUndefinedSymbol);
356 Write32(NumUndefinedSymbols);
357 Write32(0); // tocoff
359 Write32(0); // modtaboff
360 Write32(0); // nmodtab
361 Write32(0); // extrefsymoff
362 Write32(0); // nextrefsyms
363 Write32(IndirectSymbolOffset);
364 Write32(NumIndirectSymbols);
365 Write32(0); // extreloff
366 Write32(0); // nextrel
367 Write32(0); // locreloff
368 Write32(0); // nlocrel
370 assert(OS.tell() - Start == DysymtabLoadCommandSize);
373 void WriteNlist32(MachSymbolData &MSD) {
374 MCSymbolData &Data = *MSD.SymbolData;
375 const MCSymbol &Symbol = Data.getSymbol();
377 uint16_t Flags = Data.getFlags();
378 uint32_t Address = 0;
380 // Set the N_TYPE bits. See <mach-o/nlist.h>.
382 // FIXME: Are the prebound or indirect fields possible here?
383 if (Symbol.isUndefined())
384 Type = STT_Undefined;
385 else if (Symbol.isAbsolute())
390 // FIXME: Set STAB bits.
392 if (Data.isPrivateExtern())
393 Type |= STF_PrivateExtern;
396 if (Data.isExternal() || Symbol.isUndefined())
397 Type |= STF_External;
399 // Compute the symbol address.
400 if (Symbol.isDefined()) {
401 if (Symbol.isAbsolute()) {
402 llvm_unreachable("FIXME: Not yet implemented!");
404 Address = Data.getAddress();
406 } else if (Data.isCommon()) {
407 // Common symbols are encoded with the size in the address
408 // field, and their alignment in the flags.
409 Address = Data.getCommonSize();
411 // Common alignment is packed into the 'desc' bits.
412 if (unsigned Align = Data.getCommonAlignment()) {
413 unsigned Log2Size = Log2_32(Align);
414 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
416 llvm_report_error("invalid 'common' alignment '" +
418 // FIXME: Keep this mask with the SymbolFlags enumeration.
419 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
423 // struct nlist (12 bytes)
425 Write32(MSD.StringIndex);
427 Write8(MSD.SectionIndex);
429 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
435 struct MachRelocationEntry {
439 void ComputeScatteredRelocationInfo(MCAssembler &Asm, MCFragment &Fragment,
441 const MCValue &Target,
442 std::vector<MachRelocationEntry> &Relocs) {
443 uint32_t Address = Fragment.getOffset() + Fixup.Offset;
444 unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
445 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
446 unsigned Type = RIT_Vanilla;
449 const MCSymbol *A = Target.getSymA();
450 MCSymbolData *A_SD = &Asm.getSymbolData(*A);
452 if (!A_SD->getFragment())
453 llvm_report_error("symbol '" + A->getName() +
454 "' can not be undefined in a subtraction expression");
456 uint32_t Value = A_SD->getAddress();
459 if (const MCSymbol *B = Target.getSymB()) {
460 MCSymbolData *B_SD = &Asm.getSymbolData(*B);
462 if (!B_SD->getFragment())
463 llvm_report_error("symbol '" + B->getName() +
464 "' can not be undefined in a subtraction expression");
466 // Select the appropriate difference relocation type.
468 // Note that there is no longer any semantic difference between these two
469 // relocation types from the linkers point of view, this is done solely
470 // for pedantic compatibility with 'as'.
471 Type = A_SD->isExternal() ? RIT_Difference : RIT_LocalDifference;
472 Value2 = B_SD->getAddress();
475 MachRelocationEntry MRE;
476 MRE.Word0 = ((Address << 0) |
482 Relocs.push_back(MRE);
484 if (Type == RIT_Difference || Type == RIT_LocalDifference) {
485 MachRelocationEntry MRE;
486 MRE.Word0 = ((0 << 0) |
492 Relocs.push_back(MRE);
496 void ComputeRelocationInfo(MCAssembler &Asm, MCDataFragment &Fragment,
498 std::vector<MachRelocationEntry> &Relocs) {
499 unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
500 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
502 // FIXME: Share layout object.
503 MCAsmLayout Layout(Asm);
505 // Evaluate the fixup; if the value was resolved, no relocation is needed.
507 if (Asm.EvaluateFixup(Layout, Fixup, &Fragment, Target, Fixup.FixedValue))
510 // If this is a difference or a defined symbol plus an offset, then we need
511 // a scattered relocation entry.
512 uint32_t Offset = Target.getConstant();
514 Offset += 1 << Log2Size;
515 if (Target.getSymB() ||
516 (Target.getSymA() && !Target.getSymA()->isUndefined() &&
518 return ComputeScatteredRelocationInfo(Asm, Fragment, Fixup, Target,
522 uint32_t Address = Fragment.getOffset() + Fixup.Offset;
525 unsigned IsExtern = 0;
528 if (Target.isAbsolute()) { // constant
529 // SymbolNum of 0 indicates the absolute section.
531 // FIXME: Currently, these are never generated (see code below). I cannot
532 // find a case where they are actually emitted.
536 const MCSymbol *Symbol = Target.getSymA();
537 MCSymbolData *SD = &Asm.getSymbolData(*Symbol);
539 if (Symbol->isUndefined()) {
541 Index = SD->getIndex();
544 // The index is the section ordinal.
548 MCAssembler::iterator it = Asm.begin(), ie = Asm.end();
549 for (; it != ie; ++it, ++Index)
550 if (&*it == SD->getFragment()->getParent())
552 assert(it != ie && "Unable to find section index!");
553 Value = SD->getAddress();
559 // struct relocation_info (8 bytes)
560 MachRelocationEntry MRE;
562 MRE.Word1 = ((Index << 0) |
567 Relocs.push_back(MRE);
570 void BindIndirectSymbols(MCAssembler &Asm) {
571 // This is the point where 'as' creates actual symbols for indirect symbols
572 // (in the following two passes). It would be easier for us to do this
573 // sooner when we see the attribute, but that makes getting the order in the
574 // symbol table much more complicated than it is worth.
576 // FIXME: Revisit this when the dust settles.
578 // Bind non lazy symbol pointers first.
579 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
580 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
581 // FIXME: cast<> support!
582 const MCSectionMachO &Section =
583 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
586 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
587 if (Type != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
590 Asm.getOrCreateSymbolData(*it->Symbol);
593 // Then lazy symbol pointers and symbol stubs.
594 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
595 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
596 // FIXME: cast<> support!
597 const MCSectionMachO &Section =
598 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
601 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
602 if (Type != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
603 Type != MCSectionMachO::S_SYMBOL_STUBS)
606 // Set the symbol type to undefined lazy, but only on construction.
608 // FIXME: Do not hardcode.
610 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
612 Entry.setFlags(Entry.getFlags() | 0x0001);
616 /// ComputeSymbolTable - Compute the symbol table data
618 /// \param StringTable [out] - The string table data.
619 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
621 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
622 std::vector<MachSymbolData> &LocalSymbolData,
623 std::vector<MachSymbolData> &ExternalSymbolData,
624 std::vector<MachSymbolData> &UndefinedSymbolData) {
625 // Build section lookup table.
626 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
628 for (MCAssembler::iterator it = Asm.begin(),
629 ie = Asm.end(); it != ie; ++it, ++Index)
630 SectionIndexMap[&it->getSection()] = Index;
631 assert(Index <= 256 && "Too many sections!");
633 // Index 0 is always the empty string.
634 StringMap<uint64_t> StringIndexMap;
635 StringTable += '\x00';
637 // Build the symbol arrays and the string table, but only for non-local
640 // The particular order that we collect the symbols and create the string
641 // table, then sort the symbols is chosen to match 'as'. Even though it
642 // doesn't matter for correctness, this is important for letting us diff .o
644 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
645 ie = Asm.symbol_end(); it != ie; ++it) {
646 const MCSymbol &Symbol = it->getSymbol();
648 // Ignore assembler temporaries.
649 if (it->getSymbol().isTemporary())
652 if (!it->isExternal() && !Symbol.isUndefined())
655 uint64_t &Entry = StringIndexMap[Symbol.getName()];
657 Entry = StringTable.size();
658 StringTable += Symbol.getName();
659 StringTable += '\x00';
664 MSD.StringIndex = Entry;
666 if (Symbol.isUndefined()) {
667 MSD.SectionIndex = 0;
668 UndefinedSymbolData.push_back(MSD);
669 } else if (Symbol.isAbsolute()) {
670 MSD.SectionIndex = 0;
671 ExternalSymbolData.push_back(MSD);
673 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
674 assert(MSD.SectionIndex && "Invalid section index!");
675 ExternalSymbolData.push_back(MSD);
679 // Now add the data for local symbols.
680 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
681 ie = Asm.symbol_end(); it != ie; ++it) {
682 const MCSymbol &Symbol = it->getSymbol();
684 // Ignore assembler temporaries.
685 if (it->getSymbol().isTemporary())
688 if (it->isExternal() || Symbol.isUndefined())
691 uint64_t &Entry = StringIndexMap[Symbol.getName()];
693 Entry = StringTable.size();
694 StringTable += Symbol.getName();
695 StringTable += '\x00';
700 MSD.StringIndex = Entry;
702 if (Symbol.isAbsolute()) {
703 MSD.SectionIndex = 0;
704 LocalSymbolData.push_back(MSD);
706 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
707 assert(MSD.SectionIndex && "Invalid section index!");
708 LocalSymbolData.push_back(MSD);
712 // External and undefined symbols are required to be in lexicographic order.
713 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
714 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
716 // Set the symbol indices.
718 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
719 LocalSymbolData[i].SymbolData->setIndex(Index++);
720 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
721 ExternalSymbolData[i].SymbolData->setIndex(Index++);
722 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
723 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
725 // The string table is padded to a multiple of 4.
726 while (StringTable.size() % 4)
727 StringTable += '\x00';
730 void WriteObject(MCAssembler &Asm) {
731 unsigned NumSections = Asm.size();
733 // Create symbol data for any indirect symbols.
734 BindIndirectSymbols(Asm);
736 // Compute symbol table information.
737 SmallString<256> StringTable;
738 std::vector<MachSymbolData> LocalSymbolData;
739 std::vector<MachSymbolData> ExternalSymbolData;
740 std::vector<MachSymbolData> UndefinedSymbolData;
741 unsigned NumSymbols = Asm.symbol_size();
743 // No symbol table command is written if there are no symbols.
745 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
746 UndefinedSymbolData);
748 // The section data starts after the header, the segment load command (and
749 // section headers) and the symbol table.
750 unsigned NumLoadCommands = 1;
751 uint64_t LoadCommandsSize =
752 SegmentLoadCommand32Size + NumSections * Section32Size;
754 // Add the symbol table load command sizes, if used.
756 NumLoadCommands += 2;
757 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
760 // Compute the total size of the section data, as well as its file size and
762 uint64_t SectionDataStart = Header32Size + LoadCommandsSize;
763 uint64_t SectionDataSize = 0;
764 uint64_t SectionDataFileSize = 0;
766 for (MCAssembler::iterator it = Asm.begin(),
767 ie = Asm.end(); it != ie; ++it) {
768 MCSectionData &SD = *it;
770 VMSize = std::max(VMSize, SD.getAddress() + SD.getSize());
772 if (isVirtualSection(SD.getSection()))
775 SectionDataSize = std::max(SectionDataSize,
776 SD.getAddress() + SD.getSize());
777 SectionDataFileSize = std::max(SectionDataFileSize,
778 SD.getAddress() + SD.getFileSize());
781 // The section data is padded to 4 bytes.
783 // FIXME: Is this machine dependent?
784 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
785 SectionDataFileSize += SectionDataPadding;
787 // Write the prolog, starting with the header and load command...
788 WriteHeader32(NumLoadCommands, LoadCommandsSize,
789 Asm.getSubsectionsViaSymbols());
790 WriteSegmentLoadCommand32(NumSections, VMSize,
791 SectionDataStart, SectionDataSize);
793 // ... and then the section headers.
795 // We also compute the section relocations while we do this. Note that
796 // computing relocation info will also update the fixup to have the correct
797 // value; this will overwrite the appropriate data in the fragment when it
799 std::vector<MachRelocationEntry> RelocInfos;
800 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
801 for (MCAssembler::iterator it = Asm.begin(),
802 ie = Asm.end(); it != ie; ++it) {
803 MCSectionData &SD = *it;
805 // The assembler writes relocations in the reverse order they were seen.
807 // FIXME: It is probably more complicated than this.
808 unsigned NumRelocsStart = RelocInfos.size();
809 for (MCSectionData::reverse_iterator it2 = SD.rbegin(),
810 ie2 = SD.rend(); it2 != ie2; ++it2)
811 if (MCDataFragment *DF = dyn_cast<MCDataFragment>(&*it2))
812 for (unsigned i = 0, e = DF->fixup_size(); i != e; ++i)
813 ComputeRelocationInfo(Asm, *DF, DF->getFixups()[e - i - 1],
816 unsigned NumRelocs = RelocInfos.size() - NumRelocsStart;
817 uint64_t SectionStart = SectionDataStart + SD.getAddress();
818 WriteSection32(SD, SectionStart, RelocTableEnd, NumRelocs);
819 RelocTableEnd += NumRelocs * RelocationInfoSize;
822 // Write the symbol table load command, if used.
824 unsigned FirstLocalSymbol = 0;
825 unsigned NumLocalSymbols = LocalSymbolData.size();
826 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
827 unsigned NumExternalSymbols = ExternalSymbolData.size();
828 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
829 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
830 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
831 unsigned NumSymTabSymbols =
832 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
833 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
834 uint64_t IndirectSymbolOffset = 0;
836 // If used, the indirect symbols are written after the section data.
837 if (NumIndirectSymbols)
838 IndirectSymbolOffset = RelocTableEnd;
840 // The symbol table is written after the indirect symbol data.
841 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
843 // The string table is written after symbol table.
844 uint64_t StringTableOffset =
845 SymbolTableOffset + NumSymTabSymbols * Nlist32Size;
846 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
847 StringTableOffset, StringTable.size());
849 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
850 FirstExternalSymbol, NumExternalSymbols,
851 FirstUndefinedSymbol, NumUndefinedSymbols,
852 IndirectSymbolOffset, NumIndirectSymbols);
855 // Write the actual section data.
856 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
857 WriteFileData(OS, *it, *this);
859 // Write the extra padding.
860 WriteZeros(SectionDataPadding);
862 // Write the relocation entries.
863 for (unsigned i = 0, e = RelocInfos.size(); i != e; ++i) {
864 Write32(RelocInfos[i].Word0);
865 Write32(RelocInfos[i].Word1);
868 // Write the symbol table data, if used.
870 // Write the indirect symbol entries.
871 for (MCAssembler::indirect_symbol_iterator
872 it = Asm.indirect_symbol_begin(),
873 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
874 // Indirect symbols in the non lazy symbol pointer section have some
876 const MCSectionMachO &Section =
877 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
879 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
880 if (Type == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
881 // If this symbol is defined and internal, mark it as such.
882 if (it->Symbol->isDefined() &&
883 !Asm.getSymbolData(*it->Symbol).isExternal()) {
884 uint32_t Flags = ISF_Local;
885 if (it->Symbol->isAbsolute())
886 Flags |= ISF_Absolute;
892 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
895 // FIXME: Check that offsets match computed ones.
897 // Write the symbol table entries.
898 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
899 WriteNlist32(LocalSymbolData[i]);
900 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
901 WriteNlist32(ExternalSymbolData[i]);
902 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
903 WriteNlist32(UndefinedSymbolData[i]);
905 // Write the string table.
906 OS << StringTable.str();
910 void ApplyFixup(const MCAsmFixup &Fixup, MCDataFragment &DF) {
911 unsigned Size = 1 << getFixupKindLog2Size(Fixup.Kind);
913 // FIXME: Endianness assumption.
914 assert(Fixup.Offset + Size <= DF.getContents().size() &&
915 "Invalid fixup offset!");
916 for (unsigned i = 0; i != Size; ++i)
917 DF.getContents()[Fixup.Offset + i] = uint8_t(Fixup.FixedValue >> (i * 8));
923 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
926 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
929 FileSize(~UINT64_C(0))
932 Parent->getFragmentList().push_back(this);
935 MCFragment::~MCFragment() {
938 uint64_t MCFragment::getAddress() const {
939 assert(getParent() && "Missing Section!");
940 return getParent()->getAddress() + Offset;
945 MCSectionData::MCSectionData() : Section(0) {}
947 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
948 : Section(&_Section),
950 Address(~UINT64_C(0)),
952 FileSize(~UINT64_C(0)),
953 HasInstructions(false)
956 A->getSectionList().push_back(this);
961 MCSymbolData::MCSymbolData() : Symbol(0) {}
963 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
964 uint64_t _Offset, MCAssembler *A)
965 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
966 IsExternal(false), IsPrivateExtern(false),
967 CommonSize(0), CommonAlign(0), Flags(0), Index(0)
970 A->getSymbolList().push_back(this);
975 MCAssembler::MCAssembler(MCContext &_Context, TargetAsmBackend &_Backend,
977 : Context(_Context), Backend(_Backend), OS(_OS), SubsectionsViaSymbols(false)
981 MCAssembler::~MCAssembler() {
984 bool MCAssembler::EvaluateFixup(const MCAsmLayout &Layout, MCAsmFixup &Fixup,
986 MCValue &Target, uint64_t &Value) const {
987 if (!Fixup.Value->EvaluateAsRelocatable(Target, &Layout))
988 llvm_report_error("expected relocatable expression");
990 // FIXME: How do non-scattered symbols work in ELF? I presume the linker
991 // doesn't support small relocations, but then under what criteria does the
992 // assembler allow symbol differences?
994 Value = Target.getConstant();
996 // FIXME: This "resolved" check isn't quite right. The assumption is that if
997 // we have a PCrel access to a temporary, then that temporary is in the same
998 // atom, and so the value is resolved. We need explicit atom's to implement
999 // this more precisely.
1000 bool IsResolved = true, IsPCRel = isFixupKindPCRel(Fixup.Kind);
1001 if (const MCSymbol *Symbol = Target.getSymA()) {
1002 if (Symbol->isDefined())
1003 Value += getSymbolData(*Symbol).getAddress();
1007 // With scattered symbols, we assume anything that isn't a PCrel temporary
1008 // access can have an arbitrary value.
1009 if (getBackend().hasScatteredSymbols() &&
1010 (!IsPCRel || !Symbol->isTemporary()))
1013 if (const MCSymbol *Symbol = Target.getSymB()) {
1014 if (Symbol->isDefined())
1015 Value -= getSymbolData(*Symbol).getAddress();
1019 // With scattered symbols, we assume anything that isn't a PCrel temporary
1020 // access can have an arbitrary value.
1021 if (getBackend().hasScatteredSymbols() &&
1022 (!IsPCRel || !Symbol->isTemporary()))
1027 Value -= DF->getOffset() + Fixup.Offset;
1032 void MCAssembler::LayoutSection(MCSectionData &SD) {
1033 MCAsmLayout Layout(*this);
1034 uint64_t Address = SD.getAddress();
1036 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
1037 MCFragment &F = *it;
1039 F.setOffset(Address - SD.getAddress());
1041 // Evaluate fragment size.
1042 switch (F.getKind()) {
1043 case MCFragment::FT_Align: {
1044 MCAlignFragment &AF = cast<MCAlignFragment>(F);
1046 uint64_t Size = OffsetToAlignment(Address, AF.getAlignment());
1047 if (Size > AF.getMaxBytesToEmit())
1050 AF.setFileSize(Size);
1054 case MCFragment::FT_Data:
1055 case MCFragment::FT_Fill:
1056 F.setFileSize(F.getMaxFileSize());
1059 case MCFragment::FT_Org: {
1060 MCOrgFragment &OF = cast<MCOrgFragment>(F);
1062 int64_t TargetLocation;
1063 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, &Layout))
1064 llvm_report_error("expected assembly-time absolute expression");
1066 // FIXME: We need a way to communicate this error.
1067 int64_t Offset = TargetLocation - F.getOffset();
1069 llvm_report_error("invalid .org offset '" + Twine(TargetLocation) +
1070 "' (at offset '" + Twine(F.getOffset()) + "'");
1072 F.setFileSize(Offset);
1076 case MCFragment::FT_ZeroFill: {
1077 MCZeroFillFragment &ZFF = cast<MCZeroFillFragment>(F);
1079 // Align the fragment offset; it is safe to adjust the offset freely since
1080 // this is only in virtual sections.
1081 Address = RoundUpToAlignment(Address, ZFF.getAlignment());
1082 F.setOffset(Address - SD.getAddress());
1084 // FIXME: This is misnamed.
1085 F.setFileSize(ZFF.getSize());
1090 Address += F.getFileSize();
1093 // Set the section sizes.
1094 SD.setSize(Address - SD.getAddress());
1095 if (isVirtualSection(SD.getSection()))
1098 SD.setFileSize(Address - SD.getAddress());
1101 /// WriteNopData - Write optimal nops to the output file for the \arg Count
1102 /// bytes. This returns the number of bytes written. It may return 0 if
1103 /// the \arg Count is more than the maximum optimal nops.
1105 /// FIXME this is X86 32-bit specific and should move to a better place.
1106 static uint64_t WriteNopData(uint64_t Count, MachObjectWriter &MOW) {
1107 static const uint8_t Nops[16][16] = {
1115 {0x0f, 0x1f, 0x40, 0x00},
1116 // nopl 0(%[re]ax,%[re]ax,1)
1117 {0x0f, 0x1f, 0x44, 0x00, 0x00},
1118 // nopw 0(%[re]ax,%[re]ax,1)
1119 {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1121 {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1122 // nopl 0L(%[re]ax,%[re]ax,1)
1123 {0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1124 // nopw 0L(%[re]ax,%[re]ax,1)
1125 {0x66, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1126 // nopw %cs:0L(%[re]ax,%[re]ax,1)
1127 {0x66, 0x2e, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1128 // nopl 0(%[re]ax,%[re]ax,1)
1129 // nopw 0(%[re]ax,%[re]ax,1)
1130 {0x0f, 0x1f, 0x44, 0x00, 0x00,
1131 0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1132 // nopw 0(%[re]ax,%[re]ax,1)
1133 // nopw 0(%[re]ax,%[re]ax,1)
1134 {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00,
1135 0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1136 // nopw 0(%[re]ax,%[re]ax,1)
1137 // nopl 0L(%[re]ax) */
1138 {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00,
1139 0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1142 {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00,
1143 0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1145 // nopl 0L(%[re]ax,%[re]ax,1)
1146 {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00,
1147 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00}
1153 for (uint64_t i = 0; i < Count; i++)
1154 MOW.Write8 (uint8_t(Nops[Count - 1][i]));
1159 /// WriteFileData - Write the \arg F data to the output file.
1160 static void WriteFileData(raw_ostream &OS, const MCFragment &F,
1161 MachObjectWriter &MOW) {
1162 uint64_t Start = OS.tell();
1167 // FIXME: Embed in fragments instead?
1168 switch (F.getKind()) {
1169 case MCFragment::FT_Align: {
1170 MCAlignFragment &AF = cast<MCAlignFragment>(F);
1171 uint64_t Count = AF.getFileSize() / AF.getValueSize();
1173 // FIXME: This error shouldn't actually occur (the front end should emit
1174 // multiple .align directives to enforce the semantics it wants), but is
1175 // severe enough that we want to report it. How to handle this?
1176 if (Count * AF.getValueSize() != AF.getFileSize())
1177 llvm_report_error("undefined .align directive, value size '" +
1178 Twine(AF.getValueSize()) +
1179 "' is not a divisor of padding size '" +
1180 Twine(AF.getFileSize()) + "'");
1182 // See if we are aligning with nops, and if so do that first to try to fill
1183 // the Count bytes. Then if that did not fill any bytes or there are any
1184 // bytes left to fill use the the Value and ValueSize to fill the rest.
1185 if (AF.getEmitNops()) {
1186 uint64_t NopByteCount = WriteNopData(Count, MOW);
1187 Count -= NopByteCount;
1190 for (uint64_t i = 0; i != Count; ++i) {
1191 switch (AF.getValueSize()) {
1193 assert(0 && "Invalid size!");
1194 case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
1195 case 2: MOW.Write16(uint16_t(AF.getValue())); break;
1196 case 4: MOW.Write32(uint32_t(AF.getValue())); break;
1197 case 8: MOW.Write64(uint64_t(AF.getValue())); break;
1203 case MCFragment::FT_Data: {
1204 MCDataFragment &DF = cast<MCDataFragment>(F);
1206 // Apply the fixups.
1208 // FIXME: Move elsewhere.
1209 for (MCDataFragment::const_fixup_iterator it = DF.fixup_begin(),
1210 ie = DF.fixup_end(); it != ie; ++it)
1211 MOW.ApplyFixup(*it, DF);
1213 OS << cast<MCDataFragment>(F).getContents().str();
1217 case MCFragment::FT_Fill: {
1218 MCFillFragment &FF = cast<MCFillFragment>(F);
1219 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
1220 switch (FF.getValueSize()) {
1222 assert(0 && "Invalid size!");
1223 case 1: MOW.Write8 (uint8_t (FF.getValue())); break;
1224 case 2: MOW.Write16(uint16_t(FF.getValue())); break;
1225 case 4: MOW.Write32(uint32_t(FF.getValue())); break;
1226 case 8: MOW.Write64(uint64_t(FF.getValue())); break;
1232 case MCFragment::FT_Org: {
1233 MCOrgFragment &OF = cast<MCOrgFragment>(F);
1235 for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
1236 MOW.Write8(uint8_t(OF.getValue()));
1241 case MCFragment::FT_ZeroFill: {
1242 assert(0 && "Invalid zero fill fragment in concrete section!");
1247 assert(OS.tell() - Start == F.getFileSize());
1250 /// WriteFileData - Write the \arg SD data to the output file.
1251 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
1252 MachObjectWriter &MOW) {
1253 // Ignore virtual sections.
1254 if (isVirtualSection(SD.getSection())) {
1255 assert(SD.getFileSize() == 0);
1259 uint64_t Start = OS.tell();
1262 for (MCSectionData::const_iterator it = SD.begin(),
1263 ie = SD.end(); it != ie; ++it)
1264 WriteFileData(OS, *it, MOW);
1266 // Add section padding.
1267 assert(SD.getFileSize() >= SD.getSize() && "Invalid section sizes!");
1268 MOW.WriteZeros(SD.getFileSize() - SD.getSize());
1270 assert(OS.tell() - Start == SD.getFileSize());
1273 void MCAssembler::Finish() {
1274 DEBUG_WITH_TYPE("mc-dump", {
1275 llvm::errs() << "assembler backend - pre-layout\n--\n";
1278 // Layout the concrete sections and fragments.
1279 uint64_t Address = 0;
1280 MCSectionData *Prev = 0;
1281 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1282 MCSectionData &SD = *it;
1284 // Skip virtual sections.
1285 if (isVirtualSection(SD.getSection()))
1288 // Align this section if necessary by adding padding bytes to the previous
1290 if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment())) {
1291 assert(Prev && "Missing prev section!");
1292 Prev->setFileSize(Prev->getFileSize() + Pad);
1296 // Layout the section fragments and its size.
1297 SD.setAddress(Address);
1299 Address += SD.getFileSize();
1304 // Layout the virtual sections.
1305 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1306 MCSectionData &SD = *it;
1308 if (!isVirtualSection(SD.getSection()))
1311 // Align this section if necessary by adding padding bytes to the previous
1313 if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment()))
1316 SD.setAddress(Address);
1318 Address += SD.getSize();
1322 DEBUG_WITH_TYPE("mc-dump", {
1323 llvm::errs() << "assembler backend - post-layout\n--\n";
1326 // Write the object file.
1327 MachObjectWriter MOW(OS);
1328 MOW.WriteObject(*this);
1334 // Debugging methods
1338 raw_ostream &operator<<(raw_ostream &OS, const MCAsmFixup &AF) {
1339 OS << "<MCAsmFixup" << " Offset:" << AF.Offset << " Value:" << *AF.Value
1340 << " Kind:" << AF.Kind << ">";
1346 void MCFragment::dump() {
1347 raw_ostream &OS = llvm::errs();
1349 OS << "<MCFragment " << (void*) this << " Offset:" << Offset
1350 << " FileSize:" << FileSize;
1355 void MCAlignFragment::dump() {
1356 raw_ostream &OS = llvm::errs();
1358 OS << "<MCAlignFragment ";
1359 this->MCFragment::dump();
1361 OS << " Alignment:" << getAlignment()
1362 << " Value:" << getValue() << " ValueSize:" << getValueSize()
1363 << " MaxBytesToEmit:" << getMaxBytesToEmit() << ">";
1366 void MCDataFragment::dump() {
1367 raw_ostream &OS = llvm::errs();
1369 OS << "<MCDataFragment ";
1370 this->MCFragment::dump();
1372 OS << " Contents:[";
1373 for (unsigned i = 0, e = getContents().size(); i != e; ++i) {
1375 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1377 OS << "] (" << getContents().size() << " bytes)";
1379 if (!getFixups().empty()) {
1382 for (fixup_iterator it = fixup_begin(), ie = fixup_end(); it != ie; ++it) {
1383 if (it != fixup_begin()) OS << ",\n ";
1392 void MCFillFragment::dump() {
1393 raw_ostream &OS = llvm::errs();
1395 OS << "<MCFillFragment ";
1396 this->MCFragment::dump();
1398 OS << " Value:" << getValue() << " ValueSize:" << getValueSize()
1399 << " Count:" << getCount() << ">";
1402 void MCOrgFragment::dump() {
1403 raw_ostream &OS = llvm::errs();
1405 OS << "<MCOrgFragment ";
1406 this->MCFragment::dump();
1408 OS << " Offset:" << getOffset() << " Value:" << getValue() << ">";
1411 void MCZeroFillFragment::dump() {
1412 raw_ostream &OS = llvm::errs();
1414 OS << "<MCZeroFillFragment ";
1415 this->MCFragment::dump();
1417 OS << " Size:" << getSize() << " Alignment:" << getAlignment() << ">";
1420 void MCSectionData::dump() {
1421 raw_ostream &OS = llvm::errs();
1423 OS << "<MCSectionData";
1424 OS << " Alignment:" << getAlignment() << " Address:" << Address
1425 << " Size:" << Size << " FileSize:" << FileSize
1426 << " Fragments:[\n ";
1427 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1428 if (it != begin()) OS << ",\n ";
1434 void MCSymbolData::dump() {
1435 raw_ostream &OS = llvm::errs();
1437 OS << "<MCSymbolData Symbol:" << getSymbol()
1438 << " Fragment:" << getFragment() << " Offset:" << getOffset()
1439 << " Flags:" << getFlags() << " Index:" << getIndex();
1441 OS << " (common, size:" << getCommonSize()
1442 << " align: " << getCommonAlignment() << ")";
1444 OS << " (external)";
1445 if (isPrivateExtern())
1446 OS << " (private extern)";
1450 void MCAssembler::dump() {
1451 raw_ostream &OS = llvm::errs();
1453 OS << "<MCAssembler\n";
1454 OS << " Sections:[\n ";
1455 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1456 if (it != begin()) OS << ",\n ";
1462 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1463 if (it != symbol_begin()) OS << ",\n ";