Remove duplicated info on what .text, .data and .bss look like.
[oota-llvm.git] / lib / MC / MCMachOStreamer.cpp
1 //===-- MCMachOStreamer.cpp - MachO Streamer ------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
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"
27
28 using namespace llvm;
29
30 namespace {
31
32 class MCMachOStreamer : public MCObjectStreamer {
33 private:
34   virtual void EmitInstToData(const MCInst &Inst);
35
36   void EmitDataRegion(DataRegionData::KindTy Kind);
37   void EmitDataRegionEnd();
38 public:
39   MCMachOStreamer(MCContext &Context, MCAsmBackend &MAB, raw_ostream &OS,
40                   MCCodeEmitter *Emitter)
41       : MCObjectStreamer(Context, 0, MAB, OS, Emitter) {}
42
43   /// @name MCStreamer Interface
44   /// @{
45
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,
51                                    MCSymbol *EHSymbol);
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");
62   }
63   virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
64     llvm_unreachable("macho doesn't support this directive");
65   }
66   virtual void EmitCOFFSymbolType(int Type) {
67     llvm_unreachable("macho doesn't support this directive");
68   }
69   virtual void EndCOFFSymbolDef() {
70     llvm_unreachable("macho doesn't support this directive");
71   }
72   virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
73     llvm_unreachable("macho doesn't support this directive");
74   }
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);
81
82   virtual void EmitFileDirective(StringRef Filename) {
83     // FIXME: Just ignore the .file; it isn't important enough to fail the
84     // entire assembly.
85
86     // report_fatal_error("unsupported directive: '.file'");
87   }
88
89   virtual void EmitIdent(StringRef IdentString) {
90     llvm_unreachable("macho doesn't support this directive");
91   }
92
93   virtual void FinishImpl();
94 };
95
96 } // end anonymous namespace.
97
98 void MCMachOStreamer::InitSections() {
99   InitToTextSection();
100 }
101
102 void MCMachOStreamer::InitToTextSection() {
103   SwitchSection(getContext().getObjectFileInfo()->getTextSection());
104 }
105
106 void MCMachOStreamer::EmitEHSymAttributes(const MCSymbol *Symbol,
107                                           MCSymbol *EHSymbol) {
108   MCSymbolData &SD =
109     getAssembler().getOrCreateSymbolData(*Symbol);
110   if (SD.isExternal())
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);
116 }
117
118 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
119   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
120
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());
127
128   MCObjectStreamer::EmitLabel(Symbol);
129
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
134   // diffability.
135   //
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);
139 }
140
141 void MCMachOStreamer::EmitDebugLabel(MCSymbol *Symbol) {
142   EmitLabel(Symbol);
143 }
144 void MCMachOStreamer::EmitDataRegion(DataRegionData::KindTy Kind) {
145   if (!getAssembler().getBackend().hasDataInCodeSupport())
146     return;
147   // Create a temporary label to mark the start of the data region.
148   MCSymbol *Start = getContext().CreateTempSymbol();
149   EmitLabel(Start);
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);
154 }
155
156 void MCMachOStreamer::EmitDataRegionEnd() {
157   if (!getAssembler().getBackend().hasDataInCodeSupport())
158     return;
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();
165   EmitLabel(Data.End);
166 }
167
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.
172   switch (Flag) {
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);
179     return;
180   }
181 }
182
183 void MCMachOStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) {
184   getAssembler().getLinkerOptions().push_back(Options);
185 }
186
187 void MCMachOStreamer::EmitDataRegion(MCDataRegionType Kind) {
188   switch (Kind) {
189   case MCDR_DataRegion:
190     EmitDataRegion(DataRegionData::Data);
191     return;
192   case MCDR_DataRegionJT8:
193     EmitDataRegion(DataRegionData::JumpTable8);
194     return;
195   case MCDR_DataRegionJT16:
196     EmitDataRegion(DataRegionData::JumpTable16);
197     return;
198   case MCDR_DataRegionJT32:
199     EmitDataRegion(DataRegionData::JumpTable32);
200     return;
201   case MCDR_DataRegionEnd:
202     EmitDataRegionEnd();
203     return;
204   }
205 }
206
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);
211
212   // Mark the thumb bit on the symbol.
213   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
214   SD.setFlags(SD.getFlags() | SF_ThumbFunc);
215 }
216
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;
225     ISD.Symbol = Symbol;
226     ISD.SectionData = getCurrentSectionData();
227     getAssembler().getIndirectSymbols().push_back(ISD);
228     return true;
229   }
230
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);
235
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).
239   //
240   // In the future it might be worth trying to make these operations more well
241   // defined.
242   switch (Attribute) {
243   case MCSA_Invalid:
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:
251   case MCSA_Hidden:
252   case MCSA_IndirectSymbol:
253   case MCSA_Internal:
254   case MCSA_Protected:
255   case MCSA_Weak:
256   case MCSA_Local:
257     return false;
258
259   case MCSA_Global:
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
263     // lookup.
264     //
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);
268     break;
269
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);
275     break;
276
277     // Since .reference sets the no dead strip bit, it is equivalent to
278     // .no_dead_strip in practice.
279   case MCSA_Reference:
280   case MCSA_NoDeadStrip:
281     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
282     break;
283
284   case MCSA_SymbolResolver:
285     SD.setFlags(SD.getFlags() | SF_SymbolResolver);
286     break;
287
288   case MCSA_PrivateExtern:
289     SD.setExternal(true);
290     SD.setPrivateExtern(true);
291     break;
292
293   case MCSA_WeakReference:
294     // FIXME: This requires -dynamic.
295     if (Symbol->isUndefined())
296       SD.setFlags(SD.getFlags() | SF_WeakReference);
297     break;
298
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);
303     break;
304
305   case MCSA_WeakDefAutoPrivate:
306     SD.setFlags(SD.getFlags() | SF_WeakDefinition | SF_WeakReference);
307     break;
308   }
309
310   return true;
311 }
312
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);
319 }
320
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!");
325
326   AssignSection(Symbol, NULL);
327
328   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
329   SD.setExternal(true);
330   SD.setCommon(Size, ByteAlignment);
331 }
332
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);
338 }
339
340 void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
341                                    uint64_t Size, unsigned ByteAlignment) {
342   MCSectionData &SectData = getAssembler().getOrCreateSectionData(*Section);
343
344   // The symbol may not be present, which only creates the section.
345   if (!Symbol)
346     return;
347
348   // On darwin all virtual sections have zerofill type.
349   assert(Section->isVirtualSection() && "Section does not have zerofill type!");
350
351   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
352
353   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
354
355   // Emit an align fragment if necessary.
356   if (ByteAlignment != 1)
357     new MCAlignFragment(ByteAlignment, 0, 0, ByteAlignment, &SectData);
358
359   MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
360   SD.setFragment(F);
361
362   AssignSection(Symbol, Section);
363
364   // Update the maximum alignment on the zero fill section if necessary.
365   if (ByteAlignment > SectData.getAlignment())
366     SectData.setAlignment(ByteAlignment);
367 }
368
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);
374   return;
375 }
376
377 void MCMachOStreamer::EmitInstToData(const MCInst &Inst) {
378   MCDataFragment *DF = getOrCreateDataFragment();
379
380   SmallVector<MCFixup, 4> Fixups;
381   SmallString<256> Code;
382   raw_svector_ostream VecOS(Code);
383   getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
384   VecOS.flush();
385
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]);
390   }
391   DF->getContents().append(Code.begin(), Code.end());
392 }
393
394 void MCMachOStreamer::FinishImpl() {
395   EmitFrames(&getAssembler().getBackend(), true);
396
397   // We have to set the fragment atom associations so we can relax properly for
398   // Mach-O.
399
400   // First, scan the symbol table to build a lookup table from fragments to
401   // defining symbols.
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()) &&
406         it->getFragment()) {
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;
410     }
411   }
412
413   // Set the fragment atom associations by tracking the last seen atom defining
414   // symbol.
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))
421         CurrentAtom = SD;
422       it2->setAtom(CurrentAtom);
423     }
424   }
425
426   this->MCObjectStreamer::FinishImpl();
427 }
428
429 MCStreamer *llvm::createMachOStreamer(MCContext &Context, MCAsmBackend &MAB,
430                                       raw_ostream &OS, MCCodeEmitter *CE,
431                                       bool RelaxAll) {
432   MCMachOStreamer *S = new MCMachOStreamer(Context, MAB, OS, CE);
433   if (RelaxAll)
434     S->getAssembler().setRelaxAll(true);
435   return S;
436 }