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