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(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(MCSection *Section, MCSymbol *Symbol = nullptr,
102 uint64_t Size = 0, unsigned ByteAlignment = 0) override;
103 void EmitTBSSSymbol(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(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 !Section->getBeginSymbol()) {
167 MCSymbol *Label = getContext().createLinkerPrivateTempSymbol();
168 Section->setBeginSymbol(Label);
169 HasSectionLabel[Section] = true;
173 void MCMachOStreamer::EmitEHSymAttributes(const MCSymbol *Symbol,
174 MCSymbol *EHSymbol) {
176 getAssembler().getOrCreateSymbolData(*Symbol);
178 EmitSymbolAttribute(EHSymbol, MCSA_Global);
179 if (SD.getFlags() & SF_WeakDefinition)
180 EmitSymbolAttribute(EHSymbol, MCSA_WeakDefinition);
181 if (SD.isPrivateExtern())
182 EmitSymbolAttribute(EHSymbol, MCSA_PrivateExtern);
185 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
186 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
188 // isSymbolLinkerVisible uses the section.
189 AssignSection(Symbol, getCurrentSection().first);
190 // We have to create a new fragment if this is an atom defining symbol,
191 // fragments cannot span atoms.
192 if (getAssembler().isSymbolLinkerVisible(*Symbol))
193 insert(new MCDataFragment());
195 MCObjectStreamer::EmitLabel(Symbol);
197 MCSymbolData &SD = Symbol->getData();
198 // This causes the reference type flag to be cleared. Darwin 'as' was "trying"
199 // to clear the weak reference and weak definition bits too, but the
200 // implementation was buggy. For now we just try to match 'as', for
203 // FIXME: Cleanup this code, these bits should be emitted based on semantic
204 // properties, not on the order of definition, etc.
205 SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeMask);
208 void MCMachOStreamer::EmitDataRegion(DataRegionData::KindTy Kind) {
209 if (!getAssembler().getBackend().hasDataInCodeSupport())
211 // Create a temporary label to mark the start of the data region.
212 MCSymbol *Start = getContext().createTempSymbol();
214 // Record the region for the object writer to use.
215 DataRegionData Data = { Kind, Start, nullptr };
216 std::vector<DataRegionData> &Regions = getAssembler().getDataRegions();
217 Regions.push_back(Data);
220 void MCMachOStreamer::EmitDataRegionEnd() {
221 if (!getAssembler().getBackend().hasDataInCodeSupport())
223 std::vector<DataRegionData> &Regions = getAssembler().getDataRegions();
224 assert(!Regions.empty() && "Mismatched .end_data_region!");
225 DataRegionData &Data = Regions.back();
226 assert(!Data.End && "Mismatched .end_data_region!");
227 // Create a temporary label to mark the end of the data region.
228 Data.End = getContext().createTempSymbol();
232 void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
233 // Let the target do whatever target specific stuff it needs to do.
234 getAssembler().getBackend().handleAssemblerFlag(Flag);
235 // Do any generic stuff we need to do.
237 case MCAF_SyntaxUnified: return; // no-op here.
238 case MCAF_Code16: return; // Change parsing mode; no-op here.
239 case MCAF_Code32: return; // Change parsing mode; no-op here.
240 case MCAF_Code64: return; // Change parsing mode; no-op here.
241 case MCAF_SubsectionsViaSymbols:
242 getAssembler().setSubsectionsViaSymbols(true);
247 void MCMachOStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) {
248 getAssembler().getLinkerOptions().push_back(Options);
251 void MCMachOStreamer::EmitDataRegion(MCDataRegionType Kind) {
253 case MCDR_DataRegion:
254 EmitDataRegion(DataRegionData::Data);
256 case MCDR_DataRegionJT8:
257 EmitDataRegion(DataRegionData::JumpTable8);
259 case MCDR_DataRegionJT16:
260 EmitDataRegion(DataRegionData::JumpTable16);
262 case MCDR_DataRegionJT32:
263 EmitDataRegion(DataRegionData::JumpTable32);
265 case MCDR_DataRegionEnd:
271 void MCMachOStreamer::EmitVersionMin(MCVersionMinType Kind, unsigned Major,
272 unsigned Minor, unsigned Update) {
273 getAssembler().setVersionMinInfo(Kind, Major, Minor, Update);
276 void MCMachOStreamer::EmitThumbFunc(MCSymbol *Symbol) {
277 // Remember that the function is a thumb function. Fixup and relocation
278 // values will need adjusted.
279 getAssembler().setIsThumbFunc(Symbol);
282 bool MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
283 MCSymbolAttr Attribute) {
284 // Indirect symbols are handled differently, to match how 'as' handles
285 // them. This makes writing matching .o files easier.
286 if (Attribute == MCSA_IndirectSymbol) {
287 // Note that we intentionally cannot use the symbol data here; this is
288 // important for matching the string table that 'as' generates.
289 IndirectSymbolData ISD;
291 ISD.Section = getCurrentSectionOnly();
292 getAssembler().getIndirectSymbols().push_back(ISD);
296 // Adding a symbol attribute always introduces the symbol, note that an
297 // important side effect of calling getOrCreateSymbolData here is to register
298 // the symbol with the assembler.
299 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
301 // The implementation of symbol attributes is designed to match 'as', but it
302 // leaves much to desired. It doesn't really make sense to arbitrarily add and
303 // remove flags, but 'as' allows this (in particular, see .desc).
305 // In the future it might be worth trying to make these operations more well
309 case MCSA_ELF_TypeFunction:
310 case MCSA_ELF_TypeIndFunction:
311 case MCSA_ELF_TypeObject:
312 case MCSA_ELF_TypeTLS:
313 case MCSA_ELF_TypeCommon:
314 case MCSA_ELF_TypeNoType:
315 case MCSA_ELF_TypeGnuUniqueObject:
317 case MCSA_IndirectSymbol:
325 SD.setExternal(true);
326 // This effectively clears the undefined lazy bit, in Darwin 'as', although
327 // it isn't very consistent because it implements this as part of symbol
330 // FIXME: Cleanup this code, these bits should be emitted based on semantic
331 // properties, not on the order of definition, etc.
332 SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeUndefinedLazy);
335 case MCSA_LazyReference:
336 // FIXME: This requires -dynamic.
337 SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
338 if (Symbol->isUndefined())
339 SD.setFlags(SD.getFlags() | SF_ReferenceTypeUndefinedLazy);
342 // Since .reference sets the no dead strip bit, it is equivalent to
343 // .no_dead_strip in practice.
345 case MCSA_NoDeadStrip:
346 SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
349 case MCSA_SymbolResolver:
350 SD.setFlags(SD.getFlags() | SF_SymbolResolver);
353 case MCSA_PrivateExtern:
354 SD.setExternal(true);
355 SD.setPrivateExtern(true);
358 case MCSA_WeakReference:
359 // FIXME: This requires -dynamic.
360 if (Symbol->isUndefined())
361 SD.setFlags(SD.getFlags() | SF_WeakReference);
364 case MCSA_WeakDefinition:
365 // FIXME: 'as' enforces that this is defined and global. The manual claims
366 // it has to be in a coalesced section, but this isn't enforced.
367 SD.setFlags(SD.getFlags() | SF_WeakDefinition);
370 case MCSA_WeakDefAutoPrivate:
371 SD.setFlags(SD.getFlags() | SF_WeakDefinition | SF_WeakReference);
378 void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
379 // Encode the 'desc' value into the lowest implementation defined bits.
380 assert(DescValue == (DescValue & SF_DescFlagsMask) &&
381 "Invalid .desc value!");
382 getAssembler().getOrCreateSymbolData(*Symbol).setFlags(
383 DescValue & SF_DescFlagsMask);
386 void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
387 unsigned ByteAlignment) {
388 // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
389 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
391 AssignSection(Symbol, nullptr);
393 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
394 SD.setExternal(true);
395 Symbol->setCommon(Size, ByteAlignment);
398 void MCMachOStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
399 unsigned ByteAlignment) {
400 // '.lcomm' is equivalent to '.zerofill'.
401 return EmitZerofill(getContext().getObjectFileInfo()->getDataBSSSection(),
402 Symbol, Size, ByteAlignment);
405 void MCMachOStreamer::EmitZerofill(MCSection *Section, MCSymbol *Symbol,
406 uint64_t Size, unsigned ByteAlignment) {
407 getAssembler().registerSection(*Section);
409 // The symbol may not be present, which only creates the section.
413 // On darwin all virtual sections have zerofill type.
414 assert(Section->isVirtualSection() && "Section does not have zerofill type!");
416 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
418 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
420 // Emit an align fragment if necessary.
421 if (ByteAlignment != 1)
422 new MCAlignFragment(ByteAlignment, 0, 0, ByteAlignment, Section);
424 MCFragment *F = new MCFillFragment(0, 0, Size, Section);
427 AssignSection(Symbol, Section);
429 // Update the maximum alignment on the zero fill section if necessary.
430 if (ByteAlignment > Section->getAlignment())
431 Section->setAlignment(ByteAlignment);
434 // This should always be called with the thread local bss section. Like the
435 // .zerofill directive this doesn't actually switch sections on us.
436 void MCMachOStreamer::EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
437 uint64_t Size, unsigned ByteAlignment) {
438 EmitZerofill(Section, Symbol, Size, ByteAlignment);
442 void MCMachOStreamer::EmitInstToData(const MCInst &Inst,
443 const MCSubtargetInfo &STI) {
444 MCDataFragment *DF = getOrCreateDataFragment();
446 SmallVector<MCFixup, 4> Fixups;
447 SmallString<256> Code;
448 raw_svector_ostream VecOS(Code);
449 getAssembler().getEmitter().encodeInstruction(Inst, VecOS, Fixups, STI);
452 // Add the fixups and data.
453 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
454 Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
455 DF->getFixups().push_back(Fixups[i]);
457 DF->getContents().append(Code.begin(), Code.end());
460 void MCMachOStreamer::FinishImpl() {
461 EmitFrames(&getAssembler().getBackend());
463 // We have to set the fragment atom associations so we can relax properly for
466 // First, scan the symbol table to build a lookup table from fragments to
468 DenseMap<const MCFragment *, const MCSymbol *> DefiningSymbolMap;
469 for (const MCSymbol &Symbol : getAssembler().symbols()) {
470 MCSymbolData &SD = Symbol.getData();
471 if (getAssembler().isSymbolLinkerVisible(Symbol) && SD.getFragment()) {
472 // An atom defining symbol should never be internal to a fragment.
473 assert(Symbol.getOffset() == 0 &&
474 "Invalid offset in atom defining symbol!");
475 DefiningSymbolMap[SD.getFragment()] = &Symbol;
479 // Set the fragment atom associations by tracking the last seen atom defining
481 for (MCAssembler::iterator it = getAssembler().begin(),
482 ie = getAssembler().end(); it != ie; ++it) {
483 const MCSymbol *CurrentAtom = nullptr;
484 for (MCSection::iterator it2 = it->begin(), ie2 = it->end(); it2 != ie2;
486 if (const MCSymbol *Symbol = DefiningSymbolMap.lookup(it2))
487 CurrentAtom = Symbol;
488 it2->setAtom(CurrentAtom);
492 this->MCObjectStreamer::FinishImpl();
495 MCStreamer *llvm::createMachOStreamer(MCContext &Context, MCAsmBackend &MAB,
496 raw_pwrite_stream &OS, MCCodeEmitter *CE,
497 bool RelaxAll, bool DWARFMustBeAtTheEnd,
498 bool LabelSections) {
499 MCMachOStreamer *S = new MCMachOStreamer(Context, MAB, OS, CE,
500 DWARFMustBeAtTheEnd, LabelSections);
502 S->getAssembler().setRelaxAll(true);