1 //===-- MCMachOStreamer.cpp - MachO Streamer ------------------------------===//
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 #include "llvm/MC/MCStreamer.h"
11 #include "llvm/ADT/DenseMap.h"
12 #include "llvm/ADT/SmallVector.h"
13 #include "llvm/MC/MCAsmBackend.h"
14 #include "llvm/MC/MCAssembler.h"
15 #include "llvm/MC/MCCodeEmitter.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCDwarf.h"
18 #include "llvm/MC/MCExpr.h"
19 #include "llvm/MC/MCInst.h"
20 #include "llvm/MC/MCLinkerOptimizationHint.h"
21 #include "llvm/MC/MCMachOSymbolFlags.h"
22 #include "llvm/MC/MCObjectFileInfo.h"
23 #include "llvm/MC/MCObjectStreamer.h"
24 #include "llvm/MC/MCSection.h"
25 #include "llvm/MC/MCSectionMachO.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/Support/Dwarf.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/TargetRegistry.h"
30 #include "llvm/Support/raw_ostream.h"
36 class MCMachOStreamer : public MCObjectStreamer {
38 /// LabelSections - true if each section change should emit a linker local
39 /// label for use in relocations for assembler local references. Obviates the
40 /// need for local relocations. False by default.
43 bool DWARFMustBeAtTheEnd;
44 bool CreatedADWARFSection;
46 /// HasSectionLabel - map of which sections have already had a non-local
47 /// label emitted to them. Used so we don't emit extraneous linker local
48 /// labels in the middle of the section.
49 DenseMap<const MCSection*, bool> HasSectionLabel;
51 void EmitInstToData(const MCInst &Inst, const MCSubtargetInfo &STI) override;
53 void EmitDataRegion(DataRegionData::KindTy Kind);
54 void EmitDataRegionEnd();
57 MCMachOStreamer(MCContext &Context, MCAsmBackend &MAB, raw_pwrite_stream &OS,
58 MCCodeEmitter *Emitter, bool DWARFMustBeAtTheEnd, bool label)
59 : MCObjectStreamer(Context, MAB, OS, Emitter), LabelSections(label),
60 DWARFMustBeAtTheEnd(DWARFMustBeAtTheEnd), CreatedADWARFSection(false) {}
63 void reset() override {
64 HasSectionLabel.clear();
65 MCObjectStreamer::reset();
68 /// @name MCStreamer Interface
71 void ChangeSection(const MCSection *Sect, const MCExpr *Subsect) override;
72 void EmitLabel(MCSymbol *Symbol) override;
73 void EmitEHSymAttributes(const MCSymbol *Symbol, MCSymbol *EHSymbol) override;
74 void EmitAssemblerFlag(MCAssemblerFlag Flag) override;
75 void EmitLinkerOptions(ArrayRef<std::string> Options) override;
76 void EmitDataRegion(MCDataRegionType Kind) override;
77 void EmitVersionMin(MCVersionMinType Kind, unsigned Major,
78 unsigned Minor, unsigned Update) override;
79 void EmitThumbFunc(MCSymbol *Func) override;
80 bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override;
81 void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) override;
82 void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
83 unsigned ByteAlignment) override;
84 void BeginCOFFSymbolDef(const MCSymbol *Symbol) override {
85 llvm_unreachable("macho doesn't support this directive");
87 void EmitCOFFSymbolStorageClass(int StorageClass) override {
88 llvm_unreachable("macho doesn't support this directive");
90 void EmitCOFFSymbolType(int Type) override {
91 llvm_unreachable("macho doesn't support this directive");
93 void EndCOFFSymbolDef() override {
94 llvm_unreachable("macho doesn't support this directive");
96 void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) override {
97 llvm_unreachable("macho doesn't support this directive");
99 void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
100 unsigned ByteAlignment) override;
101 void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = nullptr,
102 uint64_t Size = 0, unsigned ByteAlignment = 0) override;
103 void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol, uint64_t Size,
104 unsigned ByteAlignment = 0) override;
106 void EmitFileDirective(StringRef Filename) override {
107 // FIXME: Just ignore the .file; it isn't important enough to fail the
110 // report_fatal_error("unsupported directive: '.file'");
113 void EmitIdent(StringRef IdentString) override {
114 llvm_unreachable("macho doesn't support this directive");
117 void EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) override {
118 getAssembler().getLOHContainer().addDirective(Kind, Args);
121 void FinishImpl() override;
124 } // end anonymous namespace.
126 static bool canGoAfterDWARF(const MCSectionMachO &MSec) {
127 // These sections are created by the assembler itself after the end of
129 StringRef SegName = MSec.getSegmentName();
130 StringRef SecName = MSec.getSectionName();
132 if (SegName == "__LD" && SecName == "__compact_unwind")
135 if (SegName == "__IMPORT") {
136 if (SecName == "__jump_table")
139 if (SecName == "__pointers")
143 if (SegName == "__TEXT" && SecName == "__eh_frame")
146 if (SegName == "__DATA" && SecName == "__nl_symbol_ptr")
152 void MCMachOStreamer::ChangeSection(const MCSection *Section,
153 const MCExpr *Subsection) {
154 // Change the section normally.
155 bool Created = MCObjectStreamer::changeSectionImpl(Section, Subsection);
156 const MCSectionMachO &MSec = *cast<MCSectionMachO>(Section);
157 StringRef SegName = MSec.getSegmentName();
158 if (SegName == "__DWARF")
159 CreatedADWARFSection = true;
160 else if (Created && DWARFMustBeAtTheEnd && !canGoAfterDWARF(MSec))
161 assert(!CreatedADWARFSection && "Creating regular section after DWARF");
163 // Output a linker-local symbol so we don't need section-relative local
164 // relocations. The linker hates us when we do that.
165 if (LabelSections && !HasSectionLabel[Section]) {
166 MCSymbol *Label = getContext().CreateLinkerPrivateTempSymbol();
168 HasSectionLabel[Section] = true;
172 void MCMachOStreamer::EmitEHSymAttributes(const MCSymbol *Symbol,
173 MCSymbol *EHSymbol) {
175 getAssembler().getOrCreateSymbolData(*Symbol);
177 EmitSymbolAttribute(EHSymbol, MCSA_Global);
178 if (SD.getFlags() & SF_WeakDefinition)
179 EmitSymbolAttribute(EHSymbol, MCSA_WeakDefinition);
180 if (SD.isPrivateExtern())
181 EmitSymbolAttribute(EHSymbol, MCSA_PrivateExtern);
184 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
185 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
187 // isSymbolLinkerVisible uses the section.
188 AssignSection(Symbol, getCurrentSection().first);
189 // We have to create a new fragment if this is an atom defining symbol,
190 // fragments cannot span atoms.
191 if (getAssembler().isSymbolLinkerVisible(*Symbol))
192 insert(new MCDataFragment());
194 MCObjectStreamer::EmitLabel(Symbol);
196 MCSymbolData &SD = getAssembler().getSymbolData(*Symbol);
197 // This causes the reference type flag to be cleared. Darwin 'as' was "trying"
198 // to clear the weak reference and weak definition bits too, but the
199 // implementation was buggy. For now we just try to match 'as', for
202 // FIXME: Cleanup this code, these bits should be emitted based on semantic
203 // properties, not on the order of definition, etc.
204 SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeMask);
207 void MCMachOStreamer::EmitDataRegion(DataRegionData::KindTy Kind) {
208 if (!getAssembler().getBackend().hasDataInCodeSupport())
210 // Create a temporary label to mark the start of the data region.
211 MCSymbol *Start = getContext().CreateTempSymbol();
213 // Record the region for the object writer to use.
214 DataRegionData Data = { Kind, Start, nullptr };
215 std::vector<DataRegionData> &Regions = getAssembler().getDataRegions();
216 Regions.push_back(Data);
219 void MCMachOStreamer::EmitDataRegionEnd() {
220 if (!getAssembler().getBackend().hasDataInCodeSupport())
222 std::vector<DataRegionData> &Regions = getAssembler().getDataRegions();
223 assert(!Regions.empty() && "Mismatched .end_data_region!");
224 DataRegionData &Data = Regions.back();
225 assert(!Data.End && "Mismatched .end_data_region!");
226 // Create a temporary label to mark the end of the data region.
227 Data.End = getContext().CreateTempSymbol();
231 void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
232 // Let the target do whatever target specific stuff it needs to do.
233 getAssembler().getBackend().handleAssemblerFlag(Flag);
234 // Do any generic stuff we need to do.
236 case MCAF_SyntaxUnified: return; // no-op here.
237 case MCAF_Code16: return; // Change parsing mode; no-op here.
238 case MCAF_Code32: return; // Change parsing mode; no-op here.
239 case MCAF_Code64: return; // Change parsing mode; no-op here.
240 case MCAF_SubsectionsViaSymbols:
241 getAssembler().setSubsectionsViaSymbols(true);
246 void MCMachOStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) {
247 getAssembler().getLinkerOptions().push_back(Options);
250 void MCMachOStreamer::EmitDataRegion(MCDataRegionType Kind) {
252 case MCDR_DataRegion:
253 EmitDataRegion(DataRegionData::Data);
255 case MCDR_DataRegionJT8:
256 EmitDataRegion(DataRegionData::JumpTable8);
258 case MCDR_DataRegionJT16:
259 EmitDataRegion(DataRegionData::JumpTable16);
261 case MCDR_DataRegionJT32:
262 EmitDataRegion(DataRegionData::JumpTable32);
264 case MCDR_DataRegionEnd:
270 void MCMachOStreamer::EmitVersionMin(MCVersionMinType Kind, unsigned Major,
271 unsigned Minor, unsigned Update) {
272 getAssembler().setVersionMinInfo(Kind, Major, Minor, Update);
275 void MCMachOStreamer::EmitThumbFunc(MCSymbol *Symbol) {
276 // Remember that the function is a thumb function. Fixup and relocation
277 // values will need adjusted.
278 getAssembler().setIsThumbFunc(Symbol);
281 bool MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
282 MCSymbolAttr Attribute) {
283 // Indirect symbols are handled differently, to match how 'as' handles
284 // them. This makes writing matching .o files easier.
285 if (Attribute == MCSA_IndirectSymbol) {
286 // Note that we intentionally cannot use the symbol data here; this is
287 // important for matching the string table that 'as' generates.
288 IndirectSymbolData ISD;
290 ISD.SectionData = getCurrentSectionData();
291 getAssembler().getIndirectSymbols().push_back(ISD);
295 // Adding a symbol attribute always introduces the symbol, note that an
296 // important side effect of calling getOrCreateSymbolData here is to register
297 // the symbol with the assembler.
298 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
300 // The implementation of symbol attributes is designed to match 'as', but it
301 // leaves much to desired. It doesn't really make sense to arbitrarily add and
302 // remove flags, but 'as' allows this (in particular, see .desc).
304 // In the future it might be worth trying to make these operations more well
308 case MCSA_ELF_TypeFunction:
309 case MCSA_ELF_TypeIndFunction:
310 case MCSA_ELF_TypeObject:
311 case MCSA_ELF_TypeTLS:
312 case MCSA_ELF_TypeCommon:
313 case MCSA_ELF_TypeNoType:
314 case MCSA_ELF_TypeGnuUniqueObject:
316 case MCSA_IndirectSymbol:
324 SD.setExternal(true);
325 // This effectively clears the undefined lazy bit, in Darwin 'as', although
326 // it isn't very consistent because it implements this as part of symbol
329 // FIXME: Cleanup this code, these bits should be emitted based on semantic
330 // properties, not on the order of definition, etc.
331 SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeUndefinedLazy);
334 case MCSA_LazyReference:
335 // FIXME: This requires -dynamic.
336 SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
337 if (Symbol->isUndefined())
338 SD.setFlags(SD.getFlags() | SF_ReferenceTypeUndefinedLazy);
341 // Since .reference sets the no dead strip bit, it is equivalent to
342 // .no_dead_strip in practice.
344 case MCSA_NoDeadStrip:
345 SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
348 case MCSA_SymbolResolver:
349 SD.setFlags(SD.getFlags() | SF_SymbolResolver);
352 case MCSA_PrivateExtern:
353 SD.setExternal(true);
354 SD.setPrivateExtern(true);
357 case MCSA_WeakReference:
358 // FIXME: This requires -dynamic.
359 if (Symbol->isUndefined())
360 SD.setFlags(SD.getFlags() | SF_WeakReference);
363 case MCSA_WeakDefinition:
364 // FIXME: 'as' enforces that this is defined and global. The manual claims
365 // it has to be in a coalesced section, but this isn't enforced.
366 SD.setFlags(SD.getFlags() | SF_WeakDefinition);
369 case MCSA_WeakDefAutoPrivate:
370 SD.setFlags(SD.getFlags() | SF_WeakDefinition | SF_WeakReference);
377 void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
378 // Encode the 'desc' value into the lowest implementation defined bits.
379 assert(DescValue == (DescValue & SF_DescFlagsMask) &&
380 "Invalid .desc value!");
381 getAssembler().getOrCreateSymbolData(*Symbol).setFlags(
382 DescValue & SF_DescFlagsMask);
385 void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
386 unsigned ByteAlignment) {
387 // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
388 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
390 AssignSection(Symbol, nullptr);
392 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
393 SD.setExternal(true);
394 SD.setCommon(Size, ByteAlignment);
397 void MCMachOStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
398 unsigned ByteAlignment) {
399 // '.lcomm' is equivalent to '.zerofill'.
400 return EmitZerofill(getContext().getObjectFileInfo()->getDataBSSSection(),
401 Symbol, Size, ByteAlignment);
404 void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
405 uint64_t Size, unsigned ByteAlignment) {
406 MCSectionData &SectData = getAssembler().getOrCreateSectionData(*Section);
408 // The symbol may not be present, which only creates the section.
412 // On darwin all virtual sections have zerofill type.
413 assert(Section->isVirtualSection() && "Section does not have zerofill type!");
415 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
417 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
419 // Emit an align fragment if necessary.
420 if (ByteAlignment != 1)
421 new MCAlignFragment(ByteAlignment, 0, 0, ByteAlignment, &SectData);
423 MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
426 AssignSection(Symbol, Section);
428 // Update the maximum alignment on the zero fill section if necessary.
429 if (ByteAlignment > SectData.getAlignment())
430 SectData.setAlignment(ByteAlignment);
433 // This should always be called with the thread local bss section. Like the
434 // .zerofill directive this doesn't actually switch sections on us.
435 void MCMachOStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
436 uint64_t Size, unsigned ByteAlignment) {
437 EmitZerofill(Section, Symbol, Size, ByteAlignment);
441 void MCMachOStreamer::EmitInstToData(const MCInst &Inst,
442 const MCSubtargetInfo &STI) {
443 MCDataFragment *DF = getOrCreateDataFragment();
445 SmallVector<MCFixup, 4> Fixups;
446 SmallString<256> Code;
447 raw_svector_ostream VecOS(Code);
448 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups, STI);
451 // Add the fixups and data.
452 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
453 Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
454 DF->getFixups().push_back(Fixups[i]);
456 DF->getContents().append(Code.begin(), Code.end());
459 void MCMachOStreamer::FinishImpl() {
460 EmitFrames(&getAssembler().getBackend());
462 // We have to set the fragment atom associations so we can relax properly for
465 // First, scan the symbol table to build a lookup table from fragments to
467 DenseMap<const MCFragment*, MCSymbolData*> DefiningSymbolMap;
468 for (MCSymbolData &SD : getAssembler().symbols()) {
469 if (getAssembler().isSymbolLinkerVisible(SD.getSymbol()) &&
471 // An atom defining symbol should never be internal to a fragment.
472 assert(SD.getOffset() == 0 && "Invalid offset in atom defining symbol!");
473 DefiningSymbolMap[SD.getFragment()] = &SD;
477 // Set the fragment atom associations by tracking the last seen atom defining
479 for (MCAssembler::iterator it = getAssembler().begin(),
480 ie = getAssembler().end(); it != ie; ++it) {
481 MCSymbolData *CurrentAtom = nullptr;
482 for (MCSectionData::iterator it2 = it->begin(),
483 ie2 = it->end(); it2 != ie2; ++it2) {
484 if (MCSymbolData *SD = DefiningSymbolMap.lookup(it2))
486 it2->setAtom(CurrentAtom);
490 this->MCObjectStreamer::FinishImpl();
493 MCStreamer *llvm::createMachOStreamer(MCContext &Context, MCAsmBackend &MAB,
494 raw_pwrite_stream &OS, MCCodeEmitter *CE,
495 bool RelaxAll, bool DWARFMustBeAtTheEnd,
496 bool LabelSections) {
497 MCMachOStreamer *S = new MCMachOStreamer(Context, MAB, OS, CE,
498 DWARFMustBeAtTheEnd, LabelSections);
500 S->getAssembler().setRelaxAll(true);