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::EmitDebugLabel(MCSymbol *Symbol) {
72 void MCELFStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
73 // Let the target do whatever target specific stuff it needs to do.
74 getAssembler().getBackend().handleAssemblerFlag(Flag);
75 // Do any generic stuff we need to do.
77 case MCAF_SyntaxUnified: return; // no-op here.
78 case MCAF_Code16: return; // Change parsing mode; no-op here.
79 case MCAF_Code32: return; // Change parsing mode; no-op here.
80 case MCAF_Code64: return; // Change parsing mode; no-op here.
81 case MCAF_SubsectionsViaSymbols:
82 getAssembler().setSubsectionsViaSymbols(true);
86 llvm_unreachable("invalid assembler flag!");
89 void MCELFStreamer::ChangeSection(const MCSection *Section,
90 const MCExpr *Subsection) {
91 MCSectionData *CurSection = getCurrentSectionData();
92 if (CurSection && CurSection->isBundleLocked())
93 report_fatal_error("Unterminated .bundle_lock when changing a section");
94 const MCSymbol *Grp = static_cast<const MCSectionELF *>(Section)->getGroup();
96 getAssembler().getOrCreateSymbolData(*Grp);
97 this->MCObjectStreamer::ChangeSection(Section, Subsection);
100 void MCELFStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
101 getAssembler().getOrCreateSymbolData(*Symbol);
102 const MCExpr *Value = MCSymbolRefExpr::Create(
103 Symbol, MCSymbolRefExpr::VK_WEAKREF, getContext());
104 Alias->setVariableValue(Value);
107 // When GNU as encounters more than one .type declaration for an object it seems
108 // to use a mechanism similar to the one below to decide which type is actually
109 // used in the object file. The greater of T1 and T2 is selected based on the
110 // following ordering:
111 // STT_NOTYPE < STT_OBJECT < STT_FUNC < STT_GNU_IFUNC < STT_TLS < anything else
112 // If neither T1 < T2 nor T2 < T1 according to this ordering, use T2 (the user
114 static unsigned CombineSymbolTypes(unsigned T1, unsigned T2) {
115 unsigned TypeOrdering[] = {ELF::STT_NOTYPE, ELF::STT_OBJECT, ELF::STT_FUNC,
116 ELF::STT_GNU_IFUNC, ELF::STT_TLS};
117 for (unsigned i = 0; i != array_lengthof(TypeOrdering); ++i) {
118 if (T1 == TypeOrdering[i])
120 if (T2 == TypeOrdering[i])
127 bool MCELFStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
128 MCSymbolAttr Attribute) {
129 // Indirect symbols are handled differently, to match how 'as' handles
130 // them. This makes writing matching .o files easier.
131 if (Attribute == MCSA_IndirectSymbol) {
132 // Note that we intentionally cannot use the symbol data here; this is
133 // important for matching the string table that 'as' generates.
134 IndirectSymbolData ISD;
136 ISD.SectionData = getCurrentSectionData();
137 getAssembler().getIndirectSymbols().push_back(ISD);
141 // Adding a symbol attribute always introduces the symbol, note that an
142 // important side effect of calling getOrCreateSymbolData here is to register
143 // the symbol with the assembler.
144 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
146 // The implementation of symbol attributes is designed to match 'as', but it
147 // leaves much to desired. It doesn't really make sense to arbitrarily add and
148 // remove flags, but 'as' allows this (in particular, see .desc).
150 // In the future it might be worth trying to make these operations more well
153 case MCSA_LazyReference:
155 case MCSA_SymbolResolver:
156 case MCSA_PrivateExtern:
157 case MCSA_WeakDefinition:
158 case MCSA_WeakDefAutoPrivate:
160 case MCSA_IndirectSymbol:
163 case MCSA_NoDeadStrip:
164 case MCSA_ELF_TypeGnuUniqueObject:
169 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
170 SD.setExternal(true);
171 BindingExplicitlySet.insert(Symbol);
174 case MCSA_WeakReference:
176 MCELF::SetBinding(SD, ELF::STB_WEAK);
177 SD.setExternal(true);
178 BindingExplicitlySet.insert(Symbol);
182 MCELF::SetBinding(SD, ELF::STB_LOCAL);
183 SD.setExternal(false);
184 BindingExplicitlySet.insert(Symbol);
187 case MCSA_ELF_TypeFunction:
188 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
192 case MCSA_ELF_TypeIndFunction:
193 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
194 ELF::STT_GNU_IFUNC));
197 case MCSA_ELF_TypeObject:
198 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
202 case MCSA_ELF_TypeTLS:
203 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
207 case MCSA_ELF_TypeCommon:
208 // TODO: Emit these as a common symbol.
209 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
213 case MCSA_ELF_TypeNoType:
214 MCELF::SetType(SD, CombineSymbolTypes(MCELF::GetType(SD),
219 MCELF::SetVisibility(SD, ELF::STV_PROTECTED);
223 MCELF::SetVisibility(SD, ELF::STV_HIDDEN);
227 MCELF::SetVisibility(SD, ELF::STV_INTERNAL);
234 void MCELFStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
235 unsigned ByteAlignment) {
236 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
238 if (!BindingExplicitlySet.count(Symbol)) {
239 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
240 SD.setExternal(true);
243 MCELF::SetType(SD, ELF::STT_OBJECT);
245 if (MCELF::GetBinding(SD) == ELF_STB_Local) {
246 const MCSection *Section = getAssembler().getContext().getELFSection(".bss",
250 SectionKind::getBSS());
252 AssignSection(Symbol, Section);
254 struct LocalCommon L = {&SD, Size, ByteAlignment};
255 LocalCommons.push_back(L);
257 SD.setCommon(Size, ByteAlignment);
260 SD.setSize(MCConstantExpr::Create(Size, getContext()));
263 void MCELFStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
264 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
268 void MCELFStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
269 unsigned ByteAlignment) {
270 // FIXME: Should this be caught and done earlier?
271 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
272 MCELF::SetBinding(SD, ELF::STB_LOCAL);
273 SD.setExternal(false);
274 BindingExplicitlySet.insert(Symbol);
275 EmitCommonSymbol(Symbol, Size, ByteAlignment);
278 void MCELFStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size) {
279 if (getCurrentSectionData()->isBundleLocked())
280 report_fatal_error("Emitting values inside a locked bundle is forbidden");
281 fixSymbolsInTLSFixups(Value);
282 MCObjectStreamer::EmitValueImpl(Value, Size);
285 void MCELFStreamer::EmitValueToAlignment(unsigned ByteAlignment,
288 unsigned MaxBytesToEmit) {
289 if (getCurrentSectionData()->isBundleLocked())
290 report_fatal_error("Emitting values inside a locked bundle is forbidden");
291 MCObjectStreamer::EmitValueToAlignment(ByteAlignment, Value,
292 ValueSize, MaxBytesToEmit);
295 // Add a symbol for the file name of this module. They start after the
296 // null symbol and don't count as normal symbol, i.e. a non-STT_FILE symbol
297 // with the same name may appear.
298 void MCELFStreamer::EmitFileDirective(StringRef Filename) {
299 getAssembler().addFileName(Filename);
302 void MCELFStreamer::EmitIdent(StringRef IdentString) {
303 const MCSection *Comment = getAssembler().getContext().getELFSection(
304 ".comment", ELF::SHT_PROGBITS, ELF::SHF_MERGE | ELF::SHF_STRINGS,
305 SectionKind::getReadOnly(), 1, "");
307 SwitchSection(Comment);
312 EmitBytes(IdentString);
317 void MCELFStreamer::fixSymbolsInTLSFixups(const MCExpr *expr) {
318 switch (expr->getKind()) {
320 cast<MCTargetExpr>(expr)->fixELFSymbolsInTLSFixups(getAssembler());
322 case MCExpr::Constant:
325 case MCExpr::Binary: {
326 const MCBinaryExpr *be = cast<MCBinaryExpr>(expr);
327 fixSymbolsInTLSFixups(be->getLHS());
328 fixSymbolsInTLSFixups(be->getRHS());
332 case MCExpr::SymbolRef: {
333 const MCSymbolRefExpr &symRef = *cast<MCSymbolRefExpr>(expr);
334 switch (symRef.getKind()) {
337 case MCSymbolRefExpr::VK_GOTTPOFF:
338 case MCSymbolRefExpr::VK_INDNTPOFF:
339 case MCSymbolRefExpr::VK_NTPOFF:
340 case MCSymbolRefExpr::VK_GOTNTPOFF:
341 case MCSymbolRefExpr::VK_TLSGD:
342 case MCSymbolRefExpr::VK_TLSLD:
343 case MCSymbolRefExpr::VK_TLSLDM:
344 case MCSymbolRefExpr::VK_TPOFF:
345 case MCSymbolRefExpr::VK_DTPOFF:
346 case MCSymbolRefExpr::VK_Mips_TLSGD:
347 case MCSymbolRefExpr::VK_Mips_GOTTPREL:
348 case MCSymbolRefExpr::VK_Mips_TPREL_HI:
349 case MCSymbolRefExpr::VK_Mips_TPREL_LO:
350 case MCSymbolRefExpr::VK_PPC_DTPMOD:
351 case MCSymbolRefExpr::VK_PPC_TPREL:
352 case MCSymbolRefExpr::VK_PPC_TPREL_LO:
353 case MCSymbolRefExpr::VK_PPC_TPREL_HI:
354 case MCSymbolRefExpr::VK_PPC_TPREL_HA:
355 case MCSymbolRefExpr::VK_PPC_TPREL_HIGHER:
356 case MCSymbolRefExpr::VK_PPC_TPREL_HIGHERA:
357 case MCSymbolRefExpr::VK_PPC_TPREL_HIGHEST:
358 case MCSymbolRefExpr::VK_PPC_TPREL_HIGHESTA:
359 case MCSymbolRefExpr::VK_PPC_DTPREL:
360 case MCSymbolRefExpr::VK_PPC_DTPREL_LO:
361 case MCSymbolRefExpr::VK_PPC_DTPREL_HI:
362 case MCSymbolRefExpr::VK_PPC_DTPREL_HA:
363 case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHER:
364 case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHERA:
365 case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHEST:
366 case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHESTA:
367 case MCSymbolRefExpr::VK_PPC_GOT_TPREL:
368 case MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO:
369 case MCSymbolRefExpr::VK_PPC_GOT_TPREL_HI:
370 case MCSymbolRefExpr::VK_PPC_GOT_TPREL_HA:
371 case MCSymbolRefExpr::VK_PPC_GOT_DTPREL:
372 case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_LO:
373 case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_HI:
374 case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_HA:
375 case MCSymbolRefExpr::VK_PPC_TLS:
376 case MCSymbolRefExpr::VK_PPC_GOT_TLSGD:
377 case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO:
378 case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HI:
379 case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HA:
380 case MCSymbolRefExpr::VK_PPC_TLSGD:
381 case MCSymbolRefExpr::VK_PPC_GOT_TLSLD:
382 case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO:
383 case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HI:
384 case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HA:
385 case MCSymbolRefExpr::VK_PPC_TLSLD:
388 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(symRef.getSymbol());
389 MCELF::SetType(SD, ELF::STT_TLS);
394 fixSymbolsInTLSFixups(cast<MCUnaryExpr>(expr)->getSubExpr());
399 void MCELFStreamer::EmitInstToFragment(const MCInst &Inst,
400 const MCSubtargetInfo &STI) {
401 this->MCObjectStreamer::EmitInstToFragment(Inst, STI);
402 MCRelaxableFragment &F = *cast<MCRelaxableFragment>(getCurrentFragment());
404 for (unsigned i = 0, e = F.getFixups().size(); i != e; ++i)
405 fixSymbolsInTLSFixups(F.getFixups()[i].getValue());
408 void MCELFStreamer::EmitInstToData(const MCInst &Inst,
409 const MCSubtargetInfo &STI) {
410 MCAssembler &Assembler = getAssembler();
411 SmallVector<MCFixup, 4> Fixups;
412 SmallString<256> Code;
413 raw_svector_ostream VecOS(Code);
414 Assembler.getEmitter().EncodeInstruction(Inst, VecOS, Fixups, STI);
417 for (unsigned i = 0, e = Fixups.size(); i != e; ++i)
418 fixSymbolsInTLSFixups(Fixups[i].getValue());
420 // There are several possibilities here:
422 // If bundling is disabled, append the encoded instruction to the current data
423 // fragment (or create a new such fragment if the current fragment is not a
426 // If bundling is enabled:
427 // - If we're not in a bundle-locked group, emit the instruction into a
428 // fragment of its own. If there are no fixups registered for the
429 // instruction, emit a MCCompactEncodedInstFragment. Otherwise, emit a
431 // - If we're in a bundle-locked group, append the instruction to the current
432 // data fragment because we want all the instructions in a group to get into
433 // the same fragment. Be careful not to do that for the first instruction in
434 // the group, though.
437 if (Assembler.isBundlingEnabled()) {
438 MCSectionData *SD = getCurrentSectionData();
439 if (SD->isBundleLocked() && !SD->isBundleGroupBeforeFirstInst())
440 // If we are bundle-locked, we re-use the current fragment.
441 // The bundle-locking directive ensures this is a new data fragment.
442 DF = cast<MCDataFragment>(getCurrentFragment());
443 else if (!SD->isBundleLocked() && Fixups.size() == 0) {
444 // Optimize memory usage by emitting the instruction to a
445 // MCCompactEncodedInstFragment when not in a bundle-locked group and
446 // there are no fixups registered.
447 MCCompactEncodedInstFragment *CEIF = new MCCompactEncodedInstFragment();
449 CEIF->getContents().append(Code.begin(), Code.end());
452 DF = new MCDataFragment();
454 if (SD->getBundleLockState() == MCSectionData::BundleLockedAlignToEnd) {
455 // If this is a new fragment created for a bundle-locked group, and the
456 // group was marked as "align_to_end", set a flag in the fragment.
457 DF->setAlignToBundleEnd(true);
461 // We're now emitting an instruction in a bundle group, so this flag has
463 SD->setBundleGroupBeforeFirstInst(false);
465 DF = getOrCreateDataFragment();
468 // Add the fixups and data.
469 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
470 Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
471 DF->getFixups().push_back(Fixups[i]);
473 DF->setHasInstructions(true);
474 DF->getContents().append(Code.begin(), Code.end());
477 void MCELFStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
478 assert(AlignPow2 <= 30 && "Invalid bundle alignment");
479 MCAssembler &Assembler = getAssembler();
480 if (Assembler.getBundleAlignSize() == 0 && AlignPow2 > 0)
481 Assembler.setBundleAlignSize(1 << AlignPow2);
483 report_fatal_error(".bundle_align_mode should be only set once per file");
486 void MCELFStreamer::EmitBundleLock(bool AlignToEnd) {
487 MCSectionData *SD = getCurrentSectionData();
491 if (!getAssembler().isBundlingEnabled())
492 report_fatal_error(".bundle_lock forbidden when bundling is disabled");
493 else if (SD->isBundleLocked())
494 report_fatal_error("Nesting of .bundle_lock is forbidden");
496 SD->setBundleLockState(AlignToEnd ? MCSectionData::BundleLockedAlignToEnd :
497 MCSectionData::BundleLocked);
498 SD->setBundleGroupBeforeFirstInst(true);
501 void MCELFStreamer::EmitBundleUnlock() {
502 MCSectionData *SD = getCurrentSectionData();
505 if (!getAssembler().isBundlingEnabled())
506 report_fatal_error(".bundle_unlock forbidden when bundling is disabled");
507 else if (!SD->isBundleLocked())
508 report_fatal_error(".bundle_unlock without matching lock");
509 else if (SD->isBundleGroupBeforeFirstInst())
510 report_fatal_error("Empty bundle-locked group is forbidden");
512 SD->setBundleLockState(MCSectionData::NotBundleLocked);
515 void MCELFStreamer::Flush() {
516 for (std::vector<LocalCommon>::const_iterator i = LocalCommons.begin(),
517 e = LocalCommons.end();
519 MCSymbolData *SD = i->SD;
520 uint64_t Size = i->Size;
521 unsigned ByteAlignment = i->ByteAlignment;
522 const MCSymbol &Symbol = SD->getSymbol();
523 const MCSection &Section = Symbol.getSection();
525 MCSectionData &SectData = getAssembler().getOrCreateSectionData(Section);
526 new MCAlignFragment(ByteAlignment, 0, 1, ByteAlignment, &SectData);
528 MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
531 // Update the maximum alignment of the section if necessary.
532 if (ByteAlignment > SectData.getAlignment())
533 SectData.setAlignment(ByteAlignment);
536 LocalCommons.clear();
539 void MCELFStreamer::FinishImpl() {
540 EmitFrames(NULL, true);
544 this->MCObjectStreamer::FinishImpl();
547 MCStreamer *llvm::createELFStreamer(MCContext &Context, MCAsmBackend &MAB,
548 raw_ostream &OS, MCCodeEmitter *CE,
549 bool RelaxAll, bool NoExecStack) {
550 MCELFStreamer *S = new MCELFStreamer(Context, MAB, OS, CE);
552 S->getAssembler().setRelaxAll(true);
554 S->getAssembler().setNoExecStack(true);
558 void MCELFStreamer::EmitThumbFunc(MCSymbol *Func) {
559 llvm_unreachable("Generic ELF doesn't support this directive");
562 MCSymbolData &MCELFStreamer::getOrCreateSymbolData(const MCSymbol *Symbol) {
563 return getAssembler().getOrCreateSymbolData(*Symbol);
566 void MCELFStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
567 llvm_unreachable("ELF doesn't support this directive");
570 void MCELFStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
571 llvm_unreachable("ELF doesn't support this directive");
574 void MCELFStreamer::EmitCOFFSymbolStorageClass(int StorageClass) {
575 llvm_unreachable("ELF doesn't support this directive");
578 void MCELFStreamer::EmitCOFFSymbolType(int Type) {
579 llvm_unreachable("ELF doesn't support this directive");
582 void MCELFStreamer::EndCOFFSymbolDef() {
583 llvm_unreachable("ELF doesn't support this directive");
586 void MCELFStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
587 uint64_t Size, unsigned ByteAlignment) {
588 llvm_unreachable("ELF doesn't support this directive");
591 void MCELFStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
592 uint64_t Size, unsigned ByteAlignment) {
593 llvm_unreachable("ELF doesn't support this directive");