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