InitToTextSection is redundant with InitSections. Remove it.
[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 EmitLabel(MCSymbol *Symbol);
48   virtual void EmitDebugLabel(MCSymbol *Symbol);
49   virtual void EmitEHSymAttributes(const MCSymbol *Symbol,
50                                    MCSymbol *EHSymbol);
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");
61   }
62   virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
63     llvm_unreachable("macho doesn't support this directive");
64   }
65   virtual void EmitCOFFSymbolType(int Type) {
66     llvm_unreachable("macho doesn't support this directive");
67   }
68   virtual void EndCOFFSymbolDef() {
69     llvm_unreachable("macho doesn't support this directive");
70   }
71   virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
72     llvm_unreachable("macho doesn't support this directive");
73   }
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);
80
81   virtual void EmitFileDirective(StringRef Filename) {
82     // FIXME: Just ignore the .file; it isn't important enough to fail the
83     // entire assembly.
84
85     // report_fatal_error("unsupported directive: '.file'");
86   }
87
88   virtual void EmitIdent(StringRef IdentString) {
89     llvm_unreachable("macho doesn't support this directive");
90   }
91
92   virtual void FinishImpl();
93 };
94
95 } // end anonymous namespace.
96
97 void MCMachOStreamer::InitSections() {
98   SwitchSection(getContext().getObjectFileInfo()->getTextSection());
99 }
100
101 void MCMachOStreamer::EmitEHSymAttributes(const MCSymbol *Symbol,
102                                           MCSymbol *EHSymbol) {
103   MCSymbolData &SD =
104     getAssembler().getOrCreateSymbolData(*Symbol);
105   if (SD.isExternal())
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);
111 }
112
113 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
114   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
115
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());
122
123   MCObjectStreamer::EmitLabel(Symbol);
124
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
129   // diffability.
130   //
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);
134 }
135
136 void MCMachOStreamer::EmitDebugLabel(MCSymbol *Symbol) {
137   EmitLabel(Symbol);
138 }
139 void MCMachOStreamer::EmitDataRegion(DataRegionData::KindTy Kind) {
140   if (!getAssembler().getBackend().hasDataInCodeSupport())
141     return;
142   // Create a temporary label to mark the start of the data region.
143   MCSymbol *Start = getContext().CreateTempSymbol();
144   EmitLabel(Start);
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);
149 }
150
151 void MCMachOStreamer::EmitDataRegionEnd() {
152   if (!getAssembler().getBackend().hasDataInCodeSupport())
153     return;
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();
160   EmitLabel(Data.End);
161 }
162
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.
167   switch (Flag) {
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);
174     return;
175   }
176 }
177
178 void MCMachOStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) {
179   getAssembler().getLinkerOptions().push_back(Options);
180 }
181
182 void MCMachOStreamer::EmitDataRegion(MCDataRegionType Kind) {
183   switch (Kind) {
184   case MCDR_DataRegion:
185     EmitDataRegion(DataRegionData::Data);
186     return;
187   case MCDR_DataRegionJT8:
188     EmitDataRegion(DataRegionData::JumpTable8);
189     return;
190   case MCDR_DataRegionJT16:
191     EmitDataRegion(DataRegionData::JumpTable16);
192     return;
193   case MCDR_DataRegionJT32:
194     EmitDataRegion(DataRegionData::JumpTable32);
195     return;
196   case MCDR_DataRegionEnd:
197     EmitDataRegionEnd();
198     return;
199   }
200 }
201
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);
206
207   // Mark the thumb bit on the symbol.
208   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
209   SD.setFlags(SD.getFlags() | SF_ThumbFunc);
210 }
211
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;
220     ISD.Symbol = Symbol;
221     ISD.SectionData = getCurrentSectionData();
222     getAssembler().getIndirectSymbols().push_back(ISD);
223     return true;
224   }
225
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);
230
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).
234   //
235   // In the future it might be worth trying to make these operations more well
236   // defined.
237   switch (Attribute) {
238   case MCSA_Invalid:
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:
246   case MCSA_Hidden:
247   case MCSA_IndirectSymbol:
248   case MCSA_Internal:
249   case MCSA_Protected:
250   case MCSA_Weak:
251   case MCSA_Local:
252     return false;
253
254   case MCSA_Global:
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
258     // lookup.
259     //
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);
263     break;
264
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);
270     break;
271
272     // Since .reference sets the no dead strip bit, it is equivalent to
273     // .no_dead_strip in practice.
274   case MCSA_Reference:
275   case MCSA_NoDeadStrip:
276     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
277     break;
278
279   case MCSA_SymbolResolver:
280     SD.setFlags(SD.getFlags() | SF_SymbolResolver);
281     break;
282
283   case MCSA_PrivateExtern:
284     SD.setExternal(true);
285     SD.setPrivateExtern(true);
286     break;
287
288   case MCSA_WeakReference:
289     // FIXME: This requires -dynamic.
290     if (Symbol->isUndefined())
291       SD.setFlags(SD.getFlags() | SF_WeakReference);
292     break;
293
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);
298     break;
299
300   case MCSA_WeakDefAutoPrivate:
301     SD.setFlags(SD.getFlags() | SF_WeakDefinition | SF_WeakReference);
302     break;
303   }
304
305   return true;
306 }
307
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);
314 }
315
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!");
320
321   AssignSection(Symbol, NULL);
322
323   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
324   SD.setExternal(true);
325   SD.setCommon(Size, ByteAlignment);
326 }
327
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);
333 }
334
335 void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
336                                    uint64_t Size, unsigned ByteAlignment) {
337   MCSectionData &SectData = getAssembler().getOrCreateSectionData(*Section);
338
339   // The symbol may not be present, which only creates the section.
340   if (!Symbol)
341     return;
342
343   // On darwin all virtual sections have zerofill type.
344   assert(Section->isVirtualSection() && "Section does not have zerofill type!");
345
346   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
347
348   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
349
350   // Emit an align fragment if necessary.
351   if (ByteAlignment != 1)
352     new MCAlignFragment(ByteAlignment, 0, 0, ByteAlignment, &SectData);
353
354   MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
355   SD.setFragment(F);
356
357   AssignSection(Symbol, Section);
358
359   // Update the maximum alignment on the zero fill section if necessary.
360   if (ByteAlignment > SectData.getAlignment())
361     SectData.setAlignment(ByteAlignment);
362 }
363
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);
369   return;
370 }
371
372 void MCMachOStreamer::EmitInstToData(const MCInst &Inst) {
373   MCDataFragment *DF = getOrCreateDataFragment();
374
375   SmallVector<MCFixup, 4> Fixups;
376   SmallString<256> Code;
377   raw_svector_ostream VecOS(Code);
378   getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
379   VecOS.flush();
380
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]);
385   }
386   DF->getContents().append(Code.begin(), Code.end());
387 }
388
389 void MCMachOStreamer::FinishImpl() {
390   EmitFrames(&getAssembler().getBackend(), true);
391
392   // We have to set the fragment atom associations so we can relax properly for
393   // Mach-O.
394
395   // First, scan the symbol table to build a lookup table from fragments to
396   // defining symbols.
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()) &&
401         it->getFragment()) {
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;
405     }
406   }
407
408   // Set the fragment atom associations by tracking the last seen atom defining
409   // symbol.
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))
416         CurrentAtom = SD;
417       it2->setAtom(CurrentAtom);
418     }
419   }
420
421   this->MCObjectStreamer::FinishImpl();
422 }
423
424 MCStreamer *llvm::createMachOStreamer(MCContext &Context, MCAsmBackend &MAB,
425                                       raw_ostream &OS, MCCodeEmitter *CE,
426                                       bool RelaxAll) {
427   MCMachOStreamer *S = new MCMachOStreamer(Context, MAB, OS, CE);
428   if (RelaxAll)
429     S->getAssembler().setRelaxAll(true);
430   return S;
431 }