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