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