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/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"
36 inline void MCELFStreamer::SetSection(StringRef Section, unsigned Type,
37 unsigned Flags, SectionKind Kind) {
38 SwitchSection(getContext().getELFSection(Section, Type, Flags, Kind));
41 inline void MCELFStreamer::SetSectionData() {
44 ELF::SHF_WRITE | ELF::SHF_ALLOC,
45 SectionKind::getDataRel());
46 EmitCodeAlignment(4, 0);
49 inline void MCELFStreamer::SetSectionText() {
52 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC,
53 SectionKind::getText());
54 EmitCodeAlignment(4, 0);
57 inline void MCELFStreamer::SetSectionBss() {
60 ELF::SHF_WRITE | ELF::SHF_ALLOC,
61 SectionKind::getBSS());
62 EmitCodeAlignment(4, 0);
65 MCELFStreamer::~MCELFStreamer() {
68 void MCELFStreamer::InitSections() {
69 // This emulates the same behavior of GNU as. This makes it easier
70 // to compare the output as the major sections are in the same order.
77 void MCELFStreamer::EmitLabel(MCSymbol *Symbol) {
78 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
80 MCObjectStreamer::EmitLabel(Symbol);
82 const MCSectionELF &Section =
83 static_cast<const MCSectionELF&>(Symbol->getSection());
84 MCSymbolData &SD = getAssembler().getSymbolData(*Symbol);
85 if (Section.getFlags() & ELF::SHF_TLS)
86 MCELF::SetType(SD, ELF::STT_TLS);
89 void MCELFStreamer::EmitDebugLabel(MCSymbol *Symbol) {
93 void MCELFStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
95 case MCAF_SyntaxUnified: return; // no-op here.
96 case MCAF_Code16: return; // Change parsing mode; no-op here.
97 case MCAF_Code32: return; // Change parsing mode; no-op here.
98 case MCAF_Code64: return; // Change parsing mode; no-op here.
99 case MCAF_SubsectionsViaSymbols:
100 getAssembler().setSubsectionsViaSymbols(true);
104 llvm_unreachable("invalid assembler flag!");
107 void MCELFStreamer::ChangeSection(const MCSection *Section) {
108 MCSectionData *CurSection = getCurrentSectionData();
109 if (CurSection && CurSection->isBundleLocked())
110 report_fatal_error("Unterminated .bundle_lock when changing a section");
111 const MCSymbol *Grp = static_cast<const MCSectionELF *>(Section)->getGroup();
113 getAssembler().getOrCreateSymbolData(*Grp);
114 this->MCObjectStreamer::ChangeSection(Section);
117 void MCELFStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
118 getAssembler().getOrCreateSymbolData(*Symbol);
119 MCSymbolData &AliasSD = getAssembler().getOrCreateSymbolData(*Alias);
120 AliasSD.setFlags(AliasSD.getFlags() | ELF_Other_Weakref);
121 const MCExpr *Value = MCSymbolRefExpr::Create(Symbol, getContext());
122 Alias->setVariableValue(Value);
125 void MCELFStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
126 MCSymbolAttr Attribute) {
127 // Indirect symbols are handled differently, to match how 'as' handles
128 // them. This makes writing matching .o files easier.
129 if (Attribute == MCSA_IndirectSymbol) {
130 // Note that we intentionally cannot use the symbol data here; this is
131 // important for matching the string table that 'as' generates.
132 IndirectSymbolData ISD;
134 ISD.SectionData = getCurrentSectionData();
135 getAssembler().getIndirectSymbols().push_back(ISD);
139 // Adding a symbol attribute always introduces the symbol, note that an
140 // important side effect of calling getOrCreateSymbolData here is to register
141 // the symbol with the assembler.
142 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
144 // The implementation of symbol attributes is designed to match 'as', but it
145 // leaves much to desired. It doesn't really make sense to arbitrarily add and
146 // remove flags, but 'as' allows this (in particular, see .desc).
148 // In the future it might be worth trying to make these operations more well
151 case MCSA_LazyReference:
153 case MCSA_SymbolResolver:
154 case MCSA_PrivateExtern:
155 case MCSA_WeakDefinition:
156 case MCSA_WeakDefAutoPrivate:
158 case MCSA_IndirectSymbol:
159 llvm_unreachable("Invalid symbol attribute for ELF!");
161 case MCSA_NoDeadStrip:
162 case MCSA_ELF_TypeGnuUniqueObject:
167 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
168 SD.setExternal(true);
169 BindingExplicitlySet.insert(Symbol);
172 case MCSA_WeakReference:
174 MCELF::SetBinding(SD, ELF::STB_WEAK);
175 SD.setExternal(true);
176 BindingExplicitlySet.insert(Symbol);
180 MCELF::SetBinding(SD, ELF::STB_LOCAL);
181 SD.setExternal(false);
182 BindingExplicitlySet.insert(Symbol);
185 case MCSA_ELF_TypeFunction:
186 MCELF::SetType(SD, ELF::STT_FUNC);
189 case MCSA_ELF_TypeIndFunction:
190 MCELF::SetType(SD, ELF::STT_GNU_IFUNC);
193 case MCSA_ELF_TypeObject:
194 MCELF::SetType(SD, ELF::STT_OBJECT);
197 case MCSA_ELF_TypeTLS:
198 MCELF::SetType(SD, ELF::STT_TLS);
201 case MCSA_ELF_TypeCommon:
202 MCELF::SetType(SD, ELF::STT_COMMON);
205 case MCSA_ELF_TypeNoType:
206 MCELF::SetType(SD, ELF::STT_NOTYPE);
210 MCELF::SetVisibility(SD, ELF::STV_PROTECTED);
214 MCELF::SetVisibility(SD, ELF::STV_HIDDEN);
218 MCELF::SetVisibility(SD, ELF::STV_INTERNAL);
223 void MCELFStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
224 unsigned ByteAlignment) {
225 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
227 if (!BindingExplicitlySet.count(Symbol)) {
228 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
229 SD.setExternal(true);
232 MCELF::SetType(SD, ELF::STT_OBJECT);
234 if (MCELF::GetBinding(SD) == ELF_STB_Local) {
235 const MCSection *Section = getAssembler().getContext().getELFSection(".bss",
239 SectionKind::getBSS());
240 Symbol->setSection(*Section);
242 struct LocalCommon L = {&SD, Size, ByteAlignment};
243 LocalCommons.push_back(L);
245 SD.setCommon(Size, ByteAlignment);
248 SD.setSize(MCConstantExpr::Create(Size, getContext()));
251 void MCELFStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
252 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
256 void MCELFStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
257 unsigned ByteAlignment) {
258 // FIXME: Should this be caught and done earlier?
259 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
260 MCELF::SetBinding(SD, ELF::STB_LOCAL);
261 SD.setExternal(false);
262 BindingExplicitlySet.insert(Symbol);
263 EmitCommonSymbol(Symbol, Size, ByteAlignment);
266 void MCELFStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
267 unsigned AddrSpace) {
268 if (getCurrentSectionData()->isBundleLocked())
269 report_fatal_error("Emitting values inside a locked bundle is forbidden");
270 fixSymbolsInTLSFixups(Value);
271 MCObjectStreamer::EmitValueImpl(Value, Size, AddrSpace);
274 void MCELFStreamer::EmitValueToAlignment(unsigned ByteAlignment,
277 unsigned MaxBytesToEmit) {
278 if (getCurrentSectionData()->isBundleLocked())
279 report_fatal_error("Emitting values inside a locked bundle is forbidden");
280 MCObjectStreamer::EmitValueToAlignment(ByteAlignment, Value,
281 ValueSize, MaxBytesToEmit);
285 // Add a symbol for the file name of this module. This is the second
286 // entry in the module's symbol table (the first being the null symbol).
287 void MCELFStreamer::EmitFileDirective(StringRef Filename) {
288 MCSymbol *Symbol = getAssembler().getContext().GetOrCreateSymbol(Filename);
289 Symbol->setSection(*getCurrentSection());
290 Symbol->setAbsolute();
292 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
294 SD.setFlags(ELF_STT_File | ELF_STB_Local | ELF_STV_Default);
297 void MCELFStreamer::fixSymbolsInTLSFixups(const MCExpr *expr) {
298 switch (expr->getKind()) {
299 case MCExpr::Target: llvm_unreachable("Can't handle target exprs yet!");
300 case MCExpr::Constant:
303 case MCExpr::Binary: {
304 const MCBinaryExpr *be = cast<MCBinaryExpr>(expr);
305 fixSymbolsInTLSFixups(be->getLHS());
306 fixSymbolsInTLSFixups(be->getRHS());
310 case MCExpr::SymbolRef: {
311 const MCSymbolRefExpr &symRef = *cast<MCSymbolRefExpr>(expr);
312 switch (symRef.getKind()) {
315 case MCSymbolRefExpr::VK_GOTTPOFF:
316 case MCSymbolRefExpr::VK_INDNTPOFF:
317 case MCSymbolRefExpr::VK_NTPOFF:
318 case MCSymbolRefExpr::VK_GOTNTPOFF:
319 case MCSymbolRefExpr::VK_TLSGD:
320 case MCSymbolRefExpr::VK_TLSLD:
321 case MCSymbolRefExpr::VK_TLSLDM:
322 case MCSymbolRefExpr::VK_TPOFF:
323 case MCSymbolRefExpr::VK_DTPOFF:
324 case MCSymbolRefExpr::VK_ARM_TLSGD:
325 case MCSymbolRefExpr::VK_ARM_TPOFF:
326 case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
327 case MCSymbolRefExpr::VK_Mips_TLSGD:
328 case MCSymbolRefExpr::VK_Mips_GOTTPREL:
329 case MCSymbolRefExpr::VK_Mips_TPREL_HI:
330 case MCSymbolRefExpr::VK_Mips_TPREL_LO:
333 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(symRef.getSymbol());
334 MCELF::SetType(SD, ELF::STT_TLS);
339 fixSymbolsInTLSFixups(cast<MCUnaryExpr>(expr)->getSubExpr());
344 void MCELFStreamer::EmitInstToFragment(const MCInst &Inst) {
345 this->MCObjectStreamer::EmitInstToFragment(Inst);
346 MCRelaxableFragment &F = *cast<MCRelaxableFragment>(getCurrentFragment());
348 for (unsigned i = 0, e = F.getFixups().size(); i != e; ++i)
349 fixSymbolsInTLSFixups(F.getFixups()[i].getValue());
352 void MCELFStreamer::EmitInstToData(const MCInst &Inst) {
353 MCAssembler &Assembler = getAssembler();
354 SmallVector<MCFixup, 4> Fixups;
355 SmallString<256> Code;
356 raw_svector_ostream VecOS(Code);
357 Assembler.getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
360 for (unsigned i = 0, e = Fixups.size(); i != e; ++i)
361 fixSymbolsInTLSFixups(Fixups[i].getValue());
363 // There are several possibilities here:
365 // If bundling is disabled, append the encoded instruction to the current data
366 // fragment (or create a new such fragment if the current fragment is not a
369 // If bundling is enabled:
370 // - If we're not in a bundle-locked group, emit the instruction into a data
371 // fragment of its own.
372 // - If we're in a bundle-locked group, append the instruction to the current
373 // data fragment because we want all the instructions in a group to get into
374 // the same fragment. Be careful not to do that for the first instruction in
375 // the group, though.
378 if (Assembler.isBundlingEnabled()) {
379 MCSectionData *SD = getCurrentSectionData();
380 if (SD->isBundleLocked() && !SD->isBundleGroupBeforeFirstInst())
381 DF = getOrCreateDataFragment();
383 DF = new MCDataFragment(SD);
384 if (SD->getBundleLockState() == MCSectionData::BundleLockedAlignToEnd) {
385 // If this is a new fragment created for a bundle-locked group, and the
386 // group was marked as "align_to_end", set a flag in the fragment.
387 DF->setAlignToBundleEnd(true);
391 // We're now emitting an instruction in a bundle group, so this flag has
393 SD->setBundleGroupBeforeFirstInst(false);
395 DF = getOrCreateDataFragment();
398 // Add the fixups and data.
399 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
400 Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
401 DF->getFixups().push_back(Fixups[i]);
403 DF->setHasInstructions(true);
404 DF->getContents().append(Code.begin(), Code.end());
407 void MCELFStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
408 assert(AlignPow2 <= 30 && "Invalid bundle alignment");
409 MCAssembler &Assembler = getAssembler();
410 if (Assembler.getBundleAlignSize() == 0 && AlignPow2 > 0)
411 Assembler.setBundleAlignSize(1 << AlignPow2);
413 report_fatal_error(".bundle_align_mode should be only set once per file");
416 void MCELFStreamer::EmitBundleLock(bool AlignToEnd) {
417 MCSectionData *SD = getCurrentSectionData();
421 if (!getAssembler().isBundlingEnabled())
422 report_fatal_error(".bundle_lock forbidden when bundling is disabled");
423 else if (SD->isBundleLocked())
424 report_fatal_error("Nesting of .bundle_lock is forbidden");
426 SD->setBundleLockState(AlignToEnd ? MCSectionData::BundleLockedAlignToEnd :
427 MCSectionData::BundleLocked);
428 SD->setBundleGroupBeforeFirstInst(true);
431 void MCELFStreamer::EmitBundleUnlock() {
432 MCSectionData *SD = getCurrentSectionData();
435 if (!getAssembler().isBundlingEnabled())
436 report_fatal_error(".bundle_unlock forbidden when bundling is disabled");
437 else if (!SD->isBundleLocked())
438 report_fatal_error(".bundle_unlock without matching lock");
439 else if (SD->isBundleGroupBeforeFirstInst())
440 report_fatal_error("Empty bundle-locked group is forbidden");
442 SD->setBundleLockState(MCSectionData::NotBundleLocked);
445 void MCELFStreamer::FinishImpl() {
448 for (std::vector<LocalCommon>::const_iterator i = LocalCommons.begin(),
449 e = LocalCommons.end();
451 MCSymbolData *SD = i->SD;
452 uint64_t Size = i->Size;
453 unsigned ByteAlignment = i->ByteAlignment;
454 const MCSymbol &Symbol = SD->getSymbol();
455 const MCSection &Section = Symbol.getSection();
457 MCSectionData &SectData = getAssembler().getOrCreateSectionData(Section);
458 new MCAlignFragment(ByteAlignment, 0, 1, ByteAlignment, &SectData);
460 MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
463 // Update the maximum alignment of the section if necessary.
464 if (ByteAlignment > SectData.getAlignment())
465 SectData.setAlignment(ByteAlignment);
468 this->MCObjectStreamer::FinishImpl();
470 void MCELFStreamer::EmitTCEntry(const MCSymbol &S) {
471 // Creates a R_PPC64_TOC relocation
472 MCObjectStreamer::EmitSymbolValue(&S, 8, 0);
475 MCStreamer *llvm::createELFStreamer(MCContext &Context, MCAsmBackend &MAB,
476 raw_ostream &OS, MCCodeEmitter *CE,
477 bool RelaxAll, bool NoExecStack) {
478 MCELFStreamer *S = new MCELFStreamer(Context, MAB, OS, CE);
480 S->getAssembler().setRelaxAll(true);
482 S->getAssembler().setNoExecStack(true);
486 void MCELFStreamer::EmitThumbFunc(MCSymbol *Func) {
487 llvm_unreachable("Generic ELF doesn't support this directive");
490 void MCELFStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
491 llvm_unreachable("ELF doesn't support this directive");
494 void MCELFStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
495 llvm_unreachable("ELF doesn't support this directive");
498 void MCELFStreamer::EmitCOFFSymbolStorageClass(int StorageClass) {
499 llvm_unreachable("ELF doesn't support this directive");
502 void MCELFStreamer::EmitCOFFSymbolType(int Type) {
503 llvm_unreachable("ELF doesn't support this directive");
506 void MCELFStreamer::EndCOFFSymbolDef() {
507 llvm_unreachable("ELF doesn't support this directive");
510 void MCELFStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
511 uint64_t Size, unsigned ByteAlignment) {
512 llvm_unreachable("ELF doesn't support this directive");
515 void MCELFStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
516 uint64_t Size, unsigned ByteAlignment) {
517 llvm_unreachable("ELF doesn't support this directive");