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