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