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 EmitLabel(MCSymbol *Symbol);
48 virtual void EmitDebugLabel(MCSymbol *Symbol);
49 virtual void EmitEHSymAttributes(const MCSymbol *Symbol,
51 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
52 virtual void EmitLinkerOptions(ArrayRef<std::string> Options);
53 virtual void EmitDataRegion(MCDataRegionType Kind);
54 virtual void EmitThumbFunc(MCSymbol *Func);
55 virtual bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
56 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
57 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
58 unsigned ByteAlignment);
59 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {
60 llvm_unreachable("macho doesn't support this directive");
62 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
63 llvm_unreachable("macho doesn't support this directive");
65 virtual void EmitCOFFSymbolType(int Type) {
66 llvm_unreachable("macho doesn't support this directive");
68 virtual void EndCOFFSymbolDef() {
69 llvm_unreachable("macho doesn't support this directive");
71 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
72 llvm_unreachable("macho doesn't support this directive");
74 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
75 unsigned ByteAlignment);
76 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
77 uint64_t Size = 0, unsigned ByteAlignment = 0);
78 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
79 uint64_t Size, unsigned ByteAlignment = 0);
81 virtual void EmitFileDirective(StringRef Filename) {
82 // FIXME: Just ignore the .file; it isn't important enough to fail the
85 // report_fatal_error("unsupported directive: '.file'");
88 virtual void EmitIdent(StringRef IdentString) {
89 llvm_unreachable("macho doesn't support this directive");
92 virtual void FinishImpl();
95 } // end anonymous namespace.
97 void MCMachOStreamer::InitSections() {
98 SwitchSection(getContext().getObjectFileInfo()->getTextSection());
101 void MCMachOStreamer::EmitEHSymAttributes(const MCSymbol *Symbol,
102 MCSymbol *EHSymbol) {
104 getAssembler().getOrCreateSymbolData(*Symbol);
106 EmitSymbolAttribute(EHSymbol, MCSA_Global);
107 if (SD.getFlags() & SF_WeakDefinition)
108 EmitSymbolAttribute(EHSymbol, MCSA_WeakDefinition);
109 if (SD.isPrivateExtern())
110 EmitSymbolAttribute(EHSymbol, MCSA_PrivateExtern);
113 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
114 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
116 // isSymbolLinkerVisible uses the section.
117 AssignSection(Symbol, getCurrentSection().first);
118 // We have to create a new fragment if this is an atom defining symbol,
119 // fragments cannot span atoms.
120 if (getAssembler().isSymbolLinkerVisible(*Symbol))
121 insert(new MCDataFragment());
123 MCObjectStreamer::EmitLabel(Symbol);
125 MCSymbolData &SD = getAssembler().getSymbolData(*Symbol);
126 // This causes the reference type flag to be cleared. Darwin 'as' was "trying"
127 // to clear the weak reference and weak definition bits too, but the
128 // implementation was buggy. For now we just try to match 'as', for
131 // FIXME: Cleanup this code, these bits should be emitted based on semantic
132 // properties, not on the order of definition, etc.
133 SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeMask);
136 void MCMachOStreamer::EmitDebugLabel(MCSymbol *Symbol) {
139 void MCMachOStreamer::EmitDataRegion(DataRegionData::KindTy Kind) {
140 if (!getAssembler().getBackend().hasDataInCodeSupport())
142 // Create a temporary label to mark the start of the data region.
143 MCSymbol *Start = getContext().CreateTempSymbol();
145 // Record the region for the object writer to use.
146 DataRegionData Data = { Kind, Start, NULL };
147 std::vector<DataRegionData> &Regions = getAssembler().getDataRegions();
148 Regions.push_back(Data);
151 void MCMachOStreamer::EmitDataRegionEnd() {
152 if (!getAssembler().getBackend().hasDataInCodeSupport())
154 std::vector<DataRegionData> &Regions = getAssembler().getDataRegions();
155 assert(Regions.size() && "Mismatched .end_data_region!");
156 DataRegionData &Data = Regions.back();
157 assert(Data.End == NULL && "Mismatched .end_data_region!");
158 // Create a temporary label to mark the end of the data region.
159 Data.End = getContext().CreateTempSymbol();
163 void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
164 // Let the target do whatever target specific stuff it needs to do.
165 getAssembler().getBackend().handleAssemblerFlag(Flag);
166 // Do any generic stuff we need to do.
168 case MCAF_SyntaxUnified: return; // no-op here.
169 case MCAF_Code16: return; // Change parsing mode; no-op here.
170 case MCAF_Code32: return; // Change parsing mode; no-op here.
171 case MCAF_Code64: return; // Change parsing mode; no-op here.
172 case MCAF_SubsectionsViaSymbols:
173 getAssembler().setSubsectionsViaSymbols(true);
178 void MCMachOStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) {
179 getAssembler().getLinkerOptions().push_back(Options);
182 void MCMachOStreamer::EmitDataRegion(MCDataRegionType Kind) {
184 case MCDR_DataRegion:
185 EmitDataRegion(DataRegionData::Data);
187 case MCDR_DataRegionJT8:
188 EmitDataRegion(DataRegionData::JumpTable8);
190 case MCDR_DataRegionJT16:
191 EmitDataRegion(DataRegionData::JumpTable16);
193 case MCDR_DataRegionJT32:
194 EmitDataRegion(DataRegionData::JumpTable32);
196 case MCDR_DataRegionEnd:
202 void MCMachOStreamer::EmitThumbFunc(MCSymbol *Symbol) {
203 // Remember that the function is a thumb function. Fixup and relocation
204 // values will need adjusted.
205 getAssembler().setIsThumbFunc(Symbol);
207 // Mark the thumb bit on the symbol.
208 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
209 SD.setFlags(SD.getFlags() | SF_ThumbFunc);
212 bool MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
213 MCSymbolAttr Attribute) {
214 // Indirect symbols are handled differently, to match how 'as' handles
215 // them. This makes writing matching .o files easier.
216 if (Attribute == MCSA_IndirectSymbol) {
217 // Note that we intentionally cannot use the symbol data here; this is
218 // important for matching the string table that 'as' generates.
219 IndirectSymbolData ISD;
221 ISD.SectionData = getCurrentSectionData();
222 getAssembler().getIndirectSymbols().push_back(ISD);
226 // Adding a symbol attribute always introduces the symbol, note that an
227 // important side effect of calling getOrCreateSymbolData here is to register
228 // the symbol with the assembler.
229 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
231 // The implementation of symbol attributes is designed to match 'as', but it
232 // leaves much to desired. It doesn't really make sense to arbitrarily add and
233 // remove flags, but 'as' allows this (in particular, see .desc).
235 // In the future it might be worth trying to make these operations more well
239 case MCSA_ELF_TypeFunction:
240 case MCSA_ELF_TypeIndFunction:
241 case MCSA_ELF_TypeObject:
242 case MCSA_ELF_TypeTLS:
243 case MCSA_ELF_TypeCommon:
244 case MCSA_ELF_TypeNoType:
245 case MCSA_ELF_TypeGnuUniqueObject:
247 case MCSA_IndirectSymbol:
255 SD.setExternal(true);
256 // This effectively clears the undefined lazy bit, in Darwin 'as', although
257 // it isn't very consistent because it implements this as part of symbol
260 // FIXME: Cleanup this code, these bits should be emitted based on semantic
261 // properties, not on the order of definition, etc.
262 SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeUndefinedLazy);
265 case MCSA_LazyReference:
266 // FIXME: This requires -dynamic.
267 SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
268 if (Symbol->isUndefined())
269 SD.setFlags(SD.getFlags() | SF_ReferenceTypeUndefinedLazy);
272 // Since .reference sets the no dead strip bit, it is equivalent to
273 // .no_dead_strip in practice.
275 case MCSA_NoDeadStrip:
276 SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
279 case MCSA_SymbolResolver:
280 SD.setFlags(SD.getFlags() | SF_SymbolResolver);
283 case MCSA_PrivateExtern:
284 SD.setExternal(true);
285 SD.setPrivateExtern(true);
288 case MCSA_WeakReference:
289 // FIXME: This requires -dynamic.
290 if (Symbol->isUndefined())
291 SD.setFlags(SD.getFlags() | SF_WeakReference);
294 case MCSA_WeakDefinition:
295 // FIXME: 'as' enforces that this is defined and global. The manual claims
296 // it has to be in a coalesced section, but this isn't enforced.
297 SD.setFlags(SD.getFlags() | SF_WeakDefinition);
300 case MCSA_WeakDefAutoPrivate:
301 SD.setFlags(SD.getFlags() | SF_WeakDefinition | SF_WeakReference);
308 void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
309 // Encode the 'desc' value into the lowest implementation defined bits.
310 assert(DescValue == (DescValue & SF_DescFlagsMask) &&
311 "Invalid .desc value!");
312 getAssembler().getOrCreateSymbolData(*Symbol).setFlags(
313 DescValue & SF_DescFlagsMask);
316 void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
317 unsigned ByteAlignment) {
318 // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
319 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
321 AssignSection(Symbol, NULL);
323 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
324 SD.setExternal(true);
325 SD.setCommon(Size, ByteAlignment);
328 void MCMachOStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
329 unsigned ByteAlignment) {
330 // '.lcomm' is equivalent to '.zerofill'.
331 return EmitZerofill(getContext().getObjectFileInfo()->getDataBSSSection(),
332 Symbol, Size, ByteAlignment);
335 void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
336 uint64_t Size, unsigned ByteAlignment) {
337 MCSectionData &SectData = getAssembler().getOrCreateSectionData(*Section);
339 // The symbol may not be present, which only creates the section.
343 // On darwin all virtual sections have zerofill type.
344 assert(Section->isVirtualSection() && "Section does not have zerofill type!");
346 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
348 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
350 // Emit an align fragment if necessary.
351 if (ByteAlignment != 1)
352 new MCAlignFragment(ByteAlignment, 0, 0, ByteAlignment, &SectData);
354 MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
357 AssignSection(Symbol, Section);
359 // Update the maximum alignment on the zero fill section if necessary.
360 if (ByteAlignment > SectData.getAlignment())
361 SectData.setAlignment(ByteAlignment);
364 // This should always be called with the thread local bss section. Like the
365 // .zerofill directive this doesn't actually switch sections on us.
366 void MCMachOStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
367 uint64_t Size, unsigned ByteAlignment) {
368 EmitZerofill(Section, Symbol, Size, ByteAlignment);
372 void MCMachOStreamer::EmitInstToData(const MCInst &Inst) {
373 MCDataFragment *DF = getOrCreateDataFragment();
375 SmallVector<MCFixup, 4> Fixups;
376 SmallString<256> Code;
377 raw_svector_ostream VecOS(Code);
378 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
381 // Add the fixups and data.
382 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
383 Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
384 DF->getFixups().push_back(Fixups[i]);
386 DF->getContents().append(Code.begin(), Code.end());
389 void MCMachOStreamer::FinishImpl() {
390 EmitFrames(&getAssembler().getBackend(), true);
392 // We have to set the fragment atom associations so we can relax properly for
395 // First, scan the symbol table to build a lookup table from fragments to
397 DenseMap<const MCFragment*, MCSymbolData*> DefiningSymbolMap;
398 for (MCAssembler::symbol_iterator it = getAssembler().symbol_begin(),
399 ie = getAssembler().symbol_end(); it != ie; ++it) {
400 if (getAssembler().isSymbolLinkerVisible(it->getSymbol()) &&
402 // An atom defining symbol should never be internal to a fragment.
403 assert(it->getOffset() == 0 && "Invalid offset in atom defining symbol!");
404 DefiningSymbolMap[it->getFragment()] = it;
408 // Set the fragment atom associations by tracking the last seen atom defining
410 for (MCAssembler::iterator it = getAssembler().begin(),
411 ie = getAssembler().end(); it != ie; ++it) {
412 MCSymbolData *CurrentAtom = 0;
413 for (MCSectionData::iterator it2 = it->begin(),
414 ie2 = it->end(); it2 != ie2; ++it2) {
415 if (MCSymbolData *SD = DefiningSymbolMap.lookup(it2))
417 it2->setAtom(CurrentAtom);
421 this->MCObjectStreamer::FinishImpl();
424 MCStreamer *llvm::createMachOStreamer(MCContext &Context, MCAsmBackend &MAB,
425 raw_ostream &OS, MCCodeEmitter *CE,
427 MCMachOStreamer *S = new MCMachOStreamer(Context, MAB, OS, CE);
429 S->getAssembler().setRelaxAll(true);