ecc72c26b701e7896056a11fd0a2a47f3a923689
[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/Support/Debug.h"
28 #include "llvm/Support/ELF.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Target/TargetAsmBackend.h"
32
33 using namespace llvm;
34
35 namespace {
36
37 class MCELFStreamer : public MCObjectStreamer {
38   void EmitInstToFragment(const MCInst &Inst);
39   void EmitInstToData(const MCInst &Inst);
40 public:
41   MCELFStreamer(MCContext &Context, TargetAsmBackend &TAB,
42                   raw_ostream &OS, MCCodeEmitter *Emitter)
43     : MCObjectStreamer(Context, TAB, OS, Emitter, false) {}
44
45   ~MCELFStreamer() {}
46
47   /// @name MCStreamer Interface
48   /// @{
49
50   virtual void InitSections();
51   virtual void EmitLabel(MCSymbol *Symbol);
52   virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
53   virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
54   virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
55   virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
56     assert(0 && "ELF doesn't support this directive");
57   }
58   virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
59                                 unsigned ByteAlignment);
60   virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {
61     assert(0 && "ELF doesn't support this directive");
62   }
63
64   virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
65     assert(0 && "ELF doesn't support this directive");
66   }
67
68   virtual void EmitCOFFSymbolType(int Type) {
69     assert(0 && "ELF doesn't support this directive");
70   }
71
72   virtual void EndCOFFSymbolDef() {
73     assert(0 && "ELF doesn't support this directive");
74   }
75
76   virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
77      MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
78      SD.setSize(Value);
79   }
80
81   virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
82     assert(0 && "ELF doesn't support this directive");
83   }
84   virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
85                             unsigned Size = 0, unsigned ByteAlignment = 0) {
86     assert(0 && "ELF doesn't support this directive");
87   }
88   virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
89                               uint64_t Size, unsigned ByteAlignment = 0) {
90     assert(0 && "ELF doesn't support this directive");
91   }
92   virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
93   virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
94   virtual void EmitGPRel32Value(const MCExpr *Value) {
95     assert(0 && "ELF doesn't support this directive");
96   }
97   virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
98                                     unsigned ValueSize = 1,
99                                     unsigned MaxBytesToEmit = 0);
100   virtual void EmitCodeAlignment(unsigned ByteAlignment,
101                                  unsigned MaxBytesToEmit = 0);
102   virtual void EmitValueToOffset(const MCExpr *Offset,
103                                  unsigned char Value = 0);
104
105   virtual void EmitFileDirective(StringRef Filename);
106   virtual void EmitDwarfFileDirective(unsigned FileNo, StringRef Filename) {
107     DEBUG(dbgs() << "FIXME: MCELFStreamer:EmitDwarfFileDirective not implemented\n");
108   }
109
110   virtual void EmitInstruction(const MCInst &Inst);
111   virtual void Finish();
112
113 private:
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", MCSectionELF::SHT_PROGBITS,
130                MCSectionELF::SHF_WRITE |MCSectionELF::SHF_ALLOC,
131                SectionKind::getDataRel());
132     EmitCodeAlignment(4, 0);
133   }
134   void SetSectionText() {
135     SetSection(".text", MCSectionELF::SHT_PROGBITS,
136                MCSectionELF::SHF_EXECINSTR |
137                MCSectionELF::SHF_ALLOC, SectionKind::getText());
138     EmitCodeAlignment(4, 0);
139   }
140   void SetSectionBss() {
141     SetSection(".bss", MCSectionELF::SHT_NOBITS,
142                MCSectionELF::SHF_WRITE |
143                MCSectionELF::SHF_ALLOC, SectionKind::getBSS());
144     EmitCodeAlignment(4, 0);
145   }
146 };
147
148 } // end anonymous namespace.
149
150 void MCELFStreamer::InitSections() {
151   // This emulates the same behavior of GNU as. This makes it easier
152   // to compare the output as the major sections are in the same order.
153   SetSectionText();
154   SetSectionData();
155   SetSectionBss();
156   SetSectionText();
157 }
158
159 static bool isSymbolLinkerVisible(const MCAssembler &Asm,
160                                   const MCSymbolData &Data) {
161   const MCSymbol &Symbol = Data.getSymbol();
162   // Absolute temporary labels are never visible.
163   if (!Symbol.isInSection())
164     return false;
165
166   if (Asm.getBackend().doesSectionRequireSymbols(Symbol.getSection()))
167     return true;
168
169   if (!Data.isExternal())
170     return false;
171
172   return Asm.isSymbolLinkerVisible(Symbol);
173 }
174
175 void MCELFStreamer::EmitLabel(MCSymbol *Symbol) {
176   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
177
178   Symbol->setSection(*CurSection);
179
180   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
181
182   // We have to create a new fragment if this is an atom defining symbol,
183   // fragments cannot span atoms.
184   if (isSymbolLinkerVisible(getAssembler(), SD))
185     new MCDataFragment(getCurrentSectionData());
186
187   // FIXME: This is wasteful, we don't necessarily need to create a data
188   // fragment. Instead, we should mark the symbol as pointing into the data
189   // fragment if it exists, otherwise we should just queue the label and set its
190   // fragment pointer when we emit the next fragment.
191   MCDataFragment *F = getOrCreateDataFragment();
192
193   assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
194   SD.setFragment(F);
195   SD.setOffset(F->getContents().size());
196 }
197
198 void MCELFStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
199   switch (Flag) {
200   case MCAF_SyntaxUnified:  return; // no-op here?
201   case MCAF_SubsectionsViaSymbols:
202     getAssembler().setSubsectionsViaSymbols(true);
203     return;
204   }
205
206   assert(0 && "invalid assembler flag!");
207 }
208
209 void MCELFStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
210   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
211   // MCObjectStreamer.
212   // FIXME: Lift context changes into super class.
213   getAssembler().getOrCreateSymbolData(*Symbol);
214   Symbol->setVariableValue(AddValueSymbols(Value));
215 }
216
217 static void SetBinding(MCSymbolData &SD, unsigned Binding) {
218   assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
219          Binding == ELF::STB_WEAK);
220   uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STB_Shift);
221   SD.setFlags(OtherFlags | (Binding << ELF_STB_Shift));
222 }
223
224 static unsigned GetBinding(const MCSymbolData &SD) {
225   uint32_t Binding = (SD.getFlags() & (0xf << ELF_STB_Shift)) >> ELF_STB_Shift;
226   assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
227          Binding == ELF::STB_WEAK);
228   return Binding;
229 }
230
231 static void SetType(MCSymbolData &SD, unsigned Type) {
232   assert(Type == ELF::STT_NOTYPE || Type == ELF::STT_OBJECT ||
233          Type == ELF::STT_FUNC || Type == ELF::STT_SECTION ||
234          Type == ELF::STT_FILE || Type == ELF::STT_COMMON ||
235          Type == ELF::STT_TLS);
236
237   uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STT_Shift);
238   SD.setFlags(OtherFlags | (Type << ELF_STT_Shift));
239 }
240
241 static void SetVisibility(MCSymbolData &SD, unsigned Visibility) {
242   assert(Visibility == ELF::STV_DEFAULT || Visibility == ELF::STV_INTERNAL ||
243          Visibility == ELF::STV_HIDDEN || Visibility == ELF::STV_PROTECTED);
244
245   uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STV_Shift);
246   SD.setFlags(OtherFlags | (Visibility << ELF_STV_Shift));
247 }
248
249 void MCELFStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
250                                           MCSymbolAttr Attribute) {
251   // Indirect symbols are handled differently, to match how 'as' handles
252   // them. This makes writing matching .o files easier.
253   if (Attribute == MCSA_IndirectSymbol) {
254     // Note that we intentionally cannot use the symbol data here; this is
255     // important for matching the string table that 'as' generates.
256     IndirectSymbolData ISD;
257     ISD.Symbol = Symbol;
258     ISD.SectionData = getCurrentSectionData();
259     getAssembler().getIndirectSymbols().push_back(ISD);
260     return;
261   }
262
263   // Adding a symbol attribute always introduces the symbol, note that an
264   // important side effect of calling getOrCreateSymbolData here is to register
265   // the symbol with the assembler.
266   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
267
268   // The implementation of symbol attributes is designed to match 'as', but it
269   // leaves much to desired. It doesn't really make sense to arbitrarily add and
270   // remove flags, but 'as' allows this (in particular, see .desc).
271   //
272   // In the future it might be worth trying to make these operations more well
273   // defined.
274   switch (Attribute) {
275   case MCSA_LazyReference:
276   case MCSA_Reference:
277   case MCSA_NoDeadStrip:
278   case MCSA_PrivateExtern:
279   case MCSA_WeakDefinition:
280   case MCSA_WeakDefAutoPrivate:
281   case MCSA_Invalid:
282   case MCSA_ELF_TypeIndFunction:
283   case MCSA_IndirectSymbol:
284     assert(0 && "Invalid symbol attribute for ELF!");
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     BindingExplicitlySet.insert(Symbol);
297     break;
298
299   case MCSA_Local:
300     SetBinding(SD, ELF::STB_LOCAL);
301     SD.setExternal(false);
302     BindingExplicitlySet.insert(Symbol);
303     break;
304
305   case MCSA_ELF_TypeFunction:
306     SetType(SD, ELF::STT_FUNC);
307     break;
308
309   case MCSA_ELF_TypeObject:
310     SetType(SD, ELF::STT_OBJECT);
311     break;
312
313   case MCSA_ELF_TypeTLS:
314     SetType(SD, ELF::STT_TLS);
315     break;
316
317   case MCSA_ELF_TypeCommon:
318     SetType(SD, ELF::STT_COMMON);
319     break;
320
321   case MCSA_ELF_TypeNoType:
322     SetType(SD, ELF::STT_NOTYPE);
323     break;
324
325   case MCSA_Protected:
326     SetVisibility(SD, ELF::STV_PROTECTED);
327     break;
328
329   case MCSA_Hidden:
330     SetVisibility(SD, ELF::STV_HIDDEN);
331     break;
332
333   case MCSA_Internal:
334     SetVisibility(SD, ELF::STV_INTERNAL);
335     break;
336   }
337 }
338
339 void MCELFStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
340                                        unsigned ByteAlignment) {
341   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
342
343   if (!BindingExplicitlySet.count(Symbol)) {
344     SetBinding(SD, ELF::STB_GLOBAL);
345     SD.setExternal(true);
346   }
347
348   if (GetBinding(SD) == ELF_STB_Local) {
349     const MCSection *Section = getAssembler().getContext().getELFSection(".bss",
350                                                                     MCSectionELF::SHT_NOBITS,
351                                                                     MCSectionELF::SHF_WRITE |
352                                                                     MCSectionELF::SHF_ALLOC,
353                                                                     SectionKind::getBSS());
354     Symbol->setSection(*Section);
355
356     struct LocalCommon L = {&SD, Size, ByteAlignment};
357     LocalCommons.push_back(L);
358   } else {
359     SD.setCommon(Size, ByteAlignment);
360   }
361
362   SD.setSize(MCConstantExpr::Create(Size, getContext()));
363 }
364
365 void MCELFStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
366   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
367   // MCObjectStreamer.
368   getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
369 }
370
371 void MCELFStreamer::EmitValue(const MCExpr *Value, unsigned Size,
372                                 unsigned AddrSpace) {
373   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
374   // MCObjectStreamer.
375   MCDataFragment *DF = getOrCreateDataFragment();
376
377   // Avoid fixups when possible.
378   int64_t AbsValue;
379   if (AddValueSymbols(Value)->EvaluateAsAbsolute(AbsValue)) {
380     // FIXME: Endianness assumption.
381     for (unsigned i = 0; i != Size; ++i)
382       DF->getContents().push_back(uint8_t(AbsValue >> (i * 8)));
383   } else {
384     DF->addFixup(MCFixup::Create(DF->getContents().size(), AddValueSymbols(Value),
385                                  MCFixup::getKindForSize(Size)));
386     DF->getContents().resize(DF->getContents().size() + Size, 0);
387   }
388 }
389
390 void MCELFStreamer::EmitValueToAlignment(unsigned ByteAlignment,
391                                            int64_t Value, unsigned ValueSize,
392                                            unsigned MaxBytesToEmit) {
393   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
394   // MCObjectStreamer.
395   if (MaxBytesToEmit == 0)
396     MaxBytesToEmit = ByteAlignment;
397   new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
398                       getCurrentSectionData());
399
400   // Update the maximum alignment on the current section if necessary.
401   if (ByteAlignment > getCurrentSectionData()->getAlignment())
402     getCurrentSectionData()->setAlignment(ByteAlignment);
403 }
404
405 void MCELFStreamer::EmitCodeAlignment(unsigned ByteAlignment,
406                                         unsigned MaxBytesToEmit) {
407   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
408   // MCObjectStreamer.
409   if (MaxBytesToEmit == 0)
410     MaxBytesToEmit = ByteAlignment;
411   MCAlignFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
412                                            getCurrentSectionData());
413   F->setEmitNops(true);
414
415   // Update the maximum alignment on the current section if necessary.
416   if (ByteAlignment > getCurrentSectionData()->getAlignment())
417     getCurrentSectionData()->setAlignment(ByteAlignment);
418 }
419
420 void MCELFStreamer::EmitValueToOffset(const MCExpr *Offset,
421                                         unsigned char Value) {
422   // TODO: This is exactly the same as MCMachOStreamer. Consider merging into
423   // MCObjectStreamer.
424   new MCOrgFragment(*Offset, Value, getCurrentSectionData());
425 }
426
427 // Add a symbol for the file name of this module. This is the second
428 // entry in the module's symbol table (the first being the null symbol).
429 void MCELFStreamer::EmitFileDirective(StringRef Filename) {
430   MCSymbol *Symbol = getAssembler().getContext().GetOrCreateSymbol(Filename);
431   Symbol->setSection(*CurSection);
432   Symbol->setAbsolute();
433
434   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
435
436   SD.setFlags(ELF_STT_File | ELF_STB_Local | ELF_STV_Default);
437 }
438
439 void MCELFStreamer::EmitInstToFragment(const MCInst &Inst) {
440   MCInstFragment *IF = new MCInstFragment(Inst, getCurrentSectionData());
441
442   // Add the fixups and data.
443   //
444   // FIXME: Revisit this design decision when relaxation is done, we may be
445   // able to get away with not storing any extra data in the MCInst.
446   SmallVector<MCFixup, 4> Fixups;
447   SmallString<256> Code;
448   raw_svector_ostream VecOS(Code);
449   getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
450   VecOS.flush();
451
452   IF->getCode() = Code;
453   IF->getFixups() = Fixups;
454 }
455
456 void MCELFStreamer::EmitInstToData(const MCInst &Inst) {
457   MCDataFragment *DF = getOrCreateDataFragment();
458
459   SmallVector<MCFixup, 4> Fixups;
460   SmallString<256> Code;
461   raw_svector_ostream VecOS(Code);
462   getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
463   VecOS.flush();
464
465   // Add the fixups and data.
466   for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
467     Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
468     DF->addFixup(Fixups[i]);
469   }
470   DF->getContents().append(Code.begin(), Code.end());
471 }
472
473 void MCELFStreamer::EmitInstruction(const MCInst &Inst) {
474   // Scan for values.
475   for (unsigned i = 0; i != Inst.getNumOperands(); ++i)
476     if (Inst.getOperand(i).isExpr())
477       AddValueSymbols(Inst.getOperand(i).getExpr());
478
479   getCurrentSectionData()->setHasInstructions(true);
480
481   // If this instruction doesn't need relaxation, just emit it as data.
482   if (!getAssembler().getBackend().MayNeedRelaxation(Inst)) {
483     EmitInstToData(Inst);
484     return;
485   }
486
487   // Otherwise, if we are relaxing everything, relax the instruction as much as
488   // possible and emit it as data.
489   if (getAssembler().getRelaxAll()) {
490     MCInst Relaxed;
491     getAssembler().getBackend().RelaxInstruction(Inst, Relaxed);
492     while (getAssembler().getBackend().MayNeedRelaxation(Relaxed))
493       getAssembler().getBackend().RelaxInstruction(Relaxed, Relaxed);
494     EmitInstToData(Relaxed);
495     return;
496   }
497
498   // Otherwise emit to a separate fragment.
499   EmitInstToFragment(Inst);
500 }
501
502 void MCELFStreamer::Finish() {
503   for (std::vector<LocalCommon>::const_iterator i = LocalCommons.begin(),
504                                                 e = LocalCommons.end();
505        i != e; ++i) {
506     MCSymbolData *SD = i->SD;
507     uint64_t Size = i->Size;
508     unsigned ByteAlignment = i->ByteAlignment;
509     const MCSymbol &Symbol = SD->getSymbol();
510     const MCSection &Section = Symbol.getSection();
511
512     MCSectionData &SectData = getAssembler().getOrCreateSectionData(Section);
513     new MCAlignFragment(ByteAlignment, 0, 1, ByteAlignment, &SectData);
514
515     MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
516     SD->setFragment(F);
517
518     // Update the maximum alignment of the section if necessary.
519     if (ByteAlignment > SectData.getAlignment())
520       SectData.setAlignment(ByteAlignment);
521   }
522
523   // FIXME: We create more atoms than it is necessary. Some relocations to
524   // merge sections can be implemented with section address + offset,
525   // figure out which ones and why.
526
527   // First, scan the symbol table to build a lookup table from fragments to
528   // defining symbols.
529   DenseMap<const MCFragment*, MCSymbolData*> DefiningSymbolMap;
530   for (MCAssembler::symbol_iterator it = getAssembler().symbol_begin(),
531          ie = getAssembler().symbol_end(); it != ie; ++it) {
532     if (isSymbolLinkerVisible(getAssembler(), *it) &&
533         it->getFragment()) {
534       // An atom defining symbol should never be internal to a fragment.
535       assert(it->getOffset() == 0 && "Invalid offset in atom defining symbol!");
536       DefiningSymbolMap[it->getFragment()] = it;
537     }
538   }
539
540   // Set the fragment atom associations by tracking the last seen atom defining
541   // symbol.
542   for (MCAssembler::iterator it = getAssembler().begin(),
543          ie = getAssembler().end(); it != ie; ++it) {
544     MCSymbolData *CurrentAtom = 0;
545     for (MCSectionData::iterator it2 = it->begin(),
546            ie2 = it->end(); it2 != ie2; ++it2) {
547       if (MCSymbolData *SD = DefiningSymbolMap.lookup(it2))
548         CurrentAtom = SD;
549       it2->setAtom(CurrentAtom);
550     }
551   }
552
553   this->MCObjectStreamer::Finish();
554 }
555
556 MCStreamer *llvm::createELFStreamer(MCContext &Context, TargetAsmBackend &TAB,
557                                       raw_ostream &OS, MCCodeEmitter *CE,
558                                       bool RelaxAll) {
559   MCELFStreamer *S = new MCELFStreamer(Context, TAB, OS, CE);
560   if (RelaxAll)
561     S->getAssembler().setRelaxAll(true);
562   return S;
563 }