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/STLExtras.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/MC/MCAsmBackend.h"
18 #include "llvm/MC/MCAssembler.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/MCObjectFileInfo.h"
26 #include "llvm/MC/MCObjectStreamer.h"
27 #include "llvm/MC/MCSection.h"
28 #include "llvm/MC/MCSectionELF.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/MC/MCValue.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ELF.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
38 MCELFStreamer::~MCELFStreamer() {
41 void MCELFStreamer::InitSections() {
42 // This emulates the same behavior of GNU as. This makes it easier
43 // to compare the output as the major sections are in the same order.
44 SwitchSection(getContext().getObjectFileInfo()->getTextSection());
47 SwitchSection(getContext().getObjectFileInfo()->getDataSection());
50 SwitchSection(getContext().getObjectFileInfo()->getBSSSection());
53 SwitchSection(getContext().getObjectFileInfo()->getTextSection());
56 void MCELFStreamer::EmitLabel(MCSymbol *Symbol) {
57 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
59 MCObjectStreamer::EmitLabel(Symbol);
61 const MCSectionELF &Section =
62 static_cast<const MCSectionELF&>(Symbol->getSection());
63 MCSymbolData &SD = getAssembler().getSymbolData(*Symbol);
64 if (Section.getFlags() & ELF::SHF_TLS)
65 MCELF::SetType(SD, ELF::STT_TLS);
68 void MCELFStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
69 // Let the target do whatever target specific stuff it needs to do.
70 getAssembler().getBackend().handleAssemblerFlag(Flag);
71 // Do any generic stuff we need to do.
73 case MCAF_SyntaxUnified: return; // no-op here.
74 case MCAF_Code16: return; // Change parsing mode; no-op here.
75 case MCAF_Code32: return; // Change parsing mode; no-op here.
76 case MCAF_Code64: return; // Change parsing mode; no-op here.
77 case MCAF_SubsectionsViaSymbols:
78 getAssembler().setSubsectionsViaSymbols(true);
82 llvm_unreachable("invalid assembler flag!");
85 void MCELFStreamer::ChangeSection(const MCSection *Section,
86 const MCExpr *Subsection) {
87 MCSectionData *CurSection = getCurrentSectionData();
88 if (CurSection && CurSection->isBundleLocked())
89 report_fatal_error("Unterminated .bundle_lock when changing a section");
90 const MCSymbol *Grp = static_cast<const MCSectionELF *>(Section)->getGroup();
92 getAssembler().getOrCreateSymbolData(*Grp);
93 this->MCObjectStreamer::ChangeSection(Section, Subsection);
96 void MCELFStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
97 getAssembler().getOrCreateSymbolData(*Symbol);
98 const MCExpr *Value = MCSymbolRefExpr::Create(
99 Symbol, MCSymbolRefExpr::VK_WEAKREF, getContext());
100 Alias->setVariableValue(Value);
103 // When GNU as encounters more than one .type declaration for an object it seems
104 // to use a mechanism similar to the one below to decide which type is actually
105 // used in the object file. The greater of T1 and T2 is selected based on the
106 // following ordering:
107 // STT_NOTYPE < STT_OBJECT < STT_FUNC < STT_GNU_IFUNC < STT_TLS < anything else
108 // If neither T1 < T2 nor T2 < T1 according to this ordering, use T2 (the user
110 static unsigned CombineSymbolTypes(unsigned T1, unsigned T2) {
111 unsigned TypeOrdering[] = {ELF::STT_NOTYPE, ELF::STT_OBJECT, ELF::STT_FUNC,
112 ELF::STT_GNU_IFUNC, ELF::STT_TLS};
113 for (unsigned i = 0; i != array_lengthof(TypeOrdering); ++i) {
114 if (T1 == TypeOrdering[i])
116 if (T2 == TypeOrdering[i])
123 bool MCELFStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
124 MCSymbolAttr Attribute) {
125 // Indirect symbols are handled differently, to match how 'as' handles
126 // them. This makes writing matching .o files easier.
127 if (Attribute == MCSA_IndirectSymbol) {
128 // Note that we intentionally cannot use the symbol data here; this is
129 // important for matching the string table that 'as' generates.
130 IndirectSymbolData ISD;
132 ISD.SectionData = getCurrentSectionData();
133 getAssembler().getIndirectSymbols().push_back(ISD);
137 // Adding a symbol attribute always introduces the symbol, note that an
138 // important side effect of calling getOrCreateSymbolData here is to register
139 // the symbol with the assembler.
140 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
142 // The implementation of symbol attributes is designed to match 'as', but it
143 // leaves much to desired. It doesn't really make sense to arbitrarily add and
144 // remove flags, but 'as' allows this (in particular, see .desc).
146 // In the future it might be worth trying to make these operations more well
149 case MCSA_LazyReference:
151 case MCSA_SymbolResolver:
152 case MCSA_PrivateExtern:
153 case MCSA_WeakDefinition:
154 case MCSA_WeakDefAutoPrivate:
156 case MCSA_IndirectSymbol:
159 case MCSA_NoDeadStrip:
160 case MCSA_ELF_TypeGnuUniqueObject:
165 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
166 SD.setExternal(true);
167 BindingExplicitlySet.insert(Symbol);
170 case MCSA_WeakReference:
172 MCELF::SetBinding(SD, ELF::STB_WEAK);
173 SD.setExternal(true);
174 BindingExplicitlySet.insert(Symbol);
178 MCELF::SetBinding(SD, ELF::STB_LOCAL);
179 SD.setExternal(false);
180 BindingExplicitlySet.insert(Symbol);
183 case MCSA_ELF_TypeFunction:
184 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
188 case MCSA_ELF_TypeIndFunction:
189 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
190 ELF::STT_GNU_IFUNC));
193 case MCSA_ELF_TypeObject:
194 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
198 case MCSA_ELF_TypeTLS:
199 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
203 case MCSA_ELF_TypeCommon:
204 // TODO: Emit these as a common symbol.
205 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
209 case MCSA_ELF_TypeNoType:
210 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
215 MCELF::SetVisibility(SD, ELF::STV_PROTECTED);
219 MCELF::SetVisibility(SD, ELF::STV_HIDDEN);
223 MCELF::SetVisibility(SD, ELF::STV_INTERNAL);
230 void MCELFStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
231 unsigned ByteAlignment) {
232 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
234 if (!BindingExplicitlySet.count(Symbol)) {
235 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
236 SD.setExternal(true);
239 MCELF::SetType(SD, ELF::STT_OBJECT);
241 if (MCELF::GetBinding(SD) == ELF_STB_Local) {
242 const MCSection *Section = getAssembler().getContext().getELFSection(".bss",
246 SectionKind::getBSS());
248 AssignSection(Symbol, Section);
250 struct LocalCommon L = {&SD, Size, ByteAlignment};
251 LocalCommons.push_back(L);
253 SD.setCommon(Size, ByteAlignment);
256 SD.setSize(MCConstantExpr::Create(Size, getContext()));
259 void MCELFStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
260 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
264 void MCELFStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
265 unsigned ByteAlignment) {
266 // FIXME: Should this be caught and done earlier?
267 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
268 MCELF::SetBinding(SD, ELF::STB_LOCAL);
269 SD.setExternal(false);
270 BindingExplicitlySet.insert(Symbol);
271 EmitCommonSymbol(Symbol, Size, ByteAlignment);
274 void MCELFStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
276 if (getCurrentSectionData()->isBundleLocked())
277 report_fatal_error("Emitting values inside a locked bundle is forbidden");
278 fixSymbolsInTLSFixups(Value);
279 MCObjectStreamer::EmitValueImpl(Value, Size, Loc);
282 void MCELFStreamer::EmitValueToAlignment(unsigned ByteAlignment,
285 unsigned MaxBytesToEmit) {
286 if (getCurrentSectionData()->isBundleLocked())
287 report_fatal_error("Emitting values inside a locked bundle is forbidden");
288 MCObjectStreamer::EmitValueToAlignment(ByteAlignment, Value,
289 ValueSize, MaxBytesToEmit);
292 // Add a symbol for the file name of this module. They start after the
293 // null symbol and don't count as normal symbol, i.e. a non-STT_FILE symbol
294 // with the same name may appear.
295 void MCELFStreamer::EmitFileDirective(StringRef Filename) {
296 getAssembler().addFileName(Filename);
299 void MCELFStreamer::EmitIdent(StringRef IdentString) {
300 const MCSection *Comment = getAssembler().getContext().getELFSection(
301 ".comment", ELF::SHT_PROGBITS, ELF::SHF_MERGE | ELF::SHF_STRINGS,
302 SectionKind::getReadOnly(), 1, "");
304 SwitchSection(Comment);
309 EmitBytes(IdentString);
314 void MCELFStreamer::fixSymbolsInTLSFixups(const MCExpr *expr) {
315 switch (expr->getKind()) {
317 cast<MCTargetExpr>(expr)->fixELFSymbolsInTLSFixups(getAssembler());
319 case MCExpr::Constant:
322 case MCExpr::Binary: {
323 const MCBinaryExpr *be = cast<MCBinaryExpr>(expr);
324 fixSymbolsInTLSFixups(be->getLHS());
325 fixSymbolsInTLSFixups(be->getRHS());
329 case MCExpr::SymbolRef: {
330 const MCSymbolRefExpr &symRef = *cast<MCSymbolRefExpr>(expr);
331 switch (symRef.getKind()) {
334 case MCSymbolRefExpr::VK_GOTTPOFF:
335 case MCSymbolRefExpr::VK_INDNTPOFF:
336 case MCSymbolRefExpr::VK_NTPOFF:
337 case MCSymbolRefExpr::VK_GOTNTPOFF:
338 case MCSymbolRefExpr::VK_TLSGD:
339 case MCSymbolRefExpr::VK_TLSLD:
340 case MCSymbolRefExpr::VK_TLSLDM:
341 case MCSymbolRefExpr::VK_TPOFF:
342 case MCSymbolRefExpr::VK_DTPOFF:
343 case MCSymbolRefExpr::VK_Mips_TLSGD:
344 case MCSymbolRefExpr::VK_Mips_GOTTPREL:
345 case MCSymbolRefExpr::VK_Mips_TPREL_HI:
346 case MCSymbolRefExpr::VK_Mips_TPREL_LO:
347 case MCSymbolRefExpr::VK_PPC_DTPMOD:
348 case MCSymbolRefExpr::VK_PPC_TPREL:
349 case MCSymbolRefExpr::VK_PPC_TPREL_LO:
350 case MCSymbolRefExpr::VK_PPC_TPREL_HI:
351 case MCSymbolRefExpr::VK_PPC_TPREL_HA:
352 case MCSymbolRefExpr::VK_PPC_TPREL_HIGHER:
353 case MCSymbolRefExpr::VK_PPC_TPREL_HIGHERA:
354 case MCSymbolRefExpr::VK_PPC_TPREL_HIGHEST:
355 case MCSymbolRefExpr::VK_PPC_TPREL_HIGHESTA:
356 case MCSymbolRefExpr::VK_PPC_DTPREL:
357 case MCSymbolRefExpr::VK_PPC_DTPREL_LO:
358 case MCSymbolRefExpr::VK_PPC_DTPREL_HI:
359 case MCSymbolRefExpr::VK_PPC_DTPREL_HA:
360 case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHER:
361 case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHERA:
362 case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHEST:
363 case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHESTA:
364 case MCSymbolRefExpr::VK_PPC_GOT_TPREL:
365 case MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO:
366 case MCSymbolRefExpr::VK_PPC_GOT_TPREL_HI:
367 case MCSymbolRefExpr::VK_PPC_GOT_TPREL_HA:
368 case MCSymbolRefExpr::VK_PPC_GOT_DTPREL:
369 case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_LO:
370 case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_HI:
371 case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_HA:
372 case MCSymbolRefExpr::VK_PPC_TLS:
373 case MCSymbolRefExpr::VK_PPC_GOT_TLSGD:
374 case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO:
375 case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HI:
376 case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HA:
377 case MCSymbolRefExpr::VK_PPC_TLSGD:
378 case MCSymbolRefExpr::VK_PPC_GOT_TLSLD:
379 case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO:
380 case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HI:
381 case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HA:
382 case MCSymbolRefExpr::VK_PPC_TLSLD:
385 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(symRef.getSymbol());
386 MCELF::SetType(SD, ELF::STT_TLS);
391 fixSymbolsInTLSFixups(cast<MCUnaryExpr>(expr)->getSubExpr());
396 void MCELFStreamer::EmitInstToFragment(const MCInst &Inst,
397 const MCSubtargetInfo &STI) {
398 this->MCObjectStreamer::EmitInstToFragment(Inst, STI);
399 MCRelaxableFragment &F = *cast<MCRelaxableFragment>(getCurrentFragment());
401 for (unsigned i = 0, e = F.getFixups().size(); i != e; ++i)
402 fixSymbolsInTLSFixups(F.getFixups()[i].getValue());
405 void MCELFStreamer::EmitInstToData(const MCInst &Inst,
406 const MCSubtargetInfo &STI) {
407 MCAssembler &Assembler = getAssembler();
408 SmallVector<MCFixup, 4> Fixups;
409 SmallString<256> Code;
410 raw_svector_ostream VecOS(Code);
411 Assembler.getEmitter().EncodeInstruction(Inst, VecOS, Fixups, STI);
414 for (unsigned i = 0, e = Fixups.size(); i != e; ++i)
415 fixSymbolsInTLSFixups(Fixups[i].getValue());
417 // There are several possibilities here:
419 // If bundling is disabled, append the encoded instruction to the current data
420 // fragment (or create a new such fragment if the current fragment is not a
423 // If bundling is enabled:
424 // - If we're not in a bundle-locked group, emit the instruction into a
425 // fragment of its own. If there are no fixups registered for the
426 // instruction, emit a MCCompactEncodedInstFragment. Otherwise, emit a
428 // - If we're in a bundle-locked group, append the instruction to the current
429 // data fragment because we want all the instructions in a group to get into
430 // the same fragment. Be careful not to do that for the first instruction in
431 // the group, though.
434 if (Assembler.isBundlingEnabled()) {
435 MCSectionData *SD = getCurrentSectionData();
436 if (SD->isBundleLocked() && !SD->isBundleGroupBeforeFirstInst())
437 // If we are bundle-locked, we re-use the current fragment.
438 // The bundle-locking directive ensures this is a new data fragment.
439 DF = cast<MCDataFragment>(getCurrentFragment());
440 else if (!SD->isBundleLocked() && Fixups.size() == 0) {
441 // Optimize memory usage by emitting the instruction to a
442 // MCCompactEncodedInstFragment when not in a bundle-locked group and
443 // there are no fixups registered.
444 MCCompactEncodedInstFragment *CEIF = new MCCompactEncodedInstFragment();
446 CEIF->getContents().append(Code.begin(), Code.end());
449 DF = new MCDataFragment();
451 if (SD->getBundleLockState() == MCSectionData::BundleLockedAlignToEnd) {
452 // If this is a new fragment created for a bundle-locked group, and the
453 // group was marked as "align_to_end", set a flag in the fragment.
454 DF->setAlignToBundleEnd(true);
458 // We're now emitting an instruction in a bundle group, so this flag has
460 SD->setBundleGroupBeforeFirstInst(false);
462 DF = getOrCreateDataFragment();
465 // Add the fixups and data.
466 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
467 Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
468 DF->getFixups().push_back(Fixups[i]);
470 DF->setHasInstructions(true);
471 DF->getContents().append(Code.begin(), Code.end());
474 void MCELFStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
475 assert(AlignPow2 <= 30 && "Invalid bundle alignment");
476 MCAssembler &Assembler = getAssembler();
477 if (Assembler.getBundleAlignSize() == 0 && AlignPow2 > 0)
478 Assembler.setBundleAlignSize(1 << AlignPow2);
480 report_fatal_error(".bundle_align_mode should be only set once per file");
483 void MCELFStreamer::EmitBundleLock(bool AlignToEnd) {
484 MCSectionData *SD = getCurrentSectionData();
488 if (!getAssembler().isBundlingEnabled())
489 report_fatal_error(".bundle_lock forbidden when bundling is disabled");
490 else if (SD->isBundleLocked())
491 report_fatal_error("Nesting of .bundle_lock is forbidden");
493 SD->setBundleLockState(AlignToEnd ? MCSectionData::BundleLockedAlignToEnd :
494 MCSectionData::BundleLocked);
495 SD->setBundleGroupBeforeFirstInst(true);
498 void MCELFStreamer::EmitBundleUnlock() {
499 MCSectionData *SD = getCurrentSectionData();
502 if (!getAssembler().isBundlingEnabled())
503 report_fatal_error(".bundle_unlock forbidden when bundling is disabled");
504 else if (!SD->isBundleLocked())
505 report_fatal_error(".bundle_unlock without matching lock");
506 else if (SD->isBundleGroupBeforeFirstInst())
507 report_fatal_error("Empty bundle-locked group is forbidden");
509 SD->setBundleLockState(MCSectionData::NotBundleLocked);
512 void MCELFStreamer::Flush() {
513 for (std::vector<LocalCommon>::const_iterator i = LocalCommons.begin(),
514 e = LocalCommons.end();
516 MCSymbolData *SD = i->SD;
517 uint64_t Size = i->Size;
518 unsigned ByteAlignment = i->ByteAlignment;
519 const MCSymbol &Symbol = SD->getSymbol();
520 const MCSection &Section = Symbol.getSection();
522 MCSectionData &SectData = getAssembler().getOrCreateSectionData(Section);
523 new MCAlignFragment(ByteAlignment, 0, 1, ByteAlignment, &SectData);
525 MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
528 // Update the maximum alignment of the section if necessary.
529 if (ByteAlignment > SectData.getAlignment())
530 SectData.setAlignment(ByteAlignment);
533 LocalCommons.clear();
536 void MCELFStreamer::FinishImpl() {
541 this->MCObjectStreamer::FinishImpl();
544 MCStreamer *llvm::createELFStreamer(MCContext &Context, MCAsmBackend &MAB,
545 raw_ostream &OS, MCCodeEmitter *CE,
546 bool RelaxAll, bool NoExecStack) {
547 MCELFStreamer *S = new MCELFStreamer(Context, MAB, OS, CE);
549 S->getAssembler().setRelaxAll(true);
551 S->getAssembler().setNoExecStack(true);
555 void MCELFStreamer::EmitThumbFunc(MCSymbol *Func) {
556 llvm_unreachable("Generic ELF doesn't support this directive");
559 void MCELFStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
560 llvm_unreachable("ELF doesn't support this directive");
563 void MCELFStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
564 llvm_unreachable("ELF doesn't support this directive");
567 void MCELFStreamer::EmitCOFFSymbolStorageClass(int StorageClass) {
568 llvm_unreachable("ELF doesn't support this directive");
571 void MCELFStreamer::EmitCOFFSymbolType(int Type) {
572 llvm_unreachable("ELF doesn't support this directive");
575 void MCELFStreamer::EndCOFFSymbolDef() {
576 llvm_unreachable("ELF doesn't support this directive");
579 void MCELFStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
580 uint64_t Size, unsigned ByteAlignment) {
581 llvm_unreachable("ELF doesn't support this directive");
584 void MCELFStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
585 uint64_t Size, unsigned ByteAlignment) {
586 llvm_unreachable("ELF doesn't support this directive");