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