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