1 //===- lib/MC/MCELFStreamer.cpp - ELF Object Output ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file assembles .s files and emits ELF .o object files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/MC/MCStreamer.h"
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/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 #include "llvm/Target/TargetAsmBackend.h"
38 static void SetBinding(MCSymbolData &SD, unsigned Binding) {
39 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
40 Binding == ELF::STB_WEAK);
41 uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STB_Shift);
42 SD.setFlags(OtherFlags | (Binding << ELF_STB_Shift));
45 static unsigned GetBinding(const MCSymbolData &SD) {
46 uint32_t Binding = (SD.getFlags() & (0xf << ELF_STB_Shift)) >> ELF_STB_Shift;
47 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
48 Binding == ELF::STB_WEAK);
52 static void SetType(MCSymbolData &SD, unsigned Type) {
53 assert(Type == ELF::STT_NOTYPE || Type == ELF::STT_OBJECT ||
54 Type == ELF::STT_FUNC || Type == ELF::STT_SECTION ||
55 Type == ELF::STT_FILE || Type == ELF::STT_COMMON ||
56 Type == ELF::STT_TLS);
58 uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STT_Shift);
59 SD.setFlags(OtherFlags | (Type << ELF_STT_Shift));
62 static void SetVisibility(MCSymbolData &SD, unsigned Visibility) {
63 assert(Visibility == ELF::STV_DEFAULT || Visibility == ELF::STV_INTERNAL ||
64 Visibility == ELF::STV_HIDDEN || Visibility == ELF::STV_PROTECTED);
66 uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STV_Shift);
67 SD.setFlags(OtherFlags | (Visibility << ELF_STV_Shift));
70 class MCELFStreamer : public MCObjectStreamer {
72 MCELFStreamer(MCContext &Context, TargetAsmBackend &TAB,
73 raw_ostream &OS, MCCodeEmitter *Emitter)
74 : MCObjectStreamer(Context, TAB, OS, Emitter, false) {}
78 /// @name MCStreamer Interface
81 virtual void InitSections();
82 virtual void EmitLabel(MCSymbol *Symbol);
83 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
84 virtual void EmitThumbFunc(MCSymbol *Func);
85 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
86 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol);
87 virtual void SwitchSection(const MCSection *Section);
88 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
89 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
90 assert(0 && "ELF doesn't support this directive");
92 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
93 unsigned ByteAlignment);
94 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {
95 assert(0 && "ELF doesn't support this directive");
98 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
99 assert(0 && "ELF doesn't support this directive");
102 virtual void EmitCOFFSymbolType(int Type) {
103 assert(0 && "ELF doesn't support this directive");
106 virtual void EndCOFFSymbolDef() {
107 assert(0 && "ELF doesn't support this directive");
110 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
111 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
115 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
116 assert(0 && "ELF doesn't support this directive");
118 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
119 unsigned Size = 0, unsigned ByteAlignment = 0) {
120 assert(0 && "ELF doesn't support this directive");
122 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
123 uint64_t Size, unsigned ByteAlignment = 0) {
124 assert(0 && "ELF doesn't support this directive");
126 virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
127 virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
128 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
129 unsigned ValueSize = 1,
130 unsigned MaxBytesToEmit = 0);
131 virtual void EmitCodeAlignment(unsigned ByteAlignment,
132 unsigned MaxBytesToEmit = 0);
133 virtual void EmitValueToOffset(const MCExpr *Offset,
134 unsigned char Value = 0);
136 virtual void EmitFileDirective(StringRef Filename);
138 virtual void Finish();
141 virtual void EmitInstToFragment(const MCInst &Inst);
142 virtual void EmitInstToData(const MCInst &Inst);
144 void fixSymbolsInTLSFixups(const MCExpr *expr);
149 unsigned ByteAlignment;
151 std::vector<LocalCommon> LocalCommons;
153 SmallPtrSet<MCSymbol *, 16> BindingExplicitlySet;
155 void SetSection(StringRef Section, unsigned Type, unsigned Flags,
157 SwitchSection(getContext().getELFSection(Section, Type, Flags, Kind));
160 void SetSectionData() {
161 SetSection(".data", MCSectionELF::SHT_PROGBITS,
162 MCSectionELF::SHF_WRITE |MCSectionELF::SHF_ALLOC,
163 SectionKind::getDataRel());
164 EmitCodeAlignment(4, 0);
166 void SetSectionText() {
167 SetSection(".text", MCSectionELF::SHT_PROGBITS,
168 MCSectionELF::SHF_EXECINSTR |
169 MCSectionELF::SHF_ALLOC, SectionKind::getText());
170 EmitCodeAlignment(4, 0);
172 void SetSectionBss() {
173 SetSection(".bss", MCSectionELF::SHT_NOBITS,
174 MCSectionELF::SHF_WRITE |
175 MCSectionELF::SHF_ALLOC, SectionKind::getBSS());
176 EmitCodeAlignment(4, 0);
180 } // end anonymous namespace.
182 void MCELFStreamer::InitSections() {
183 // This emulates the same behavior of GNU as. This makes it easier
184 // to compare the output as the major sections are in the same order.
191 void MCELFStreamer::EmitLabel(MCSymbol *Symbol) {
192 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
194 Symbol->setSection(*CurSection);
196 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
198 const MCSectionELF &Section =
199 static_cast<const MCSectionELF&>(Symbol->getSection());
200 if (Section.getFlags() & MCSectionELF::SHF_TLS)
201 SetType(SD, ELF::STT_TLS);
203 // FIXME: This is wasteful, we don't necessarily need to create a data
204 // fragment. Instead, we should mark the symbol as pointing into the data
205 // fragment if it exists, otherwise we should just queue the label and set its
206 // fragment pointer when we emit the next fragment.
207 MCDataFragment *F = getOrCreateDataFragment();
209 assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
211 SD.setOffset(F->getContents().size());
214 void MCELFStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
216 case MCAF_SyntaxUnified: return; // no-op here.
217 case MCAF_Code16: return; // no-op here.
218 case MCAF_Code32: return; // no-op here.
219 case MCAF_SubsectionsViaSymbols:
220 getAssembler().setSubsectionsViaSymbols(true);
224 assert(0 && "invalid assembler flag!");
227 void MCELFStreamer::EmitThumbFunc(MCSymbol *Func) {
228 // FIXME: Anything needed here to flag the function as thumb?
231 void MCELFStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
232 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
234 // FIXME: Lift context changes into super class.
235 getAssembler().getOrCreateSymbolData(*Symbol);
236 Symbol->setVariableValue(AddValueSymbols(Value));
239 void MCELFStreamer::SwitchSection(const MCSection *Section) {
240 const MCSymbol *Grp = static_cast<const MCSectionELF *>(Section)->getGroup();
242 getAssembler().getOrCreateSymbolData(*Grp);
243 this->MCObjectStreamer::SwitchSection(Section);
246 void MCELFStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
247 getAssembler().getOrCreateSymbolData(*Symbol);
248 MCSymbolData &AliasSD = getAssembler().getOrCreateSymbolData(*Alias);
249 AliasSD.setFlags(AliasSD.getFlags() | ELF_Other_Weakref);
250 const MCExpr *Value = MCSymbolRefExpr::Create(Symbol, getContext());
251 Alias->setVariableValue(Value);
254 void MCELFStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
255 MCSymbolAttr Attribute) {
256 // Indirect symbols are handled differently, to match how 'as' handles
257 // them. This makes writing matching .o files easier.
258 if (Attribute == MCSA_IndirectSymbol) {
259 // Note that we intentionally cannot use the symbol data here; this is
260 // important for matching the string table that 'as' generates.
261 IndirectSymbolData ISD;
263 ISD.SectionData = getCurrentSectionData();
264 getAssembler().getIndirectSymbols().push_back(ISD);
268 // Adding a symbol attribute always introduces the symbol, note that an
269 // important side effect of calling getOrCreateSymbolData here is to register
270 // the symbol with the assembler.
271 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
273 // The implementation of symbol attributes is designed to match 'as', but it
274 // leaves much to desired. It doesn't really make sense to arbitrarily add and
275 // remove flags, but 'as' allows this (in particular, see .desc).
277 // In the future it might be worth trying to make these operations more well
280 case MCSA_LazyReference:
282 case MCSA_NoDeadStrip:
283 case MCSA_SymbolResolver:
284 case MCSA_PrivateExtern:
285 case MCSA_WeakDefinition:
286 case MCSA_WeakDefAutoPrivate:
288 case MCSA_ELF_TypeIndFunction:
289 case MCSA_IndirectSymbol:
290 assert(0 && "Invalid symbol attribute for ELF!");
293 case MCSA_ELF_TypeGnuUniqueObject:
298 SetBinding(SD, ELF::STB_GLOBAL);
299 SD.setExternal(true);
300 BindingExplicitlySet.insert(Symbol);
303 case MCSA_WeakReference:
305 SetBinding(SD, ELF::STB_WEAK);
306 SD.setExternal(true);
307 BindingExplicitlySet.insert(Symbol);
311 SetBinding(SD, ELF::STB_LOCAL);
312 SD.setExternal(false);
313 BindingExplicitlySet.insert(Symbol);
316 case MCSA_ELF_TypeFunction:
317 SetType(SD, ELF::STT_FUNC);
320 case MCSA_ELF_TypeObject:
321 SetType(SD, ELF::STT_OBJECT);
324 case MCSA_ELF_TypeTLS:
325 SetType(SD, ELF::STT_TLS);
328 case MCSA_ELF_TypeCommon:
329 SetType(SD, ELF::STT_COMMON);
332 case MCSA_ELF_TypeNoType:
333 SetType(SD, ELF::STT_NOTYPE);
337 SetVisibility(SD, ELF::STV_PROTECTED);
341 SetVisibility(SD, ELF::STV_HIDDEN);
345 SetVisibility(SD, ELF::STV_INTERNAL);
350 void MCELFStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
351 unsigned ByteAlignment) {
352 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
354 if (!BindingExplicitlySet.count(Symbol)) {
355 SetBinding(SD, ELF::STB_GLOBAL);
356 SD.setExternal(true);
359 SetType(SD, ELF::STT_OBJECT);
361 if (GetBinding(SD) == ELF_STB_Local) {
362 const MCSection *Section = getAssembler().getContext().getELFSection(".bss",
363 MCSectionELF::SHT_NOBITS,
364 MCSectionELF::SHF_WRITE |
365 MCSectionELF::SHF_ALLOC,
366 SectionKind::getBSS());
367 Symbol->setSection(*Section);
369 struct LocalCommon L = {&SD, Size, ByteAlignment};
370 LocalCommons.push_back(L);
372 SD.setCommon(Size, ByteAlignment);
375 SD.setSize(MCConstantExpr::Create(Size, getContext()));
378 void MCELFStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
379 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
381 getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
384 void MCELFStreamer::EmitValue(const MCExpr *Value, unsigned Size,
385 unsigned AddrSpace) {
386 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
388 MCDataFragment *DF = getOrCreateDataFragment();
390 // Avoid fixups when possible.
392 if (AddValueSymbols(Value)->EvaluateAsAbsolute(AbsValue)) {
393 // FIXME: Endianness assumption.
394 for (unsigned i = 0; i != Size; ++i)
395 DF->getContents().push_back(uint8_t(AbsValue >> (i * 8)));
397 DF->addFixup(MCFixup::Create(DF->getContents().size(), AddValueSymbols(Value),
398 MCFixup::getKindForSize(Size, false)));
399 DF->getContents().resize(DF->getContents().size() + Size, 0);
403 void MCELFStreamer::EmitValueToAlignment(unsigned ByteAlignment,
404 int64_t Value, unsigned ValueSize,
405 unsigned MaxBytesToEmit) {
406 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
408 if (MaxBytesToEmit == 0)
409 MaxBytesToEmit = ByteAlignment;
410 new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
411 getCurrentSectionData());
413 // Update the maximum alignment on the current section if necessary.
414 if (ByteAlignment > getCurrentSectionData()->getAlignment())
415 getCurrentSectionData()->setAlignment(ByteAlignment);
418 void MCELFStreamer::EmitCodeAlignment(unsigned ByteAlignment,
419 unsigned MaxBytesToEmit) {
420 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
422 if (MaxBytesToEmit == 0)
423 MaxBytesToEmit = ByteAlignment;
424 MCAlignFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
425 getCurrentSectionData());
426 F->setEmitNops(true);
428 // Update the maximum alignment on the current section if necessary.
429 if (ByteAlignment > getCurrentSectionData()->getAlignment())
430 getCurrentSectionData()->setAlignment(ByteAlignment);
433 void MCELFStreamer::EmitValueToOffset(const MCExpr *Offset,
434 unsigned char Value) {
435 // TODO: This is exactly the same as MCMachOStreamer. Consider merging into
437 new MCOrgFragment(*Offset, Value, getCurrentSectionData());
440 // Add a symbol for the file name of this module. This is the second
441 // entry in the module's symbol table (the first being the null symbol).
442 void MCELFStreamer::EmitFileDirective(StringRef Filename) {
443 MCSymbol *Symbol = getAssembler().getContext().GetOrCreateSymbol(Filename);
444 Symbol->setSection(*CurSection);
445 Symbol->setAbsolute();
447 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
449 SD.setFlags(ELF_STT_File | ELF_STB_Local | ELF_STV_Default);
452 void MCELFStreamer::fixSymbolsInTLSFixups(const MCExpr *expr) {
453 switch (expr->getKind()) {
454 case MCExpr::Target: llvm_unreachable("Can't handle target exprs yet!");
455 case MCExpr::Constant:
458 case MCExpr::Binary: {
459 const MCBinaryExpr *be = cast<MCBinaryExpr>(expr);
460 fixSymbolsInTLSFixups(be->getLHS());
461 fixSymbolsInTLSFixups(be->getRHS());
465 case MCExpr::SymbolRef: {
466 const MCSymbolRefExpr &symRef = *cast<MCSymbolRefExpr>(expr);
467 switch (symRef.getKind()) {
470 case MCSymbolRefExpr::VK_NTPOFF:
471 case MCSymbolRefExpr::VK_GOTNTPOFF:
472 case MCSymbolRefExpr::VK_TLSGD:
473 case MCSymbolRefExpr::VK_TLSLDM:
474 case MCSymbolRefExpr::VK_TPOFF:
475 case MCSymbolRefExpr::VK_DTPOFF:
476 case MCSymbolRefExpr::VK_GOTTPOFF:
477 case MCSymbolRefExpr::VK_TLSLD:
478 case MCSymbolRefExpr::VK_ARM_TLSGD:
481 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(symRef.getSymbol());
482 SetType(SD, ELF::STT_TLS);
487 fixSymbolsInTLSFixups(cast<MCUnaryExpr>(expr)->getSubExpr());
492 void MCELFStreamer::EmitInstToFragment(const MCInst &Inst) {
493 MCInstFragment *IF = new MCInstFragment(Inst, getCurrentSectionData());
495 // Add the fixups and data.
497 // FIXME: Revisit this design decision when relaxation is done, we may be
498 // able to get away with not storing any extra data in the MCInst.
499 SmallVector<MCFixup, 4> Fixups;
500 SmallString<256> Code;
501 raw_svector_ostream VecOS(Code);
502 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
505 for (unsigned i = 0, e = Fixups.size(); i != e; ++i)
506 fixSymbolsInTLSFixups(Fixups[i].getValue());
508 IF->getCode() = Code;
509 IF->getFixups() = Fixups;
512 void MCELFStreamer::EmitInstToData(const MCInst &Inst) {
513 MCDataFragment *DF = getOrCreateDataFragment();
515 SmallVector<MCFixup, 4> Fixups;
516 SmallString<256> Code;
517 raw_svector_ostream VecOS(Code);
518 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
521 for (unsigned i = 0, e = Fixups.size(); i != e; ++i)
522 fixSymbolsInTLSFixups(Fixups[i].getValue());
524 // Add the fixups and data.
525 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
526 Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
527 DF->addFixup(Fixups[i]);
529 DF->getContents().append(Code.begin(), Code.end());
532 void MCELFStreamer::Finish() {
533 // FIXME: duplicated code with the MachO streamer.
534 // Dump out the dwarf file & directory tables and line tables.
535 if (getContext().hasDwarfFiles()) {
536 const MCSection *DwarfLineSection =
537 getContext().getELFSection(".debug_line", 0, 0,
538 SectionKind::getDataRelLocal());
540 getAssembler().getOrCreateSectionData(*DwarfLineSection);
541 int PointerSize = getAssembler().getBackend().getPointerSize();
542 MCDwarfFileTable::Emit(this, DwarfLineSection, &DLS, PointerSize);
545 for (std::vector<LocalCommon>::const_iterator i = LocalCommons.begin(),
546 e = LocalCommons.end();
548 MCSymbolData *SD = i->SD;
549 uint64_t Size = i->Size;
550 unsigned ByteAlignment = i->ByteAlignment;
551 const MCSymbol &Symbol = SD->getSymbol();
552 const MCSection &Section = Symbol.getSection();
554 MCSectionData &SectData = getAssembler().getOrCreateSectionData(Section);
555 new MCAlignFragment(ByteAlignment, 0, 1, ByteAlignment, &SectData);
557 MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
560 // Update the maximum alignment of the section if necessary.
561 if (ByteAlignment > SectData.getAlignment())
562 SectData.setAlignment(ByteAlignment);
565 this->MCObjectStreamer::Finish();
568 MCStreamer *llvm::createELFStreamer(MCContext &Context, TargetAsmBackend &TAB,
569 raw_ostream &OS, MCCodeEmitter *CE,
571 MCELFStreamer *S = new MCELFStreamer(Context, TAB, OS, CE);
573 S->getAssembler().setRelaxAll(true);