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/MCELFStreamer.h"
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/MC/MCAssembler.h"
18 #include "llvm/MC/MCAsmBackend.h"
19 #include "llvm/MC/MCCodeEmitter.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCELF.h"
22 #include "llvm/MC/MCELFSymbolFlags.h"
23 #include "llvm/MC/MCExpr.h"
24 #include "llvm/MC/MCInst.h"
25 #include "llvm/MC/MCObjectStreamer.h"
26 #include "llvm/MC/MCSection.h"
27 #include "llvm/MC/MCSectionELF.h"
28 #include "llvm/MC/MCSymbol.h"
29 #include "llvm/MC/MCValue.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ELF.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
38 inline void MCELFStreamer::SetSection(StringRef Section, unsigned Type,
39 unsigned Flags, SectionKind Kind) {
40 SwitchSection(getContext().getELFSection(Section, Type, Flags, Kind));
43 inline void MCELFStreamer::SetSectionData() {
46 ELF::SHF_WRITE | ELF::SHF_ALLOC,
47 SectionKind::getDataRel());
48 EmitCodeAlignment(4, 0);
51 inline void MCELFStreamer::SetSectionText() {
54 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC,
55 SectionKind::getText());
56 EmitCodeAlignment(4, 0);
59 inline void MCELFStreamer::SetSectionBss() {
62 ELF::SHF_WRITE | ELF::SHF_ALLOC,
63 SectionKind::getBSS());
64 EmitCodeAlignment(4, 0);
67 MCELFStreamer::~MCELFStreamer() {
70 void MCELFStreamer::InitToTextSection() {
74 void MCELFStreamer::InitSections() {
75 // This emulates the same behavior of GNU as. This makes it easier
76 // to compare the output as the major sections are in the same order.
83 void MCELFStreamer::EmitLabel(MCSymbol *Symbol) {
84 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
86 MCObjectStreamer::EmitLabel(Symbol);
88 const MCSectionELF &Section =
89 static_cast<const MCSectionELF&>(Symbol->getSection());
90 MCSymbolData &SD = getAssembler().getSymbolData(*Symbol);
91 if (Section.getFlags() & ELF::SHF_TLS)
92 MCELF::SetType(SD, ELF::STT_TLS);
95 void MCELFStreamer::EmitDebugLabel(MCSymbol *Symbol) {
99 void MCELFStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
100 // Let the target do whatever target specific stuff it needs to do.
101 getAssembler().getBackend().handleAssemblerFlag(Flag);
102 // Do any generic stuff we need to do.
104 case MCAF_SyntaxUnified: return; // no-op here.
105 case MCAF_Code16: return; // Change parsing mode; no-op here.
106 case MCAF_Code32: return; // Change parsing mode; no-op here.
107 case MCAF_Code64: return; // Change parsing mode; no-op here.
108 case MCAF_SubsectionsViaSymbols:
109 getAssembler().setSubsectionsViaSymbols(true);
113 llvm_unreachable("invalid assembler flag!");
116 void MCELFStreamer::ChangeSection(const MCSection *Section,
117 const MCExpr *Subsection) {
118 MCSectionData *CurSection = getCurrentSectionData();
119 if (CurSection && CurSection->isBundleLocked())
120 report_fatal_error("Unterminated .bundle_lock when changing a section");
121 const MCSymbol *Grp = static_cast<const MCSectionELF *>(Section)->getGroup();
123 getAssembler().getOrCreateSymbolData(*Grp);
124 this->MCObjectStreamer::ChangeSection(Section, Subsection);
127 void MCELFStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
128 getAssembler().getOrCreateSymbolData(*Symbol);
129 MCSymbolData &AliasSD = getAssembler().getOrCreateSymbolData(*Alias);
130 AliasSD.setFlags(AliasSD.getFlags() | ELF_Other_Weakref);
131 const MCExpr *Value = MCSymbolRefExpr::Create(Symbol, getContext());
132 Alias->setVariableValue(Value);
135 // When GNU as encounters more than one .type declaration for an object it seems
136 // to use a mechanism similar to the one below to decide which type is actually
137 // used in the object file. The greater of T1 and T2 is selected based on the
138 // following ordering:
139 // STT_NOTYPE < STT_OBJECT < STT_FUNC < STT_GNU_IFUNC < STT_TLS < anything else
140 // If neither T1 < T2 nor T2 < T1 according to this ordering, use T2 (the user
142 static unsigned CombineSymbolTypes(unsigned T1, unsigned T2) {
143 unsigned TypeOrdering[] = {ELF::STT_NOTYPE, ELF::STT_OBJECT, ELF::STT_FUNC,
144 ELF::STT_GNU_IFUNC, ELF::STT_TLS};
145 for (unsigned i = 0; i != array_lengthof(TypeOrdering); ++i) {
146 if (T1 == TypeOrdering[i])
148 if (T2 == TypeOrdering[i])
155 bool MCELFStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
156 MCSymbolAttr Attribute) {
157 // Indirect symbols are handled differently, to match how 'as' handles
158 // them. This makes writing matching .o files easier.
159 if (Attribute == MCSA_IndirectSymbol) {
160 // Note that we intentionally cannot use the symbol data here; this is
161 // important for matching the string table that 'as' generates.
162 IndirectSymbolData ISD;
164 ISD.SectionData = getCurrentSectionData();
165 getAssembler().getIndirectSymbols().push_back(ISD);
169 // Adding a symbol attribute always introduces the symbol, note that an
170 // important side effect of calling getOrCreateSymbolData here is to register
171 // the symbol with the assembler.
172 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
174 // The implementation of symbol attributes is designed to match 'as', but it
175 // leaves much to desired. It doesn't really make sense to arbitrarily add and
176 // remove flags, but 'as' allows this (in particular, see .desc).
178 // In the future it might be worth trying to make these operations more well
181 case MCSA_LazyReference:
183 case MCSA_SymbolResolver:
184 case MCSA_PrivateExtern:
185 case MCSA_WeakDefinition:
186 case MCSA_WeakDefAutoPrivate:
188 case MCSA_IndirectSymbol:
191 case MCSA_NoDeadStrip:
192 case MCSA_ELF_TypeGnuUniqueObject:
197 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
198 SD.setExternal(true);
199 BindingExplicitlySet.insert(Symbol);
202 case MCSA_WeakReference:
204 MCELF::SetBinding(SD, ELF::STB_WEAK);
205 SD.setExternal(true);
206 BindingExplicitlySet.insert(Symbol);
210 MCELF::SetBinding(SD, ELF::STB_LOCAL);
211 SD.setExternal(false);
212 BindingExplicitlySet.insert(Symbol);
215 case MCSA_ELF_TypeFunction:
216 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
220 case MCSA_ELF_TypeIndFunction:
221 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
222 ELF::STT_GNU_IFUNC));
225 case MCSA_ELF_TypeObject:
226 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
230 case MCSA_ELF_TypeTLS:
231 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
235 case MCSA_ELF_TypeCommon:
236 // TODO: Emit these as a common symbol.
237 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
241 case MCSA_ELF_TypeNoType:
242 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
247 MCELF::SetVisibility(SD, ELF::STV_PROTECTED);
251 MCELF::SetVisibility(SD, ELF::STV_HIDDEN);
255 MCELF::SetVisibility(SD, ELF::STV_INTERNAL);
262 void MCELFStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
263 unsigned ByteAlignment) {
264 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
266 if (!BindingExplicitlySet.count(Symbol)) {
267 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
268 SD.setExternal(true);
271 MCELF::SetType(SD, ELF::STT_OBJECT);
273 if (MCELF::GetBinding(SD) == ELF_STB_Local) {
274 const MCSection *Section = getAssembler().getContext().getELFSection(".bss",
278 SectionKind::getBSS());
280 AssignSection(Symbol, Section);
282 struct LocalCommon L = {&SD, Size, ByteAlignment};
283 LocalCommons.push_back(L);
285 SD.setCommon(Size, ByteAlignment);
288 SD.setSize(MCConstantExpr::Create(Size, getContext()));
291 void MCELFStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
292 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
296 void MCELFStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
297 unsigned ByteAlignment) {
298 // FIXME: Should this be caught and done earlier?
299 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
300 MCELF::SetBinding(SD, ELF::STB_LOCAL);
301 SD.setExternal(false);
302 BindingExplicitlySet.insert(Symbol);
303 EmitCommonSymbol(Symbol, Size, ByteAlignment);
306 void MCELFStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size) {
307 if (getCurrentSectionData()->isBundleLocked())
308 report_fatal_error("Emitting values inside a locked bundle is forbidden");
309 fixSymbolsInTLSFixups(Value);
310 MCObjectStreamer::EmitValueImpl(Value, Size);
313 void MCELFStreamer::EmitValueToAlignment(unsigned ByteAlignment,
316 unsigned MaxBytesToEmit) {
317 if (getCurrentSectionData()->isBundleLocked())
318 report_fatal_error("Emitting values inside a locked bundle is forbidden");
319 MCObjectStreamer::EmitValueToAlignment(ByteAlignment, Value,
320 ValueSize, MaxBytesToEmit);
323 // Add a symbol for the file name of this module. They start after the
324 // null symbol and don't count as normal symbol, i.e. a non-STT_FILE symbol
325 // with the same name may appear.
326 void MCELFStreamer::EmitFileDirective(StringRef Filename) {
327 getAssembler().addFileName(Filename);
330 void MCELFStreamer::EmitIdent(StringRef IdentString) {
331 const MCSection *Comment = getAssembler().getContext().getELFSection(
332 ".comment", ELF::SHT_PROGBITS, ELF::SHF_MERGE | ELF::SHF_STRINGS,
333 SectionKind::getReadOnly(), 1, "");
335 SwitchSection(Comment);
340 EmitBytes(IdentString);
345 void MCELFStreamer::fixSymbolsInTLSFixups(const MCExpr *expr) {
346 switch (expr->getKind()) {
348 cast<MCTargetExpr>(expr)->fixELFSymbolsInTLSFixups(getAssembler());
350 case MCExpr::Constant:
353 case MCExpr::Binary: {
354 const MCBinaryExpr *be = cast<MCBinaryExpr>(expr);
355 fixSymbolsInTLSFixups(be->getLHS());
356 fixSymbolsInTLSFixups(be->getRHS());
360 case MCExpr::SymbolRef: {
361 const MCSymbolRefExpr &symRef = *cast<MCSymbolRefExpr>(expr);
362 switch (symRef.getKind()) {
365 case MCSymbolRefExpr::VK_GOTTPOFF:
366 case MCSymbolRefExpr::VK_INDNTPOFF:
367 case MCSymbolRefExpr::VK_NTPOFF:
368 case MCSymbolRefExpr::VK_GOTNTPOFF:
369 case MCSymbolRefExpr::VK_TLSGD:
370 case MCSymbolRefExpr::VK_TLSLD:
371 case MCSymbolRefExpr::VK_TLSLDM:
372 case MCSymbolRefExpr::VK_TPOFF:
373 case MCSymbolRefExpr::VK_DTPOFF:
374 case MCSymbolRefExpr::VK_Mips_TLSGD:
375 case MCSymbolRefExpr::VK_Mips_GOTTPREL:
376 case MCSymbolRefExpr::VK_Mips_TPREL_HI:
377 case MCSymbolRefExpr::VK_Mips_TPREL_LO:
378 case MCSymbolRefExpr::VK_PPC_DTPMOD:
379 case MCSymbolRefExpr::VK_PPC_TPREL:
380 case MCSymbolRefExpr::VK_PPC_TPREL_LO:
381 case MCSymbolRefExpr::VK_PPC_TPREL_HI:
382 case MCSymbolRefExpr::VK_PPC_TPREL_HA:
383 case MCSymbolRefExpr::VK_PPC_TPREL_HIGHER:
384 case MCSymbolRefExpr::VK_PPC_TPREL_HIGHERA:
385 case MCSymbolRefExpr::VK_PPC_TPREL_HIGHEST:
386 case MCSymbolRefExpr::VK_PPC_TPREL_HIGHESTA:
387 case MCSymbolRefExpr::VK_PPC_DTPREL:
388 case MCSymbolRefExpr::VK_PPC_DTPREL_LO:
389 case MCSymbolRefExpr::VK_PPC_DTPREL_HI:
390 case MCSymbolRefExpr::VK_PPC_DTPREL_HA:
391 case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHER:
392 case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHERA:
393 case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHEST:
394 case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHESTA:
395 case MCSymbolRefExpr::VK_PPC_GOT_TPREL:
396 case MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO:
397 case MCSymbolRefExpr::VK_PPC_GOT_TPREL_HI:
398 case MCSymbolRefExpr::VK_PPC_GOT_TPREL_HA:
399 case MCSymbolRefExpr::VK_PPC_GOT_DTPREL:
400 case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_LO:
401 case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_HI:
402 case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_HA:
403 case MCSymbolRefExpr::VK_PPC_TLS:
404 case MCSymbolRefExpr::VK_PPC_GOT_TLSGD:
405 case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO:
406 case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HI:
407 case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HA:
408 case MCSymbolRefExpr::VK_PPC_TLSGD:
409 case MCSymbolRefExpr::VK_PPC_GOT_TLSLD:
410 case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO:
411 case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HI:
412 case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HA:
413 case MCSymbolRefExpr::VK_PPC_TLSLD:
416 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(symRef.getSymbol());
417 MCELF::SetType(SD, ELF::STT_TLS);
422 fixSymbolsInTLSFixups(cast<MCUnaryExpr>(expr)->getSubExpr());
427 void MCELFStreamer::EmitInstToFragment(const MCInst &Inst) {
428 this->MCObjectStreamer::EmitInstToFragment(Inst);
429 MCRelaxableFragment &F = *cast<MCRelaxableFragment>(getCurrentFragment());
431 for (unsigned i = 0, e = F.getFixups().size(); i != e; ++i)
432 fixSymbolsInTLSFixups(F.getFixups()[i].getValue());
435 void MCELFStreamer::EmitInstToData(const MCInst &Inst) {
436 MCAssembler &Assembler = getAssembler();
437 SmallVector<MCFixup, 4> Fixups;
438 SmallString<256> Code;
439 raw_svector_ostream VecOS(Code);
440 Assembler.getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
443 for (unsigned i = 0, e = Fixups.size(); i != e; ++i)
444 fixSymbolsInTLSFixups(Fixups[i].getValue());
446 // There are several possibilities here:
448 // If bundling is disabled, append the encoded instruction to the current data
449 // fragment (or create a new such fragment if the current fragment is not a
452 // If bundling is enabled:
453 // - If we're not in a bundle-locked group, emit the instruction into a
454 // fragment of its own. If there are no fixups registered for the
455 // instruction, emit a MCCompactEncodedInstFragment. Otherwise, emit a
457 // - If we're in a bundle-locked group, append the instruction to the current
458 // data fragment because we want all the instructions in a group to get into
459 // the same fragment. Be careful not to do that for the first instruction in
460 // the group, though.
463 if (Assembler.isBundlingEnabled()) {
464 MCSectionData *SD = getCurrentSectionData();
465 if (SD->isBundleLocked() && !SD->isBundleGroupBeforeFirstInst())
466 // If we are bundle-locked, we re-use the current fragment.
467 // The bundle-locking directive ensures this is a new data fragment.
468 DF = cast<MCDataFragment>(getCurrentFragment());
469 else if (!SD->isBundleLocked() && Fixups.size() == 0) {
470 // Optimize memory usage by emitting the instruction to a
471 // MCCompactEncodedInstFragment when not in a bundle-locked group and
472 // there are no fixups registered.
473 MCCompactEncodedInstFragment *CEIF = new MCCompactEncodedInstFragment();
475 CEIF->getContents().append(Code.begin(), Code.end());
478 DF = new MCDataFragment();
480 if (SD->getBundleLockState() == MCSectionData::BundleLockedAlignToEnd) {
481 // If this is a new fragment created for a bundle-locked group, and the
482 // group was marked as "align_to_end", set a flag in the fragment.
483 DF->setAlignToBundleEnd(true);
487 // We're now emitting an instruction in a bundle group, so this flag has
489 SD->setBundleGroupBeforeFirstInst(false);
491 DF = getOrCreateDataFragment();
494 // Add the fixups and data.
495 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
496 Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
497 DF->getFixups().push_back(Fixups[i]);
499 DF->setHasInstructions(true);
500 DF->getContents().append(Code.begin(), Code.end());
503 void MCELFStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
504 assert(AlignPow2 <= 30 && "Invalid bundle alignment");
505 MCAssembler &Assembler = getAssembler();
506 if (Assembler.getBundleAlignSize() == 0 && AlignPow2 > 0)
507 Assembler.setBundleAlignSize(1 << AlignPow2);
509 report_fatal_error(".bundle_align_mode should be only set once per file");
512 void MCELFStreamer::EmitBundleLock(bool AlignToEnd) {
513 MCSectionData *SD = getCurrentSectionData();
517 if (!getAssembler().isBundlingEnabled())
518 report_fatal_error(".bundle_lock forbidden when bundling is disabled");
519 else if (SD->isBundleLocked())
520 report_fatal_error("Nesting of .bundle_lock is forbidden");
522 SD->setBundleLockState(AlignToEnd ? MCSectionData::BundleLockedAlignToEnd :
523 MCSectionData::BundleLocked);
524 SD->setBundleGroupBeforeFirstInst(true);
527 void MCELFStreamer::EmitBundleUnlock() {
528 MCSectionData *SD = getCurrentSectionData();
531 if (!getAssembler().isBundlingEnabled())
532 report_fatal_error(".bundle_unlock forbidden when bundling is disabled");
533 else if (!SD->isBundleLocked())
534 report_fatal_error(".bundle_unlock without matching lock");
535 else if (SD->isBundleGroupBeforeFirstInst())
536 report_fatal_error("Empty bundle-locked group is forbidden");
538 SD->setBundleLockState(MCSectionData::NotBundleLocked);
541 void MCELFStreamer::Flush() {
542 for (std::vector<LocalCommon>::const_iterator i = LocalCommons.begin(),
543 e = LocalCommons.end();
545 MCSymbolData *SD = i->SD;
546 uint64_t Size = i->Size;
547 unsigned ByteAlignment = i->ByteAlignment;
548 const MCSymbol &Symbol = SD->getSymbol();
549 const MCSection &Section = Symbol.getSection();
551 MCSectionData &SectData = getAssembler().getOrCreateSectionData(Section);
552 new MCAlignFragment(ByteAlignment, 0, 1, ByteAlignment, &SectData);
554 MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
557 // Update the maximum alignment of the section if necessary.
558 if (ByteAlignment > SectData.getAlignment())
559 SectData.setAlignment(ByteAlignment);
562 LocalCommons.clear();
565 void MCELFStreamer::FinishImpl() {
566 EmitFrames(NULL, true);
570 this->MCObjectStreamer::FinishImpl();
573 MCStreamer *llvm::createELFStreamer(MCContext &Context,
574 MCTargetStreamer *Streamer,
575 MCAsmBackend &MAB, raw_ostream &OS,
576 MCCodeEmitter *CE, bool RelaxAll,
578 MCELFStreamer *S = new MCELFStreamer(Context, Streamer, MAB, OS, CE);
580 S->getAssembler().setRelaxAll(true);
582 S->getAssembler().setNoExecStack(true);
586 void MCELFStreamer::EmitThumbFunc(MCSymbol *Func) {
587 llvm_unreachable("Generic ELF doesn't support this directive");
590 MCSymbolData &MCELFStreamer::getOrCreateSymbolData(MCSymbol *Symbol) {
591 return getAssembler().getOrCreateSymbolData(*Symbol);
594 void MCELFStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
595 llvm_unreachable("ELF doesn't support this directive");
598 void MCELFStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
599 llvm_unreachable("ELF doesn't support this directive");
602 void MCELFStreamer::EmitCOFFSymbolStorageClass(int StorageClass) {
603 llvm_unreachable("ELF doesn't support this directive");
606 void MCELFStreamer::EmitCOFFSymbolType(int Type) {
607 llvm_unreachable("ELF doesn't support this directive");
610 void MCELFStreamer::EndCOFFSymbolDef() {
611 llvm_unreachable("ELF doesn't support this directive");
614 void MCELFStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
615 uint64_t Size, unsigned ByteAlignment) {
616 llvm_unreachable("ELF doesn't support this directive");
619 void MCELFStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
620 uint64_t Size, unsigned ByteAlignment) {
621 llvm_unreachable("ELF doesn't support this directive");