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 void EmitInstToData(const MCInst &Inst, const MCSubtargetInfo &STI) override;
36 void EmitDataRegion(DataRegionData::KindTy Kind);
37 void EmitDataRegionEnd();
39 MCMachOStreamer(MCContext &Context, MCAsmBackend &MAB, raw_ostream &OS,
40 MCCodeEmitter *Emitter)
41 : MCObjectStreamer(Context, MAB, OS, Emitter) {}
43 /// @name MCStreamer Interface
46 void EmitLabel(MCSymbol *Symbol) override;
47 void EmitDebugLabel(MCSymbol *Symbol) override;
48 void EmitEHSymAttributes(const MCSymbol *Symbol, MCSymbol *EHSymbol) override;
49 void EmitAssemblerFlag(MCAssemblerFlag Flag) override;
50 void EmitLinkerOptions(ArrayRef<std::string> Options) override;
51 void EmitDataRegion(MCDataRegionType Kind) override;
52 void EmitVersionMin(MCVersionMinType Kind, unsigned Major,
53 unsigned Minor, unsigned Update) override;
54 void EmitThumbFunc(MCSymbol *Func) override;
55 bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override;
56 void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) override;
57 void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
58 unsigned ByteAlignment) override;
59 void BeginCOFFSymbolDef(const MCSymbol *Symbol) override {
60 llvm_unreachable("macho doesn't support this directive");
62 void EmitCOFFSymbolStorageClass(int StorageClass) override {
63 llvm_unreachable("macho doesn't support this directive");
65 void EmitCOFFSymbolType(int Type) override {
66 llvm_unreachable("macho doesn't support this directive");
68 void EndCOFFSymbolDef() override {
69 llvm_unreachable("macho doesn't support this directive");
71 void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) override {
72 llvm_unreachable("macho doesn't support this directive");
74 void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
75 unsigned ByteAlignment) override;
76 void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
77 uint64_t Size = 0, unsigned ByteAlignment = 0) override;
78 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
79 uint64_t Size, unsigned ByteAlignment = 0) override;
81 void EmitFileDirective(StringRef Filename) override {
82 // FIXME: Just ignore the .file; it isn't important enough to fail the
85 // report_fatal_error("unsupported directive: '.file'");
88 void EmitIdent(StringRef IdentString) override {
89 llvm_unreachable("macho doesn't support this directive");
92 void FinishImpl() override;
95 } // end anonymous namespace.
97 void MCMachOStreamer::EmitEHSymAttributes(const MCSymbol *Symbol,
100 getAssembler().getOrCreateSymbolData(*Symbol);
102 EmitSymbolAttribute(EHSymbol, MCSA_Global);
103 if (SD.getFlags() & SF_WeakDefinition)
104 EmitSymbolAttribute(EHSymbol, MCSA_WeakDefinition);
105 if (SD.isPrivateExtern())
106 EmitSymbolAttribute(EHSymbol, MCSA_PrivateExtern);
109 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
110 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
112 // isSymbolLinkerVisible uses the section.
113 AssignSection(Symbol, getCurrentSection().first);
114 // We have to create a new fragment if this is an atom defining symbol,
115 // fragments cannot span atoms.
116 if (getAssembler().isSymbolLinkerVisible(*Symbol))
117 insert(new MCDataFragment());
119 MCObjectStreamer::EmitLabel(Symbol);
121 MCSymbolData &SD = getAssembler().getSymbolData(*Symbol);
122 // This causes the reference type flag to be cleared. Darwin 'as' was "trying"
123 // to clear the weak reference and weak definition bits too, but the
124 // implementation was buggy. For now we just try to match 'as', for
127 // FIXME: Cleanup this code, these bits should be emitted based on semantic
128 // properties, not on the order of definition, etc.
129 SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeMask);
132 void MCMachOStreamer::EmitDebugLabel(MCSymbol *Symbol) {
135 void MCMachOStreamer::EmitDataRegion(DataRegionData::KindTy Kind) {
136 if (!getAssembler().getBackend().hasDataInCodeSupport())
138 // Create a temporary label to mark the start of the data region.
139 MCSymbol *Start = getContext().CreateTempSymbol();
141 // Record the region for the object writer to use.
142 DataRegionData Data = { Kind, Start, NULL };
143 std::vector<DataRegionData> &Regions = getAssembler().getDataRegions();
144 Regions.push_back(Data);
147 void MCMachOStreamer::EmitDataRegionEnd() {
148 if (!getAssembler().getBackend().hasDataInCodeSupport())
150 std::vector<DataRegionData> &Regions = getAssembler().getDataRegions();
151 assert(Regions.size() && "Mismatched .end_data_region!");
152 DataRegionData &Data = Regions.back();
153 assert(Data.End == NULL && "Mismatched .end_data_region!");
154 // Create a temporary label to mark the end of the data region.
155 Data.End = getContext().CreateTempSymbol();
159 void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
160 // Let the target do whatever target specific stuff it needs to do.
161 getAssembler().getBackend().handleAssemblerFlag(Flag);
162 // Do any generic stuff we need to do.
164 case MCAF_SyntaxUnified: return; // no-op here.
165 case MCAF_Code16: return; // Change parsing mode; no-op here.
166 case MCAF_Code32: return; // Change parsing mode; no-op here.
167 case MCAF_Code64: return; // Change parsing mode; no-op here.
168 case MCAF_SubsectionsViaSymbols:
169 getAssembler().setSubsectionsViaSymbols(true);
174 void MCMachOStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) {
175 getAssembler().getLinkerOptions().push_back(Options);
178 void MCMachOStreamer::EmitDataRegion(MCDataRegionType Kind) {
180 case MCDR_DataRegion:
181 EmitDataRegion(DataRegionData::Data);
183 case MCDR_DataRegionJT8:
184 EmitDataRegion(DataRegionData::JumpTable8);
186 case MCDR_DataRegionJT16:
187 EmitDataRegion(DataRegionData::JumpTable16);
189 case MCDR_DataRegionJT32:
190 EmitDataRegion(DataRegionData::JumpTable32);
192 case MCDR_DataRegionEnd:
198 void MCMachOStreamer::EmitVersionMin(MCVersionMinType Kind, unsigned Major,
199 unsigned Minor, unsigned Update) {
200 getAssembler().setVersionMinInfo(Kind, Major, Minor, Update);
203 void MCMachOStreamer::EmitThumbFunc(MCSymbol *Symbol) {
204 // Remember that the function is a thumb function. Fixup and relocation
205 // values will need adjusted.
206 getAssembler().setIsThumbFunc(Symbol);
208 // Mark the thumb bit on the symbol.
209 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
210 SD.setFlags(SD.getFlags() | SF_ThumbFunc);
213 bool MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
214 MCSymbolAttr Attribute) {
215 // Indirect symbols are handled differently, to match how 'as' handles
216 // them. This makes writing matching .o files easier.
217 if (Attribute == MCSA_IndirectSymbol) {
218 // Note that we intentionally cannot use the symbol data here; this is
219 // important for matching the string table that 'as' generates.
220 IndirectSymbolData ISD;
222 ISD.SectionData = getCurrentSectionData();
223 getAssembler().getIndirectSymbols().push_back(ISD);
227 // Adding a symbol attribute always introduces the symbol, note that an
228 // important side effect of calling getOrCreateSymbolData here is to register
229 // the symbol with the assembler.
230 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
232 // The implementation of symbol attributes is designed to match 'as', but it
233 // leaves much to desired. It doesn't really make sense to arbitrarily add and
234 // remove flags, but 'as' allows this (in particular, see .desc).
236 // In the future it might be worth trying to make these operations more well
240 case MCSA_ELF_TypeFunction:
241 case MCSA_ELF_TypeIndFunction:
242 case MCSA_ELF_TypeObject:
243 case MCSA_ELF_TypeTLS:
244 case MCSA_ELF_TypeCommon:
245 case MCSA_ELF_TypeNoType:
246 case MCSA_ELF_TypeGnuUniqueObject:
248 case MCSA_IndirectSymbol:
256 SD.setExternal(true);
257 // This effectively clears the undefined lazy bit, in Darwin 'as', although
258 // it isn't very consistent because it implements this as part of symbol
261 // FIXME: Cleanup this code, these bits should be emitted based on semantic
262 // properties, not on the order of definition, etc.
263 SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeUndefinedLazy);
266 case MCSA_LazyReference:
267 // FIXME: This requires -dynamic.
268 SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
269 if (Symbol->isUndefined())
270 SD.setFlags(SD.getFlags() | SF_ReferenceTypeUndefinedLazy);
273 // Since .reference sets the no dead strip bit, it is equivalent to
274 // .no_dead_strip in practice.
276 case MCSA_NoDeadStrip:
277 SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
280 case MCSA_SymbolResolver:
281 SD.setFlags(SD.getFlags() | SF_SymbolResolver);
284 case MCSA_PrivateExtern:
285 SD.setExternal(true);
286 SD.setPrivateExtern(true);
289 case MCSA_WeakReference:
290 // FIXME: This requires -dynamic.
291 if (Symbol->isUndefined())
292 SD.setFlags(SD.getFlags() | SF_WeakReference);
295 case MCSA_WeakDefinition:
296 // FIXME: 'as' enforces that this is defined and global. The manual claims
297 // it has to be in a coalesced section, but this isn't enforced.
298 SD.setFlags(SD.getFlags() | SF_WeakDefinition);
301 case MCSA_WeakDefAutoPrivate:
302 SD.setFlags(SD.getFlags() | SF_WeakDefinition | SF_WeakReference);
309 void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
310 // Encode the 'desc' value into the lowest implementation defined bits.
311 assert(DescValue == (DescValue & SF_DescFlagsMask) &&
312 "Invalid .desc value!");
313 getAssembler().getOrCreateSymbolData(*Symbol).setFlags(
314 DescValue & SF_DescFlagsMask);
317 void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
318 unsigned ByteAlignment) {
319 // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
320 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
322 AssignSection(Symbol, NULL);
324 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
325 SD.setExternal(true);
326 SD.setCommon(Size, ByteAlignment);
329 void MCMachOStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
330 unsigned ByteAlignment) {
331 // '.lcomm' is equivalent to '.zerofill'.
332 return EmitZerofill(getContext().getObjectFileInfo()->getDataBSSSection(),
333 Symbol, Size, ByteAlignment);
336 void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
337 uint64_t Size, unsigned ByteAlignment) {
338 MCSectionData &SectData = getAssembler().getOrCreateSectionData(*Section);
340 // The symbol may not be present, which only creates the section.
344 // On darwin all virtual sections have zerofill type.
345 assert(Section->isVirtualSection() && "Section does not have zerofill type!");
347 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
349 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
351 // Emit an align fragment if necessary.
352 if (ByteAlignment != 1)
353 new MCAlignFragment(ByteAlignment, 0, 0, ByteAlignment, &SectData);
355 MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
358 AssignSection(Symbol, Section);
360 // Update the maximum alignment on the zero fill section if necessary.
361 if (ByteAlignment > SectData.getAlignment())
362 SectData.setAlignment(ByteAlignment);
365 // This should always be called with the thread local bss section. Like the
366 // .zerofill directive this doesn't actually switch sections on us.
367 void MCMachOStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
368 uint64_t Size, unsigned ByteAlignment) {
369 EmitZerofill(Section, Symbol, Size, ByteAlignment);
373 void MCMachOStreamer::EmitInstToData(const MCInst &Inst,
374 const MCSubtargetInfo &STI) {
375 MCDataFragment *DF = getOrCreateDataFragment();
377 SmallVector<MCFixup, 4> Fixups;
378 SmallString<256> Code;
379 raw_svector_ostream VecOS(Code);
380 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups, STI);
383 // Add the fixups and data.
384 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
385 Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
386 DF->getFixups().push_back(Fixups[i]);
388 DF->getContents().append(Code.begin(), Code.end());
391 void MCMachOStreamer::FinishImpl() {
392 EmitFrames(&getAssembler().getBackend(), true);
394 // We have to set the fragment atom associations so we can relax properly for
397 // First, scan the symbol table to build a lookup table from fragments to
399 DenseMap<const MCFragment*, MCSymbolData*> DefiningSymbolMap;
400 for (MCAssembler::symbol_iterator it = getAssembler().symbol_begin(),
401 ie = getAssembler().symbol_end(); it != ie; ++it) {
402 if (getAssembler().isSymbolLinkerVisible(it->getSymbol()) &&
404 // An atom defining symbol should never be internal to a fragment.
405 assert(it->getOffset() == 0 && "Invalid offset in atom defining symbol!");
406 DefiningSymbolMap[it->getFragment()] = it;
410 // Set the fragment atom associations by tracking the last seen atom defining
412 for (MCAssembler::iterator it = getAssembler().begin(),
413 ie = getAssembler().end(); it != ie; ++it) {
414 MCSymbolData *CurrentAtom = 0;
415 for (MCSectionData::iterator it2 = it->begin(),
416 ie2 = it->end(); it2 != ie2; ++it2) {
417 if (MCSymbolData *SD = DefiningSymbolMap.lookup(it2))
419 it2->setAtom(CurrentAtom);
423 this->MCObjectStreamer::FinishImpl();
426 MCStreamer *llvm::createMachOStreamer(MCContext &Context, MCAsmBackend &MAB,
427 raw_ostream &OS, MCCodeEmitter *CE,
429 MCMachOStreamer *S = new MCMachOStreamer(Context, MAB, OS, CE);
431 S->getAssembler().setRelaxAll(true);