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