970aa8baf43c094c390be5b6add172ed509d669e
[oota-llvm.git] / lib / MC / MCMachOStreamer.cpp
1 //
2 //                     The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "llvm/MC/MCStreamer.h"
10
11 #include "llvm/MC/MCAssembler.h"
12 #include "llvm/MC/MCContext.h"
13 #include "llvm/MC/MCCodeEmitter.h"
14 #include "llvm/MC/MCExpr.h"
15 #include "llvm/MC/MCInst.h"
16 #include "llvm/MC/MCObjectStreamer.h"
17 #include "llvm/MC/MCSection.h"
18 #include "llvm/MC/MCSymbol.h"
19 #include "llvm/MC/MCMachOSymbolFlags.h"
20 #include "llvm/MC/MCSectionMachO.h"
21 #include "llvm/MC/MCDwarf.h"
22 #include "llvm/MC/MCAsmBackend.h"
23 #include "llvm/Support/Dwarf.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/raw_ostream.h"
26
27 using namespace llvm;
28
29 namespace {
30
31 class MCMachOStreamer : public MCObjectStreamer {
32 private:
33   virtual void EmitInstToData(const MCInst &Inst);
34
35   void EmitDataRegion(DataRegionData::KindTy Kind);
36   void EmitDataRegionEnd();
37 public:
38   MCMachOStreamer(MCContext &Context, MCAsmBackend &MAB,
39                   raw_ostream &OS, MCCodeEmitter *Emitter)
40     : MCObjectStreamer(Context, MAB, OS, Emitter) {}
41
42   /// @name MCStreamer Interface
43   /// @{
44
45   virtual void InitSections();
46   virtual void EmitLabel(MCSymbol *Symbol);
47   virtual void EmitEHSymAttributes(const MCSymbol *Symbol,
48                                    MCSymbol *EHSymbol);
49   virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
50   virtual void EmitDataRegion(MCDataRegionType Kind);
51   virtual void EmitThumbFunc(MCSymbol *Func);
52   virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
53   virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
54   virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
55   virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
56                                 unsigned ByteAlignment);
57   virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {
58     llvm_unreachable("macho doesn't support this directive");
59   }
60   virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
61     llvm_unreachable("macho doesn't support this directive");
62   }
63   virtual void EmitCOFFSymbolType(int Type) {
64     llvm_unreachable("macho doesn't support this directive");
65   }
66   virtual void EndCOFFSymbolDef() {
67     llvm_unreachable("macho doesn't support this directive");
68   }
69   virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
70     llvm_unreachable("macho doesn't support this directive");
71   }
72   virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
73                                      unsigned ByteAlignment) {
74     llvm_unreachable("macho doesn't support this directive");
75   }
76   virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
77                             unsigned Size = 0, unsigned ByteAlignment = 0);
78   virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
79                               uint64_t Size, unsigned ByteAlignment = 0);
80   virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
81   virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
82                                     unsigned ValueSize = 1,
83                                     unsigned MaxBytesToEmit = 0);
84   virtual void EmitCodeAlignment(unsigned ByteAlignment,
85                                  unsigned MaxBytesToEmit = 0);
86
87   virtual void EmitFileDirective(StringRef Filename) {
88     // FIXME: Just ignore the .file; it isn't important enough to fail the
89     // entire assembly.
90
91     //report_fatal_error("unsupported directive: '.file'");
92   }
93
94   virtual void FinishImpl();
95
96   /// @}
97 };
98
99 } // end anonymous namespace.
100
101 void MCMachOStreamer::InitSections() {
102   SwitchSection(getContext().getMachOSection("__TEXT", "__text",
103                                     MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
104                                     0, SectionKind::getText()));
105
106 }
107
108 void MCMachOStreamer::EmitEHSymAttributes(const MCSymbol *Symbol,
109                                           MCSymbol *EHSymbol) {
110   MCSymbolData &SD =
111     getAssembler().getOrCreateSymbolData(*Symbol);
112   if (SD.isExternal())
113     EmitSymbolAttribute(EHSymbol, MCSA_Global);
114   if (SD.getFlags() & SF_WeakDefinition)
115     EmitSymbolAttribute(EHSymbol, MCSA_WeakDefinition);
116   if (SD.isPrivateExtern())
117     EmitSymbolAttribute(EHSymbol, MCSA_PrivateExtern);
118 }
119
120 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
121   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
122
123   // isSymbolLinkerVisible uses the section.
124   Symbol->setSection(*getCurrentSection());
125   // We have to create a new fragment if this is an atom defining symbol,
126   // fragments cannot span atoms.
127   if (getAssembler().isSymbolLinkerVisible(*Symbol))
128     new MCDataFragment(getCurrentSectionData());
129
130   MCObjectStreamer::EmitLabel(Symbol);
131
132   MCSymbolData &SD = getAssembler().getSymbolData(*Symbol);
133   // This causes the reference type flag to be cleared. Darwin 'as' was "trying"
134   // to clear the weak reference and weak definition bits too, but the
135   // implementation was buggy. For now we just try to match 'as', for
136   // diffability.
137   //
138   // FIXME: Cleanup this code, these bits should be emitted based on semantic
139   // properties, not on the order of definition, etc.
140   SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeMask);
141 }
142
143 void MCMachOStreamer::EmitDataRegion(DataRegionData::KindTy Kind) {
144   // Create a temporary label to mark the start of the data region.
145   MCSymbol *Start = getContext().CreateTempSymbol();
146   EmitLabel(Start);
147   // Record the region for the object writer to use.
148   DataRegionData Data = { Kind, Start, NULL };
149   std::vector<DataRegionData> &Regions = getAssembler().getDataRegions();
150   Regions.push_back(Data);
151 }
152
153 void MCMachOStreamer::EmitDataRegionEnd() {
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::EmitDataRegion(MCDataRegionType Kind) {
179   switch (Kind) {
180   case MCDR_DataRegion:
181     EmitDataRegion(DataRegionData::Data);
182     return;
183   case MCDR_DataRegionJT8:
184     EmitDataRegion(DataRegionData::JumpTable8);
185     return;
186   case MCDR_DataRegionJT16:
187     EmitDataRegion(DataRegionData::JumpTable16);
188     return;
189   case MCDR_DataRegionJT32:
190     EmitDataRegion(DataRegionData::JumpTable32);
191     return;
192   case MCDR_DataRegionEnd:
193     EmitDataRegionEnd();
194     return;
195   }
196 }
197
198 void MCMachOStreamer::EmitThumbFunc(MCSymbol *Symbol) {
199   // Remember that the function is a thumb function. Fixup and relocation
200   // values will need adjusted.
201   getAssembler().setIsThumbFunc(Symbol);
202
203   // Mark the thumb bit on the symbol.
204   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
205   SD.setFlags(SD.getFlags() | SF_ThumbFunc);
206 }
207
208 void MCMachOStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
209   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
210   // MCObjectStreamer.
211   // FIXME: Lift context changes into super class.
212   getAssembler().getOrCreateSymbolData(*Symbol);
213   Symbol->setVariableValue(AddValueSymbols(Value));
214 }
215
216 void MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
217                                           MCSymbolAttr Attribute) {
218   // Indirect symbols are handled differently, to match how 'as' handles
219   // them. This makes writing matching .o files easier.
220   if (Attribute == MCSA_IndirectSymbol) {
221     // Note that we intentionally cannot use the symbol data here; this is
222     // important for matching the string table that 'as' generates.
223     IndirectSymbolData ISD;
224     ISD.Symbol = Symbol;
225     ISD.SectionData = getCurrentSectionData();
226     getAssembler().getIndirectSymbols().push_back(ISD);
227     return;
228   }
229
230   // Adding a symbol attribute always introduces the symbol, note that an
231   // important side effect of calling getOrCreateSymbolData here is to register
232   // the symbol with the assembler.
233   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
234
235   // The implementation of symbol attributes is designed to match 'as', but it
236   // leaves much to desired. It doesn't really make sense to arbitrarily add and
237   // remove flags, but 'as' allows this (in particular, see .desc).
238   //
239   // In the future it might be worth trying to make these operations more well
240   // defined.
241   switch (Attribute) {
242   case MCSA_Invalid:
243   case MCSA_ELF_TypeFunction:
244   case MCSA_ELF_TypeIndFunction:
245   case MCSA_ELF_TypeObject:
246   case MCSA_ELF_TypeTLS:
247   case MCSA_ELF_TypeCommon:
248   case MCSA_ELF_TypeNoType:
249   case MCSA_ELF_TypeGnuUniqueObject:
250   case MCSA_Hidden:
251   case MCSA_IndirectSymbol:
252   case MCSA_Internal:
253   case MCSA_Protected:
254   case MCSA_Weak:
255   case MCSA_Local:
256     llvm_unreachable("Invalid symbol attribute for Mach-O!");
257
258   case MCSA_Global:
259     SD.setExternal(true);
260     // This effectively clears the undefined lazy bit, in Darwin 'as', although
261     // it isn't very consistent because it implements this as part of symbol
262     // lookup.
263     //
264     // FIXME: Cleanup this code, these bits should be emitted based on semantic
265     // properties, not on the order of definition, etc.
266     SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeUndefinedLazy);
267     break;
268
269   case MCSA_LazyReference:
270     // FIXME: This requires -dynamic.
271     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
272     if (Symbol->isUndefined())
273       SD.setFlags(SD.getFlags() | SF_ReferenceTypeUndefinedLazy);
274     break;
275
276     // Since .reference sets the no dead strip bit, it is equivalent to
277     // .no_dead_strip in practice.
278   case MCSA_Reference:
279   case MCSA_NoDeadStrip:
280     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
281     break;
282
283   case MCSA_SymbolResolver:
284     SD.setFlags(SD.getFlags() | SF_SymbolResolver);
285     break;
286
287   case MCSA_PrivateExtern:
288     SD.setExternal(true);
289     SD.setPrivateExtern(true);
290     break;
291
292   case MCSA_WeakReference:
293     // FIXME: This requires -dynamic.
294     if (Symbol->isUndefined())
295       SD.setFlags(SD.getFlags() | SF_WeakReference);
296     break;
297
298   case MCSA_WeakDefinition:
299     // FIXME: 'as' enforces that this is defined and global. The manual claims
300     // it has to be in a coalesced section, but this isn't enforced.
301     SD.setFlags(SD.getFlags() | SF_WeakDefinition);
302     break;
303
304   case MCSA_WeakDefAutoPrivate:
305     SD.setFlags(SD.getFlags() | SF_WeakDefinition | SF_WeakReference);
306     break;
307   }
308 }
309
310 void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
311   // Encode the 'desc' value into the lowest implementation defined bits.
312   assert(DescValue == (DescValue & SF_DescFlagsMask) &&
313          "Invalid .desc value!");
314   getAssembler().getOrCreateSymbolData(*Symbol).setFlags(
315     DescValue & SF_DescFlagsMask);
316 }
317
318 void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
319                                        unsigned ByteAlignment) {
320   // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
321   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
322
323   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
324   SD.setExternal(true);
325   SD.setCommon(Size, ByteAlignment);
326 }
327
328 void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
329                                    unsigned Size, unsigned ByteAlignment) {
330   MCSectionData &SectData = getAssembler().getOrCreateSectionData(*Section);
331
332   // The symbol may not be present, which only creates the section.
333   if (!Symbol)
334     return;
335
336   // FIXME: Assert that this section has the zerofill type.
337
338   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
339
340   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
341
342   // Emit an align fragment if necessary.
343   if (ByteAlignment != 1)
344     new MCAlignFragment(ByteAlignment, 0, 0, ByteAlignment, &SectData);
345
346   MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
347   SD.setFragment(F);
348
349   Symbol->setSection(*Section);
350
351   // Update the maximum alignment on the zero fill section if necessary.
352   if (ByteAlignment > SectData.getAlignment())
353     SectData.setAlignment(ByteAlignment);
354 }
355
356 // This should always be called with the thread local bss section.  Like the
357 // .zerofill directive this doesn't actually switch sections on us.
358 void MCMachOStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
359                                      uint64_t Size, unsigned ByteAlignment) {
360   EmitZerofill(Section, Symbol, Size, ByteAlignment);
361   return;
362 }
363
364 void MCMachOStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
365   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
366   // MCObjectStreamer.
367   getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
368 }
369
370 void MCMachOStreamer::EmitValueToAlignment(unsigned ByteAlignment,
371                                            int64_t Value, unsigned ValueSize,
372                                            unsigned MaxBytesToEmit) {
373   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
374   // MCObjectStreamer.
375   if (MaxBytesToEmit == 0)
376     MaxBytesToEmit = ByteAlignment;
377   new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
378                       getCurrentSectionData());
379
380   // Update the maximum alignment on the current section if necessary.
381   if (ByteAlignment > getCurrentSectionData()->getAlignment())
382     getCurrentSectionData()->setAlignment(ByteAlignment);
383 }
384
385 void MCMachOStreamer::EmitCodeAlignment(unsigned ByteAlignment,
386                                         unsigned MaxBytesToEmit) {
387   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
388   // MCObjectStreamer.
389   if (MaxBytesToEmit == 0)
390     MaxBytesToEmit = ByteAlignment;
391   MCAlignFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
392                                            getCurrentSectionData());
393   F->setEmitNops(true);
394
395   // Update the maximum alignment on the current section if necessary.
396   if (ByteAlignment > getCurrentSectionData()->getAlignment())
397     getCurrentSectionData()->setAlignment(ByteAlignment);
398 }
399
400 void MCMachOStreamer::EmitInstToData(const MCInst &Inst) {
401   MCDataFragment *DF = getOrCreateDataFragment();
402
403   SmallVector<MCFixup, 4> Fixups;
404   SmallString<256> Code;
405   raw_svector_ostream VecOS(Code);
406   getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
407   VecOS.flush();
408
409   // Add the fixups and data.
410   for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
411     Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
412     DF->addFixup(Fixups[i]);
413   }
414   DF->getContents().append(Code.begin(), Code.end());
415 }
416
417 void MCMachOStreamer::FinishImpl() {
418   EmitFrames(true);
419
420   // We have to set the fragment atom associations so we can relax properly for
421   // Mach-O.
422
423   // First, scan the symbol table to build a lookup table from fragments to
424   // defining symbols.
425   DenseMap<const MCFragment*, MCSymbolData*> DefiningSymbolMap;
426   for (MCAssembler::symbol_iterator it = getAssembler().symbol_begin(),
427          ie = getAssembler().symbol_end(); it != ie; ++it) {
428     if (getAssembler().isSymbolLinkerVisible(it->getSymbol()) &&
429         it->getFragment()) {
430       // An atom defining symbol should never be internal to a fragment.
431       assert(it->getOffset() == 0 && "Invalid offset in atom defining symbol!");
432       DefiningSymbolMap[it->getFragment()] = it;
433     }
434   }
435
436   // Set the fragment atom associations by tracking the last seen atom defining
437   // symbol.
438   for (MCAssembler::iterator it = getAssembler().begin(),
439          ie = getAssembler().end(); it != ie; ++it) {
440     MCSymbolData *CurrentAtom = 0;
441     for (MCSectionData::iterator it2 = it->begin(),
442            ie2 = it->end(); it2 != ie2; ++it2) {
443       if (MCSymbolData *SD = DefiningSymbolMap.lookup(it2))
444         CurrentAtom = SD;
445       it2->setAtom(CurrentAtom);
446     }
447   }
448
449   this->MCObjectStreamer::FinishImpl();
450 }
451
452 MCStreamer *llvm::createMachOStreamer(MCContext &Context, MCAsmBackend &MAB,
453                                       raw_ostream &OS, MCCodeEmitter *CE,
454                                       bool RelaxAll) {
455   MCMachOStreamer *S = new MCMachOStreamer(Context, MAB, OS, CE);
456   if (RelaxAll)
457     S->getAssembler().setRelaxAll(true);
458   return S;
459 }