6490cc7a82ef80960fc02329690dffbb193f1392
[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/MC/MCAssembler.h"
17 #include "llvm/MC/MCContext.h"
18 #include "llvm/MC/MCCodeEmitter.h"
19 #include "llvm/MC/MCELFSymbolFlags.h"
20 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCInst.h"
22 #include "llvm/MC/MCObjectStreamer.h"
23 #include "llvm/MC/MCSection.h"
24 #include "llvm/MC/MCSectionELF.h"
25 #include "llvm/MC/MCSymbol.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ELF.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Target/TargetAsmBackend.h"
31
32 using namespace llvm;
33
34 namespace {
35
36 class MCELFStreamer : public MCObjectStreamer {
37   void EmitInstToFragment(const MCInst &Inst);
38   void EmitInstToData(const MCInst &Inst);
39 public:
40   MCELFStreamer(MCContext &Context, TargetAsmBackend &TAB,
41                   raw_ostream &OS, MCCodeEmitter *Emitter)
42     : MCObjectStreamer(Context, TAB, OS, Emitter) {}
43
44   ~MCELFStreamer() {}
45
46   /// @name MCStreamer Interface
47   /// @{
48
49   virtual void EmitLabel(MCSymbol *Symbol);
50   virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
51   virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
52   virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
53   virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
54     assert(0 && "ELF doesn't support this directive");
55   }
56   virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
57                                 unsigned ByteAlignment);
58   virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {
59     assert(0 && "ELF doesn't support this directive");
60   }
61
62   virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
63     assert(0 && "ELF doesn't support this directive");
64   }
65
66   virtual void EmitCOFFSymbolType(int Type) {
67     assert(0 && "ELF doesn't support this directive");
68   }
69
70   virtual void EndCOFFSymbolDef() {
71     assert(0 && "ELF doesn't support this directive");
72   }
73
74   virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
75      MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
76      SD.setSize(Value);
77   }
78
79   virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
80     assert(0 && "ELF doesn't support this directive");
81   }
82   virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
83                             unsigned Size = 0, unsigned ByteAlignment = 0) {
84     assert(0 && "ELF doesn't support this directive");
85   }
86   virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
87                               uint64_t Size, unsigned ByteAlignment = 0) {
88     assert(0 && "ELF doesn't support this directive");
89   }
90   virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
91   virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
92   virtual void EmitGPRel32Value(const MCExpr *Value) {
93     assert(0 && "ELF doesn't support this directive");
94   }
95   virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
96                                     unsigned ValueSize = 1,
97                                     unsigned MaxBytesToEmit = 0);
98   virtual void EmitCodeAlignment(unsigned ByteAlignment,
99                                  unsigned MaxBytesToEmit = 0);
100   virtual void EmitValueToOffset(const MCExpr *Offset,
101                                  unsigned char Value = 0);
102
103   virtual void EmitFileDirective(StringRef Filename);
104   virtual void EmitDwarfFileDirective(unsigned FileNo, StringRef Filename) {
105     DEBUG(dbgs() << "FIXME: MCELFStreamer:EmitDwarfFileDirective not implemented\n");
106   }
107
108   virtual void EmitInstruction(const MCInst &Inst);
109   virtual void Finish();
110
111   /// @}
112 };
113
114 } // end anonymous namespace.
115
116 void MCELFStreamer::EmitLabel(MCSymbol *Symbol) {
117   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
118
119   // FIXME: This is wasteful, we don't necessarily need to create a data
120   // fragment. Instead, we should mark the symbol as pointing into the data
121   // fragment if it exists, otherwise we should just queue the label and set its
122   // fragment pointer when we emit the next fragment.
123   MCDataFragment *F = getOrCreateDataFragment();
124   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
125   assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
126   SD.setFragment(F);
127   SD.setOffset(F->getContents().size());
128
129   Symbol->setSection(*CurSection);
130 }
131
132 void MCELFStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
133   switch (Flag) {
134   case MCAF_SubsectionsViaSymbols:
135     getAssembler().setSubsectionsViaSymbols(true);
136     return;
137   }
138
139   assert(0 && "invalid assembler flag!");
140 }
141
142 void MCELFStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
143   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
144   // MCObjectStreamer.
145   // FIXME: Lift context changes into super class.
146   getAssembler().getOrCreateSymbolData(*Symbol);
147   Symbol->setVariableValue(AddValueSymbols(Value));
148 }
149
150 static void SetBinding(MCSymbolData &SD, unsigned Binding) {
151   assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
152          Binding == ELF::STB_WEAK);
153   uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STB_Shift);
154   SD.setFlags(OtherFlags | (Binding << ELF_STB_Shift));
155 }
156
157 static void SetType(MCSymbolData &SD, unsigned Type) {
158   assert(Type == ELF::STT_NOTYPE || Type == ELF::STT_OBJECT ||
159          Type == ELF::STT_FUNC || Type == ELF::STT_SECTION ||
160          Type == ELF::STT_FILE || Type == ELF::STT_COMMON ||
161          Type == ELF::STT_TLS);
162
163   uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STT_Shift);
164   SD.setFlags(OtherFlags | (Type << ELF_STT_Shift));
165 }
166
167 static void SetVisibility(MCSymbolData &SD, unsigned Visibility) {
168   assert(Visibility == ELF::STV_DEFAULT || Visibility == ELF::STV_INTERNAL ||
169          Visibility == ELF::STV_HIDDEN || Visibility == ELF::STV_PROTECTED);
170
171   uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STV_Shift);
172   SD.setFlags(OtherFlags | (Visibility << ELF_STV_Shift));
173 }
174
175 void MCELFStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
176                                           MCSymbolAttr Attribute) {
177   // Indirect symbols are handled differently, to match how 'as' handles
178   // them. This makes writing matching .o files easier.
179   if (Attribute == MCSA_IndirectSymbol) {
180     // Note that we intentionally cannot use the symbol data here; this is
181     // important for matching the string table that 'as' generates.
182     IndirectSymbolData ISD;
183     ISD.Symbol = Symbol;
184     ISD.SectionData = getCurrentSectionData();
185     getAssembler().getIndirectSymbols().push_back(ISD);
186     return;
187   }
188
189   // Adding a symbol attribute always introduces the symbol, note that an
190   // important side effect of calling getOrCreateSymbolData here is to register
191   // the symbol with the assembler.
192   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
193
194   // The implementation of symbol attributes is designed to match 'as', but it
195   // leaves much to desired. It doesn't really make sense to arbitrarily add and
196   // remove flags, but 'as' allows this (in particular, see .desc).
197   //
198   // In the future it might be worth trying to make these operations more well
199   // defined.
200   switch (Attribute) {
201   case MCSA_LazyReference:
202   case MCSA_Reference:
203   case MCSA_NoDeadStrip:
204   case MCSA_PrivateExtern:
205   case MCSA_WeakDefinition:
206   case MCSA_WeakDefAutoPrivate:
207   case MCSA_Invalid:
208   case MCSA_ELF_TypeIndFunction:
209   case MCSA_IndirectSymbol:
210     assert(0 && "Invalid symbol attribute for ELF!");
211     break;
212
213   case MCSA_Global:
214     SetBinding(SD, ELF::STB_GLOBAL);
215     SD.setExternal(true);
216     break;
217
218   case MCSA_WeakReference:
219   case MCSA_Weak:
220     SetBinding(SD, ELF::STB_WEAK);
221     break;
222
223   case MCSA_Local:
224     SetBinding(SD, ELF::STB_LOCAL);
225     break;
226
227   case MCSA_ELF_TypeFunction:
228     SetType(SD, ELF::STT_FUNC);
229     break;
230
231   case MCSA_ELF_TypeObject:
232     SetType(SD, ELF::STT_OBJECT);
233     break;
234
235   case MCSA_ELF_TypeTLS:
236     SetType(SD, ELF::STT_TLS);
237     break;
238
239   case MCSA_ELF_TypeCommon:
240     SetType(SD, ELF::STT_COMMON);
241     break;
242
243   case MCSA_ELF_TypeNoType:
244     SetType(SD, ELF::STT_NOTYPE);
245     break;
246
247   case MCSA_Protected:
248     SetVisibility(SD, ELF::STV_PROTECTED);
249     break;
250
251   case MCSA_Hidden:
252     SetVisibility(SD, ELF::STV_HIDDEN);
253     break;
254
255   case MCSA_Internal:
256     SetVisibility(SD, ELF::STV_INTERNAL);
257     break;
258   }
259 }
260
261 void MCELFStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
262                                        unsigned ByteAlignment) {
263   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
264
265   if ((SD.getFlags() & (0xf << ELF_STB_Shift)) == ELF_STB_Local) {
266     const MCSection *Section = getAssembler().getContext().getELFSection(".bss",
267                                                                     MCSectionELF::SHT_NOBITS,
268                                                                     MCSectionELF::SHF_WRITE |
269                                                                     MCSectionELF::SHF_ALLOC,
270                                                                     SectionKind::getBSS());
271
272     MCSectionData &SectData = getAssembler().getOrCreateSectionData(*Section);
273     MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
274     SD.setFragment(F);
275     Symbol->setSection(*Section);
276     SD.setSize(MCConstantExpr::Create(Size, getContext()));
277   }
278
279   SetBinding(SD, ELF::STB_GLOBAL);
280   SD.setExternal(true);
281
282   SD.setCommon(Size, ByteAlignment);
283 }
284
285 void MCELFStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
286   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
287   // MCObjectStreamer.
288   getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
289 }
290
291 void MCELFStreamer::EmitValue(const MCExpr *Value, unsigned Size,
292                                 unsigned AddrSpace) {
293   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
294   // MCObjectStreamer.
295   MCDataFragment *DF = getOrCreateDataFragment();
296
297   // Avoid fixups when possible.
298   int64_t AbsValue;
299   if (AddValueSymbols(Value)->EvaluateAsAbsolute(AbsValue)) {
300     // FIXME: Endianness assumption.
301     for (unsigned i = 0; i != Size; ++i)
302       DF->getContents().push_back(uint8_t(AbsValue >> (i * 8)));
303   } else {
304     DF->addFixup(MCFixup::Create(DF->getContents().size(), AddValueSymbols(Value),
305                                  MCFixup::getKindForSize(Size)));
306     DF->getContents().resize(DF->getContents().size() + Size, 0);
307   }
308 }
309
310 void MCELFStreamer::EmitValueToAlignment(unsigned ByteAlignment,
311                                            int64_t Value, unsigned ValueSize,
312                                            unsigned MaxBytesToEmit) {
313   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
314   // MCObjectStreamer.
315   if (MaxBytesToEmit == 0)
316     MaxBytesToEmit = ByteAlignment;
317   new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
318                       getCurrentSectionData());
319
320   // Update the maximum alignment on the current section if necessary.
321   if (ByteAlignment > getCurrentSectionData()->getAlignment())
322     getCurrentSectionData()->setAlignment(ByteAlignment);
323 }
324
325 void MCELFStreamer::EmitCodeAlignment(unsigned ByteAlignment,
326                                         unsigned MaxBytesToEmit) {
327   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
328   // MCObjectStreamer.
329   if (MaxBytesToEmit == 0)
330     MaxBytesToEmit = ByteAlignment;
331   MCAlignFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
332                                            getCurrentSectionData());
333   F->setEmitNops(true);
334
335   // Update the maximum alignment on the current section if necessary.
336   if (ByteAlignment > getCurrentSectionData()->getAlignment())
337     getCurrentSectionData()->setAlignment(ByteAlignment);
338 }
339
340 void MCELFStreamer::EmitValueToOffset(const MCExpr *Offset,
341                                         unsigned char Value) {
342   // TODO: This is exactly the same as MCMachOStreamer. Consider merging into
343   // MCObjectStreamer.
344   new MCOrgFragment(*Offset, Value, getCurrentSectionData());
345 }
346
347 // Add a symbol for the file name of this module. This is the second
348 // entry in the module's symbol table (the first being the null symbol).
349 void MCELFStreamer::EmitFileDirective(StringRef Filename) {
350   MCSymbol *Symbol = getAssembler().getContext().GetOrCreateSymbol(Filename);
351   Symbol->setSection(*CurSection);
352   Symbol->setAbsolute();
353
354   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
355
356   SD.setFlags(ELF_STT_File | ELF_STB_Local | ELF_STV_Default);
357 }
358
359 void MCELFStreamer::EmitInstToFragment(const MCInst &Inst) {
360   MCInstFragment *IF = new MCInstFragment(Inst, getCurrentSectionData());
361
362   // Add the fixups and data.
363   //
364   // FIXME: Revisit this design decision when relaxation is done, we may be
365   // able to get away with not storing any extra data in the MCInst.
366   SmallVector<MCFixup, 4> Fixups;
367   SmallString<256> Code;
368   raw_svector_ostream VecOS(Code);
369   getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
370   VecOS.flush();
371
372   IF->getCode() = Code;
373   IF->getFixups() = Fixups;
374 }
375
376 void MCELFStreamer::EmitInstToData(const MCInst &Inst) {
377   MCDataFragment *DF = getOrCreateDataFragment();
378
379   SmallVector<MCFixup, 4> Fixups;
380   SmallString<256> Code;
381   raw_svector_ostream VecOS(Code);
382   getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
383   VecOS.flush();
384
385   // Add the fixups and data.
386   for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
387     Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
388     DF->addFixup(Fixups[i]);
389   }
390   DF->getContents().append(Code.begin(), Code.end());
391 }
392
393 void MCELFStreamer::EmitInstruction(const MCInst &Inst) {
394   // Scan for values.
395   for (unsigned i = 0; i != Inst.getNumOperands(); ++i)
396     if (Inst.getOperand(i).isExpr())
397       AddValueSymbols(Inst.getOperand(i).getExpr());
398
399   getCurrentSectionData()->setHasInstructions(true);
400
401   // If this instruction doesn't need relaxation, just emit it as data.
402   if (!getAssembler().getBackend().MayNeedRelaxation(Inst)) {
403     EmitInstToData(Inst);
404     return;
405   }
406
407   // Otherwise, if we are relaxing everything, relax the instruction as much as
408   // possible and emit it as data.
409   if (getAssembler().getRelaxAll()) {
410     MCInst Relaxed;
411     getAssembler().getBackend().RelaxInstruction(Inst, Relaxed);
412     while (getAssembler().getBackend().MayNeedRelaxation(Relaxed))
413       getAssembler().getBackend().RelaxInstruction(Relaxed, Relaxed);
414     EmitInstToData(Relaxed);
415     return;
416   }
417
418   // Otherwise emit to a separate fragment.
419   EmitInstToFragment(Inst);
420 }
421
422 void MCELFStreamer::Finish() {
423   getAssembler().Finish();
424 }
425
426 MCStreamer *llvm::createELFStreamer(MCContext &Context, TargetAsmBackend &TAB,
427                                       raw_ostream &OS, MCCodeEmitter *CE,
428                                       bool RelaxAll) {
429   MCELFStreamer *S = new MCELFStreamer(Context, TAB, OS, CE);
430   if (RelaxAll)
431     S->getAssembler().setRelaxAll(true);
432   return S;
433 }