Enable DebugInfo support for COFF object files.
[oota-llvm.git] / lib / MC / MCELFStreamer.cpp
1 //===- lib/MC/MCELFStreamer.cpp - ELF 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 // This file assembles .s files and emits ELF .o object files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/MC/MCStreamer.h"
15
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/MC/MCAssembler.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCCodeEmitter.h"
20 #include "llvm/MC/MCELFSymbolFlags.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCInst.h"
23 #include "llvm/MC/MCObjectStreamer.h"
24 #include "llvm/MC/MCSection.h"
25 #include "llvm/MC/MCSectionELF.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/MC/MCValue.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ELF.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Target/TargetAsmBackend.h"
33 #include "llvm/Target/TargetAsmInfo.h"
34
35 using namespace llvm;
36
37 namespace {
38
39 static void SetBinding(MCSymbolData &SD, unsigned Binding) {
40   assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
41          Binding == ELF::STB_WEAK);
42   uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STB_Shift);
43   SD.setFlags(OtherFlags | (Binding << ELF_STB_Shift));
44 }
45
46 static unsigned GetBinding(const MCSymbolData &SD) {
47   uint32_t Binding = (SD.getFlags() & (0xf << ELF_STB_Shift)) >> ELF_STB_Shift;
48   assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
49          Binding == ELF::STB_WEAK);
50   return Binding;
51 }
52
53 static void SetType(MCSymbolData &SD, unsigned Type) {
54   assert(Type == ELF::STT_NOTYPE || Type == ELF::STT_OBJECT ||
55          Type == ELF::STT_FUNC || Type == ELF::STT_SECTION ||
56          Type == ELF::STT_FILE || Type == ELF::STT_COMMON ||
57          Type == ELF::STT_TLS);
58
59   uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STT_Shift);
60   SD.setFlags(OtherFlags | (Type << ELF_STT_Shift));
61 }
62
63 static void SetVisibility(MCSymbolData &SD, unsigned Visibility) {
64   assert(Visibility == ELF::STV_DEFAULT || Visibility == ELF::STV_INTERNAL ||
65          Visibility == ELF::STV_HIDDEN || Visibility == ELF::STV_PROTECTED);
66
67   uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STV_Shift);
68   SD.setFlags(OtherFlags | (Visibility << ELF_STV_Shift));
69 }
70
71 class MCELFStreamer : public MCObjectStreamer {
72 public:
73   MCELFStreamer(MCContext &Context, TargetAsmBackend &TAB,
74                   raw_ostream &OS, MCCodeEmitter *Emitter)
75     : MCObjectStreamer(Context, TAB, OS, Emitter) {}
76
77   ~MCELFStreamer() {}
78
79   /// @name MCStreamer Interface
80   /// @{
81
82   virtual void InitSections();
83   virtual void ChangeSection(const MCSection *Section);
84   virtual void EmitLabel(MCSymbol *Symbol);
85   virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
86   virtual void EmitThumbFunc(MCSymbol *Func);
87   virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
88   virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol);
89   virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
90   virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
91     assert(0 && "ELF doesn't support this directive");
92   }
93   virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
94                                 unsigned ByteAlignment);
95   virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {
96     assert(0 && "ELF doesn't support this directive");
97   }
98
99   virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
100     assert(0 && "ELF doesn't support this directive");
101   }
102
103   virtual void EmitCOFFSymbolType(int Type) {
104     assert(0 && "ELF doesn't support this directive");
105   }
106
107   virtual void EndCOFFSymbolDef() {
108     assert(0 && "ELF doesn't support this directive");
109   }
110
111   virtual void EmitCOFFSecRel32(MCSymbol const *Symbol) {
112     assert(0 && "ELF doesn't support this directive");
113   }
114
115   virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
116      MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
117      SD.setSize(Value);
118   }
119
120   virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size);
121
122   virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
123                             unsigned Size = 0, unsigned ByteAlignment = 0) {
124     assert(0 && "ELF doesn't support this directive");
125   }
126   virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
127                               uint64_t Size, unsigned ByteAlignment = 0) {
128     assert(0 && "ELF doesn't support this directive");
129   }
130   virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
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
137   virtual void EmitFileDirective(StringRef Filename);
138
139   virtual void Finish();
140
141 private:
142   virtual void EmitInstToFragment(const MCInst &Inst);
143   virtual void EmitInstToData(const MCInst &Inst);
144
145   void fixSymbolsInTLSFixups(const MCExpr *expr);
146
147   struct LocalCommon {
148     MCSymbolData *SD;
149     uint64_t Size;
150     unsigned ByteAlignment;
151   };
152   std::vector<LocalCommon> LocalCommons;
153
154   SmallPtrSet<MCSymbol *, 16> BindingExplicitlySet;
155   /// @}
156   void SetSection(StringRef Section, unsigned Type, unsigned Flags,
157                   SectionKind Kind) {
158     SwitchSection(getContext().getELFSection(Section, Type, Flags, Kind));
159   }
160
161   void SetSectionData() {
162     SetSection(".data", ELF::SHT_PROGBITS,
163                ELF::SHF_WRITE |ELF::SHF_ALLOC,
164                SectionKind::getDataRel());
165     EmitCodeAlignment(4, 0);
166   }
167   void SetSectionText() {
168     SetSection(".text", ELF::SHT_PROGBITS,
169                ELF::SHF_EXECINSTR |
170                ELF::SHF_ALLOC, SectionKind::getText());
171     EmitCodeAlignment(4, 0);
172   }
173   void SetSectionBss() {
174     SetSection(".bss", ELF::SHT_NOBITS,
175                ELF::SHF_WRITE |
176                ELF::SHF_ALLOC, SectionKind::getBSS());
177     EmitCodeAlignment(4, 0);
178   }
179 };
180
181 } // end anonymous namespace.
182
183 void MCELFStreamer::InitSections() {
184   // This emulates the same behavior of GNU as. This makes it easier
185   // to compare the output as the major sections are in the same order.
186   SetSectionText();
187   SetSectionData();
188   SetSectionBss();
189   SetSectionText();
190 }
191
192 void MCELFStreamer::EmitLabel(MCSymbol *Symbol) {
193   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
194
195   MCObjectStreamer::EmitLabel(Symbol);
196
197   const MCSectionELF &Section =
198     static_cast<const MCSectionELF&>(Symbol->getSection());
199   MCSymbolData &SD = getAssembler().getSymbolData(*Symbol);
200   if (Section.getFlags() & ELF::SHF_TLS)
201     SetType(SD, ELF::STT_TLS);
202 }
203
204 void MCELFStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
205   switch (Flag) {
206   case MCAF_SyntaxUnified: return; // no-op here.
207   case MCAF_Code16: return; // no-op here.
208   case MCAF_Code32: return; // no-op here.
209   case MCAF_SubsectionsViaSymbols:
210     getAssembler().setSubsectionsViaSymbols(true);
211     return;
212   }
213
214   assert(0 && "invalid assembler flag!");
215 }
216
217 void MCELFStreamer::EmitThumbFunc(MCSymbol *Func) {
218   // FIXME: Anything needed here to flag the function as thumb?
219 }
220
221 void MCELFStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
222   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
223   // MCObjectStreamer.
224   // FIXME: Lift context changes into super class.
225   getAssembler().getOrCreateSymbolData(*Symbol);
226   Symbol->setVariableValue(AddValueSymbols(Value));
227 }
228
229 void MCELFStreamer::ChangeSection(const MCSection *Section) {
230   const MCSymbol *Grp = static_cast<const MCSectionELF *>(Section)->getGroup();
231   if (Grp)
232     getAssembler().getOrCreateSymbolData(*Grp);
233   this->MCObjectStreamer::ChangeSection(Section);
234 }
235
236 void MCELFStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
237   getAssembler().getOrCreateSymbolData(*Symbol);
238   MCSymbolData &AliasSD = getAssembler().getOrCreateSymbolData(*Alias);
239   AliasSD.setFlags(AliasSD.getFlags() | ELF_Other_Weakref);
240   const MCExpr *Value = MCSymbolRefExpr::Create(Symbol, getContext());
241   Alias->setVariableValue(Value);
242 }
243
244 void MCELFStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
245                                           MCSymbolAttr Attribute) {
246   // Indirect symbols are handled differently, to match how 'as' handles
247   // them. This makes writing matching .o files easier.
248   if (Attribute == MCSA_IndirectSymbol) {
249     // Note that we intentionally cannot use the symbol data here; this is
250     // important for matching the string table that 'as' generates.
251     IndirectSymbolData ISD;
252     ISD.Symbol = Symbol;
253     ISD.SectionData = getCurrentSectionData();
254     getAssembler().getIndirectSymbols().push_back(ISD);
255     return;
256   }
257
258   // Adding a symbol attribute always introduces the symbol, note that an
259   // important side effect of calling getOrCreateSymbolData here is to register
260   // the symbol with the assembler.
261   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
262
263   // The implementation of symbol attributes is designed to match 'as', but it
264   // leaves much to desired. It doesn't really make sense to arbitrarily add and
265   // remove flags, but 'as' allows this (in particular, see .desc).
266   //
267   // In the future it might be worth trying to make these operations more well
268   // defined.
269   switch (Attribute) {
270   case MCSA_LazyReference:
271   case MCSA_Reference:
272   case MCSA_NoDeadStrip:
273   case MCSA_SymbolResolver:
274   case MCSA_PrivateExtern:
275   case MCSA_WeakDefinition:
276   case MCSA_WeakDefAutoPrivate:
277   case MCSA_Invalid:
278   case MCSA_ELF_TypeIndFunction:
279   case MCSA_IndirectSymbol:
280     assert(0 && "Invalid symbol attribute for ELF!");
281     break;
282
283   case MCSA_ELF_TypeGnuUniqueObject:
284     // Ignore for now.
285     break;
286
287   case MCSA_Global:
288     SetBinding(SD, ELF::STB_GLOBAL);
289     SD.setExternal(true);
290     BindingExplicitlySet.insert(Symbol);
291     break;
292
293   case MCSA_WeakReference:
294   case MCSA_Weak:
295     SetBinding(SD, ELF::STB_WEAK);
296     SD.setExternal(true);
297     BindingExplicitlySet.insert(Symbol);
298     break;
299
300   case MCSA_Local:
301     SetBinding(SD, ELF::STB_LOCAL);
302     SD.setExternal(false);
303     BindingExplicitlySet.insert(Symbol);
304     break;
305
306   case MCSA_ELF_TypeFunction:
307     SetType(SD, ELF::STT_FUNC);
308     break;
309
310   case MCSA_ELF_TypeObject:
311     SetType(SD, ELF::STT_OBJECT);
312     break;
313
314   case MCSA_ELF_TypeTLS:
315     SetType(SD, ELF::STT_TLS);
316     break;
317
318   case MCSA_ELF_TypeCommon:
319     SetType(SD, ELF::STT_COMMON);
320     break;
321
322   case MCSA_ELF_TypeNoType:
323     SetType(SD, ELF::STT_NOTYPE);
324     break;
325
326   case MCSA_Protected:
327     SetVisibility(SD, ELF::STV_PROTECTED);
328     break;
329
330   case MCSA_Hidden:
331     SetVisibility(SD, ELF::STV_HIDDEN);
332     break;
333
334   case MCSA_Internal:
335     SetVisibility(SD, ELF::STV_INTERNAL);
336     break;
337   }
338 }
339
340 void MCELFStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
341                                        unsigned ByteAlignment) {
342   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
343
344   if (!BindingExplicitlySet.count(Symbol)) {
345     SetBinding(SD, ELF::STB_GLOBAL);
346     SD.setExternal(true);
347   }
348
349   SetType(SD, ELF::STT_OBJECT);
350
351   if (GetBinding(SD) == ELF_STB_Local) {
352     const MCSection *Section = getAssembler().getContext().getELFSection(".bss",
353                                                                     ELF::SHT_NOBITS,
354                                                                     ELF::SHF_WRITE |
355                                                                     ELF::SHF_ALLOC,
356                                                                     SectionKind::getBSS());
357     Symbol->setSection(*Section);
358
359     struct LocalCommon L = {&SD, Size, ByteAlignment};
360     LocalCommons.push_back(L);
361   } else {
362     SD.setCommon(Size, ByteAlignment);
363   }
364
365   SD.setSize(MCConstantExpr::Create(Size, getContext()));
366 }
367
368 void MCELFStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
369   // FIXME: Should this be caught and done earlier?
370   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
371   SetBinding(SD, ELF::STB_LOCAL);
372   SD.setExternal(false);
373   BindingExplicitlySet.insert(Symbol);
374   // FIXME: ByteAlignment is not needed here, but is required.
375   EmitCommonSymbol(Symbol, Size, 1);
376 }
377
378 void MCELFStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
379   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
380   // MCObjectStreamer.
381   getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
382 }
383
384 void MCELFStreamer::EmitValueToAlignment(unsigned ByteAlignment,
385                                            int64_t Value, unsigned ValueSize,
386                                            unsigned MaxBytesToEmit) {
387   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
388   // MCObjectStreamer.
389   if (MaxBytesToEmit == 0)
390     MaxBytesToEmit = ByteAlignment;
391   new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
392                       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 MCELFStreamer::EmitCodeAlignment(unsigned ByteAlignment,
400                                         unsigned MaxBytesToEmit) {
401   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
402   // MCObjectStreamer.
403   if (MaxBytesToEmit == 0)
404     MaxBytesToEmit = ByteAlignment;
405   MCAlignFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
406                                            getCurrentSectionData());
407   F->setEmitNops(true);
408
409   // Update the maximum alignment on the current section if necessary.
410   if (ByteAlignment > getCurrentSectionData()->getAlignment())
411     getCurrentSectionData()->setAlignment(ByteAlignment);
412 }
413
414 // Add a symbol for the file name of this module. This is the second
415 // entry in the module's symbol table (the first being the null symbol).
416 void MCELFStreamer::EmitFileDirective(StringRef Filename) {
417   MCSymbol *Symbol = getAssembler().getContext().GetOrCreateSymbol(Filename);
418   Symbol->setSection(*getCurrentSection());
419   Symbol->setAbsolute();
420
421   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
422
423   SD.setFlags(ELF_STT_File | ELF_STB_Local | ELF_STV_Default);
424 }
425
426 void  MCELFStreamer::fixSymbolsInTLSFixups(const MCExpr *expr) {
427   switch (expr->getKind()) {
428   case MCExpr::Target: llvm_unreachable("Can't handle target exprs yet!");
429   case MCExpr::Constant:
430     break;
431
432   case MCExpr::Binary: {
433     const MCBinaryExpr *be = cast<MCBinaryExpr>(expr);
434     fixSymbolsInTLSFixups(be->getLHS());
435     fixSymbolsInTLSFixups(be->getRHS());
436     break;
437   }
438
439   case MCExpr::SymbolRef: {
440     const MCSymbolRefExpr &symRef = *cast<MCSymbolRefExpr>(expr);
441     switch (symRef.getKind()) {
442     default:
443       return;
444     case MCSymbolRefExpr::VK_NTPOFF:
445     case MCSymbolRefExpr::VK_GOTNTPOFF:
446     case MCSymbolRefExpr::VK_TLSGD:
447     case MCSymbolRefExpr::VK_TLSLDM:
448     case MCSymbolRefExpr::VK_TPOFF:
449     case MCSymbolRefExpr::VK_DTPOFF:
450     case MCSymbolRefExpr::VK_GOTTPOFF:
451     case MCSymbolRefExpr::VK_TLSLD:
452     case MCSymbolRefExpr::VK_ARM_TLSGD:
453       break;
454     }
455     MCSymbolData &SD = getAssembler().getOrCreateSymbolData(symRef.getSymbol());
456     SetType(SD, ELF::STT_TLS);
457     break;
458   }
459
460   case MCExpr::Unary:
461     fixSymbolsInTLSFixups(cast<MCUnaryExpr>(expr)->getSubExpr());
462     break;
463   }
464 }
465
466 void MCELFStreamer::EmitInstToFragment(const MCInst &Inst) {
467   this->MCObjectStreamer::EmitInstToFragment(Inst);
468   MCInstFragment &F = *cast<MCInstFragment>(getCurrentFragment());
469
470   for (unsigned i = 0, e = F.getFixups().size(); i != e; ++i)
471     fixSymbolsInTLSFixups(F.getFixups()[i].getValue());
472 }
473
474 void MCELFStreamer::EmitInstToData(const MCInst &Inst) {
475   MCDataFragment *DF = getOrCreateDataFragment();
476
477   SmallVector<MCFixup, 4> Fixups;
478   SmallString<256> Code;
479   raw_svector_ostream VecOS(Code);
480   getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
481   VecOS.flush();
482
483   for (unsigned i = 0, e = Fixups.size(); i != e; ++i)
484     fixSymbolsInTLSFixups(Fixups[i].getValue());
485
486   // Add the fixups and data.
487   for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
488     Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
489     DF->addFixup(Fixups[i]);
490   }
491   DF->getContents().append(Code.begin(), Code.end());
492 }
493
494 void MCELFStreamer::Finish() {
495   if (getNumFrameInfos())
496     MCDwarfFrameEmitter::Emit(*this);
497
498   for (std::vector<LocalCommon>::const_iterator i = LocalCommons.begin(),
499                                                 e = LocalCommons.end();
500        i != e; ++i) {
501     MCSymbolData *SD = i->SD;
502     uint64_t Size = i->Size;
503     unsigned ByteAlignment = i->ByteAlignment;
504     const MCSymbol &Symbol = SD->getSymbol();
505     const MCSection &Section = Symbol.getSection();
506
507     MCSectionData &SectData = getAssembler().getOrCreateSectionData(Section);
508     new MCAlignFragment(ByteAlignment, 0, 1, ByteAlignment, &SectData);
509
510     MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
511     SD->setFragment(F);
512
513     // Update the maximum alignment of the section if necessary.
514     if (ByteAlignment > SectData.getAlignment())
515       SectData.setAlignment(ByteAlignment);
516   }
517
518   this->MCObjectStreamer::Finish();
519 }
520
521 MCStreamer *llvm::createELFStreamer(MCContext &Context, TargetAsmBackend &TAB,
522                                     raw_ostream &OS, MCCodeEmitter *CE,
523                                     bool RelaxAll, bool NoExecStack) {
524   MCELFStreamer *S = new MCELFStreamer(Context, TAB, OS, CE);
525   if (RelaxAll)
526     S->getAssembler().setRelaxAll(true);
527   if (NoExecStack)
528     S->getAssembler().setNoExecStack(true);
529   return S;
530 }