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/MC/MCAsmBackend.h"
12 #include "llvm/MC/MCAssembler.h"
13 #include "llvm/MC/MCCodeEmitter.h"
14 #include "llvm/MC/MCContext.h"
15 #include "llvm/MC/MCDwarf.h"
16 #include "llvm/MC/MCExpr.h"
17 #include "llvm/MC/MCInst.h"
18 #include "llvm/MC/MCMachOSymbolFlags.h"
19 #include "llvm/MC/MCObjectFileInfo.h"
20 #include "llvm/MC/MCObjectStreamer.h"
21 #include "llvm/MC/MCSection.h"
22 #include "llvm/MC/MCSectionMachO.h"
23 #include "llvm/MC/MCSymbol.h"
24 #include "llvm/Support/Dwarf.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
32 class MCMachOStreamer : public MCObjectStreamer {
34 virtual void EmitInstToData(const MCInst &Inst);
36 void EmitDataRegion(DataRegionData::KindTy Kind);
37 void EmitDataRegionEnd();
39 MCMachOStreamer(MCContext &Context, MCAsmBackend &MAB, raw_ostream &OS,
40 MCCodeEmitter *Emitter)
41 : MCObjectStreamer(Context, 0, MAB, OS, Emitter) {}
43 /// @name MCStreamer Interface
46 virtual void InitSections();
47 virtual void InitToTextSection();
48 virtual void EmitLabel(MCSymbol *Symbol);
49 virtual void EmitDebugLabel(MCSymbol *Symbol);
50 virtual void EmitEHSymAttributes(const MCSymbol *Symbol,
52 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
53 virtual void EmitLinkerOptions(ArrayRef<std::string> Options);
54 virtual void EmitDataRegion(MCDataRegionType Kind);
55 virtual void EmitThumbFunc(MCSymbol *Func);
56 virtual bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
57 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
58 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
59 unsigned ByteAlignment);
60 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {
61 llvm_unreachable("macho doesn't support this directive");
63 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
64 llvm_unreachable("macho doesn't support this directive");
66 virtual void EmitCOFFSymbolType(int Type) {
67 llvm_unreachable("macho doesn't support this directive");
69 virtual void EndCOFFSymbolDef() {
70 llvm_unreachable("macho doesn't support this directive");
72 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
73 llvm_unreachable("macho doesn't support this directive");
75 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
76 unsigned ByteAlignment);
77 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
78 uint64_t Size = 0, unsigned ByteAlignment = 0);
79 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
80 uint64_t Size, unsigned ByteAlignment = 0);
82 virtual void EmitFileDirective(StringRef Filename) {
83 // FIXME: Just ignore the .file; it isn't important enough to fail the
86 // report_fatal_error("unsupported directive: '.file'");
89 virtual void EmitIdent(StringRef IdentString) {
90 llvm_unreachable("macho doesn't support this directive");
93 virtual void FinishImpl();
96 } // end anonymous namespace.
98 void MCMachOStreamer::InitSections() {
102 void MCMachOStreamer::InitToTextSection() {
103 SwitchSection(getContext().getObjectFileInfo()->getTextSection());
106 void MCMachOStreamer::EmitEHSymAttributes(const MCSymbol *Symbol,
107 MCSymbol *EHSymbol) {
109 getAssembler().getOrCreateSymbolData(*Symbol);
111 EmitSymbolAttribute(EHSymbol, MCSA_Global);
112 if (SD.getFlags() & SF_WeakDefinition)
113 EmitSymbolAttribute(EHSymbol, MCSA_WeakDefinition);
114 if (SD.isPrivateExtern())
115 EmitSymbolAttribute(EHSymbol, MCSA_PrivateExtern);
118 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
119 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
121 // isSymbolLinkerVisible uses the section.
122 AssignSection(Symbol, getCurrentSection().first);
123 // We have to create a new fragment if this is an atom defining symbol,
124 // fragments cannot span atoms.
125 if (getAssembler().isSymbolLinkerVisible(*Symbol))
126 insert(new MCDataFragment());
128 MCObjectStreamer::EmitLabel(Symbol);
130 MCSymbolData &SD = getAssembler().getSymbolData(*Symbol);
131 // This causes the reference type flag to be cleared. Darwin 'as' was "trying"
132 // to clear the weak reference and weak definition bits too, but the
133 // implementation was buggy. For now we just try to match 'as', for
136 // FIXME: Cleanup this code, these bits should be emitted based on semantic
137 // properties, not on the order of definition, etc.
138 SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeMask);
141 void MCMachOStreamer::EmitDebugLabel(MCSymbol *Symbol) {
144 void MCMachOStreamer::EmitDataRegion(DataRegionData::KindTy Kind) {
145 if (!getAssembler().getBackend().hasDataInCodeSupport())
147 // Create a temporary label to mark the start of the data region.
148 MCSymbol *Start = getContext().CreateTempSymbol();
150 // Record the region for the object writer to use.
151 DataRegionData Data = { Kind, Start, NULL };
152 std::vector<DataRegionData> &Regions = getAssembler().getDataRegions();
153 Regions.push_back(Data);
156 void MCMachOStreamer::EmitDataRegionEnd() {
157 if (!getAssembler().getBackend().hasDataInCodeSupport())
159 std::vector<DataRegionData> &Regions = getAssembler().getDataRegions();
160 assert(Regions.size() && "Mismatched .end_data_region!");
161 DataRegionData &Data = Regions.back();
162 assert(Data.End == NULL && "Mismatched .end_data_region!");
163 // Create a temporary label to mark the end of the data region.
164 Data.End = getContext().CreateTempSymbol();
168 void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
169 // Let the target do whatever target specific stuff it needs to do.
170 getAssembler().getBackend().handleAssemblerFlag(Flag);
171 // Do any generic stuff we need to do.
173 case MCAF_SyntaxUnified: return; // no-op here.
174 case MCAF_Code16: return; // Change parsing mode; no-op here.
175 case MCAF_Code32: return; // Change parsing mode; no-op here.
176 case MCAF_Code64: return; // Change parsing mode; no-op here.
177 case MCAF_SubsectionsViaSymbols:
178 getAssembler().setSubsectionsViaSymbols(true);
183 void MCMachOStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) {
184 getAssembler().getLinkerOptions().push_back(Options);
187 void MCMachOStreamer::EmitDataRegion(MCDataRegionType Kind) {
189 case MCDR_DataRegion:
190 EmitDataRegion(DataRegionData::Data);
192 case MCDR_DataRegionJT8:
193 EmitDataRegion(DataRegionData::JumpTable8);
195 case MCDR_DataRegionJT16:
196 EmitDataRegion(DataRegionData::JumpTable16);
198 case MCDR_DataRegionJT32:
199 EmitDataRegion(DataRegionData::JumpTable32);
201 case MCDR_DataRegionEnd:
207 void MCMachOStreamer::EmitThumbFunc(MCSymbol *Symbol) {
208 // Remember that the function is a thumb function. Fixup and relocation
209 // values will need adjusted.
210 getAssembler().setIsThumbFunc(Symbol);
212 // Mark the thumb bit on the symbol.
213 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
214 SD.setFlags(SD.getFlags() | SF_ThumbFunc);
217 bool MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
218 MCSymbolAttr Attribute) {
219 // Indirect symbols are handled differently, to match how 'as' handles
220 // them. This makes writing matching .o files easier.
221 if (Attribute == MCSA_IndirectSymbol) {
222 // Note that we intentionally cannot use the symbol data here; this is
223 // important for matching the string table that 'as' generates.
224 IndirectSymbolData ISD;
226 ISD.SectionData = getCurrentSectionData();
227 getAssembler().getIndirectSymbols().push_back(ISD);
231 // Adding a symbol attribute always introduces the symbol, note that an
232 // important side effect of calling getOrCreateSymbolData here is to register
233 // the symbol with the assembler.
234 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
236 // The implementation of symbol attributes is designed to match 'as', but it
237 // leaves much to desired. It doesn't really make sense to arbitrarily add and
238 // remove flags, but 'as' allows this (in particular, see .desc).
240 // In the future it might be worth trying to make these operations more well
244 case MCSA_ELF_TypeFunction:
245 case MCSA_ELF_TypeIndFunction:
246 case MCSA_ELF_TypeObject:
247 case MCSA_ELF_TypeTLS:
248 case MCSA_ELF_TypeCommon:
249 case MCSA_ELF_TypeNoType:
250 case MCSA_ELF_TypeGnuUniqueObject:
252 case MCSA_IndirectSymbol:
260 SD.setExternal(true);
261 // This effectively clears the undefined lazy bit, in Darwin 'as', although
262 // it isn't very consistent because it implements this as part of symbol
265 // FIXME: Cleanup this code, these bits should be emitted based on semantic
266 // properties, not on the order of definition, etc.
267 SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeUndefinedLazy);
270 case MCSA_LazyReference:
271 // FIXME: This requires -dynamic.
272 SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
273 if (Symbol->isUndefined())
274 SD.setFlags(SD.getFlags() | SF_ReferenceTypeUndefinedLazy);
277 // Since .reference sets the no dead strip bit, it is equivalent to
278 // .no_dead_strip in practice.
280 case MCSA_NoDeadStrip:
281 SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
284 case MCSA_SymbolResolver:
285 SD.setFlags(SD.getFlags() | SF_SymbolResolver);
288 case MCSA_PrivateExtern:
289 SD.setExternal(true);
290 SD.setPrivateExtern(true);
293 case MCSA_WeakReference:
294 // FIXME: This requires -dynamic.
295 if (Symbol->isUndefined())
296 SD.setFlags(SD.getFlags() | SF_WeakReference);
299 case MCSA_WeakDefinition:
300 // FIXME: 'as' enforces that this is defined and global. The manual claims
301 // it has to be in a coalesced section, but this isn't enforced.
302 SD.setFlags(SD.getFlags() | SF_WeakDefinition);
305 case MCSA_WeakDefAutoPrivate:
306 SD.setFlags(SD.getFlags() | SF_WeakDefinition | SF_WeakReference);
313 void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
314 // Encode the 'desc' value into the lowest implementation defined bits.
315 assert(DescValue == (DescValue & SF_DescFlagsMask) &&
316 "Invalid .desc value!");
317 getAssembler().getOrCreateSymbolData(*Symbol).setFlags(
318 DescValue & SF_DescFlagsMask);
321 void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
322 unsigned ByteAlignment) {
323 // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
324 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
326 AssignSection(Symbol, NULL);
328 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
329 SD.setExternal(true);
330 SD.setCommon(Size, ByteAlignment);
333 void MCMachOStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
334 unsigned ByteAlignment) {
335 // '.lcomm' is equivalent to '.zerofill'.
336 return EmitZerofill(getContext().getObjectFileInfo()->getDataBSSSection(),
337 Symbol, Size, ByteAlignment);
340 void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
341 uint64_t Size, unsigned ByteAlignment) {
342 MCSectionData &SectData = getAssembler().getOrCreateSectionData(*Section);
344 // The symbol may not be present, which only creates the section.
348 // On darwin all virtual sections have zerofill type.
349 assert(Section->isVirtualSection() && "Section does not have zerofill type!");
351 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
353 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
355 // Emit an align fragment if necessary.
356 if (ByteAlignment != 1)
357 new MCAlignFragment(ByteAlignment, 0, 0, ByteAlignment, &SectData);
359 MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
362 AssignSection(Symbol, Section);
364 // Update the maximum alignment on the zero fill section if necessary.
365 if (ByteAlignment > SectData.getAlignment())
366 SectData.setAlignment(ByteAlignment);
369 // This should always be called with the thread local bss section. Like the
370 // .zerofill directive this doesn't actually switch sections on us.
371 void MCMachOStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
372 uint64_t Size, unsigned ByteAlignment) {
373 EmitZerofill(Section, Symbol, Size, ByteAlignment);
377 void MCMachOStreamer::EmitInstToData(const MCInst &Inst) {
378 MCDataFragment *DF = getOrCreateDataFragment();
380 SmallVector<MCFixup, 4> Fixups;
381 SmallString<256> Code;
382 raw_svector_ostream VecOS(Code);
383 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
386 // Add the fixups and data.
387 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
388 Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
389 DF->getFixups().push_back(Fixups[i]);
391 DF->getContents().append(Code.begin(), Code.end());
394 void MCMachOStreamer::FinishImpl() {
395 EmitFrames(&getAssembler().getBackend(), true);
397 // We have to set the fragment atom associations so we can relax properly for
400 // First, scan the symbol table to build a lookup table from fragments to
402 DenseMap<const MCFragment*, MCSymbolData*> DefiningSymbolMap;
403 for (MCAssembler::symbol_iterator it = getAssembler().symbol_begin(),
404 ie = getAssembler().symbol_end(); it != ie; ++it) {
405 if (getAssembler().isSymbolLinkerVisible(it->getSymbol()) &&
407 // An atom defining symbol should never be internal to a fragment.
408 assert(it->getOffset() == 0 && "Invalid offset in atom defining symbol!");
409 DefiningSymbolMap[it->getFragment()] = it;
413 // Set the fragment atom associations by tracking the last seen atom defining
415 for (MCAssembler::iterator it = getAssembler().begin(),
416 ie = getAssembler().end(); it != ie; ++it) {
417 MCSymbolData *CurrentAtom = 0;
418 for (MCSectionData::iterator it2 = it->begin(),
419 ie2 = it->end(); it2 != ie2; ++it2) {
420 if (MCSymbolData *SD = DefiningSymbolMap.lookup(it2))
422 it2->setAtom(CurrentAtom);
426 this->MCObjectStreamer::FinishImpl();
429 MCStreamer *llvm::createMachOStreamer(MCContext &Context, MCAsmBackend &MAB,
430 raw_ostream &OS, MCCodeEmitter *CE,
432 MCMachOStreamer *S = new MCMachOStreamer(Context, MAB, OS, CE);
434 S->getAssembler().setRelaxAll(true);