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::InitToTextSection() {
72 void MCELFStreamer::InitSections() {
73 // This emulates the same behavior of GNU as. This makes it easier
74 // to compare the output as the major sections are in the same order.
81 void MCELFStreamer::EmitLabel(MCSymbol *Symbol) {
82 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
84 MCObjectStreamer::EmitLabel(Symbol);
86 const MCSectionELF &Section =
87 static_cast<const MCSectionELF&>(Symbol->getSection());
88 MCSymbolData &SD = getAssembler().getSymbolData(*Symbol);
89 if (Section.getFlags() & ELF::SHF_TLS)
90 MCELF::SetType(SD, ELF::STT_TLS);
93 void MCELFStreamer::EmitDebugLabel(MCSymbol *Symbol) {
97 void MCELFStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
99 case MCAF_SyntaxUnified: return; // no-op here.
100 case MCAF_Code16: return; // Change parsing mode; no-op here.
101 case MCAF_Code32: return; // Change parsing mode; no-op here.
102 case MCAF_Code64: return; // Change parsing mode; no-op here.
103 case MCAF_SubsectionsViaSymbols:
104 getAssembler().setSubsectionsViaSymbols(true);
108 llvm_unreachable("invalid assembler flag!");
111 void MCELFStreamer::ChangeSection(const MCSection *Section) {
112 MCSectionData *CurSection = getCurrentSectionData();
113 if (CurSection && CurSection->isBundleLocked())
114 report_fatal_error("Unterminated .bundle_lock when changing a section");
115 const MCSymbol *Grp = static_cast<const MCSectionELF *>(Section)->getGroup();
117 getAssembler().getOrCreateSymbolData(*Grp);
118 this->MCObjectStreamer::ChangeSection(Section);
121 void MCELFStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
122 getAssembler().getOrCreateSymbolData(*Symbol);
123 MCSymbolData &AliasSD = getAssembler().getOrCreateSymbolData(*Alias);
124 AliasSD.setFlags(AliasSD.getFlags() | ELF_Other_Weakref);
125 const MCExpr *Value = MCSymbolRefExpr::Create(Symbol, getContext());
126 Alias->setVariableValue(Value);
129 void MCELFStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
130 MCSymbolAttr Attribute) {
131 // Indirect symbols are handled differently, to match how 'as' handles
132 // them. This makes writing matching .o files easier.
133 if (Attribute == MCSA_IndirectSymbol) {
134 // Note that we intentionally cannot use the symbol data here; this is
135 // important for matching the string table that 'as' generates.
136 IndirectSymbolData ISD;
138 ISD.SectionData = getCurrentSectionData();
139 getAssembler().getIndirectSymbols().push_back(ISD);
143 // Adding a symbol attribute always introduces the symbol, note that an
144 // important side effect of calling getOrCreateSymbolData here is to register
145 // the symbol with the assembler.
146 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
148 // The implementation of symbol attributes is designed to match 'as', but it
149 // leaves much to desired. It doesn't really make sense to arbitrarily add and
150 // remove flags, but 'as' allows this (in particular, see .desc).
152 // In the future it might be worth trying to make these operations more well
155 case MCSA_LazyReference:
157 case MCSA_SymbolResolver:
158 case MCSA_PrivateExtern:
159 case MCSA_WeakDefinition:
160 case MCSA_WeakDefAutoPrivate:
162 case MCSA_IndirectSymbol:
163 llvm_unreachable("Invalid symbol attribute for ELF!");
165 case MCSA_NoDeadStrip:
166 case MCSA_ELF_TypeGnuUniqueObject:
171 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
172 SD.setExternal(true);
173 BindingExplicitlySet.insert(Symbol);
176 case MCSA_WeakReference:
178 MCELF::SetBinding(SD, ELF::STB_WEAK);
179 SD.setExternal(true);
180 BindingExplicitlySet.insert(Symbol);
184 MCELF::SetBinding(SD, ELF::STB_LOCAL);
185 SD.setExternal(false);
186 BindingExplicitlySet.insert(Symbol);
189 case MCSA_ELF_TypeFunction:
190 MCELF::SetType(SD, ELF::STT_FUNC);
193 case MCSA_ELF_TypeIndFunction:
194 MCELF::SetType(SD, ELF::STT_GNU_IFUNC);
197 case MCSA_ELF_TypeObject:
198 MCELF::SetType(SD, ELF::STT_OBJECT);
201 case MCSA_ELF_TypeTLS:
202 MCELF::SetType(SD, ELF::STT_TLS);
205 case MCSA_ELF_TypeCommon:
206 MCELF::SetType(SD, ELF::STT_COMMON);
209 case MCSA_ELF_TypeNoType:
210 MCELF::SetType(SD, ELF::STT_NOTYPE);
214 MCELF::SetVisibility(SD, ELF::STV_PROTECTED);
218 MCELF::SetVisibility(SD, ELF::STV_HIDDEN);
222 MCELF::SetVisibility(SD, ELF::STV_INTERNAL);
227 void MCELFStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
228 unsigned ByteAlignment) {
229 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
231 if (!BindingExplicitlySet.count(Symbol)) {
232 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
233 SD.setExternal(true);
236 MCELF::SetType(SD, ELF::STT_OBJECT);
238 if (MCELF::GetBinding(SD) == ELF_STB_Local) {
239 const MCSection *Section = getAssembler().getContext().getELFSection(".bss",
243 SectionKind::getBSS());
244 Symbol->setSection(*Section);
246 struct LocalCommon L = {&SD, Size, ByteAlignment};
247 LocalCommons.push_back(L);
249 SD.setCommon(Size, ByteAlignment);
252 SD.setSize(MCConstantExpr::Create(Size, getContext()));
255 void MCELFStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
256 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
260 void MCELFStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
261 unsigned ByteAlignment) {
262 // FIXME: Should this be caught and done earlier?
263 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
264 MCELF::SetBinding(SD, ELF::STB_LOCAL);
265 SD.setExternal(false);
266 BindingExplicitlySet.insert(Symbol);
267 EmitCommonSymbol(Symbol, Size, ByteAlignment);
270 void MCELFStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
271 unsigned AddrSpace) {
272 if (getCurrentSectionData()->isBundleLocked())
273 report_fatal_error("Emitting values inside a locked bundle is forbidden");
274 fixSymbolsInTLSFixups(Value);
275 MCObjectStreamer::EmitValueImpl(Value, Size, AddrSpace);
278 void MCELFStreamer::EmitValueToAlignment(unsigned ByteAlignment,
281 unsigned MaxBytesToEmit) {
282 if (getCurrentSectionData()->isBundleLocked())
283 report_fatal_error("Emitting values inside a locked bundle is forbidden");
284 MCObjectStreamer::EmitValueToAlignment(ByteAlignment, Value,
285 ValueSize, MaxBytesToEmit);
289 // Add a symbol for the file name of this module. This is the second
290 // entry in the module's symbol table (the first being the null symbol).
291 void MCELFStreamer::EmitFileDirective(StringRef Filename) {
292 MCSymbol *Symbol = getAssembler().getContext().GetOrCreateSymbol(Filename);
293 Symbol->setSection(*getCurrentSection());
294 Symbol->setAbsolute();
296 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
298 SD.setFlags(ELF_STT_File | ELF_STB_Local | ELF_STV_Default);
301 void MCELFStreamer::fixSymbolsInTLSFixups(const MCExpr *expr) {
302 switch (expr->getKind()) {
303 case MCExpr::Target: llvm_unreachable("Can't handle target exprs yet!");
304 case MCExpr::Constant:
307 case MCExpr::Binary: {
308 const MCBinaryExpr *be = cast<MCBinaryExpr>(expr);
309 fixSymbolsInTLSFixups(be->getLHS());
310 fixSymbolsInTLSFixups(be->getRHS());
314 case MCExpr::SymbolRef: {
315 const MCSymbolRefExpr &symRef = *cast<MCSymbolRefExpr>(expr);
316 switch (symRef.getKind()) {
319 case MCSymbolRefExpr::VK_GOTTPOFF:
320 case MCSymbolRefExpr::VK_INDNTPOFF:
321 case MCSymbolRefExpr::VK_NTPOFF:
322 case MCSymbolRefExpr::VK_GOTNTPOFF:
323 case MCSymbolRefExpr::VK_TLSGD:
324 case MCSymbolRefExpr::VK_TLSLD:
325 case MCSymbolRefExpr::VK_TLSLDM:
326 case MCSymbolRefExpr::VK_TPOFF:
327 case MCSymbolRefExpr::VK_DTPOFF:
328 case MCSymbolRefExpr::VK_ARM_TLSGD:
329 case MCSymbolRefExpr::VK_ARM_TPOFF:
330 case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
331 case MCSymbolRefExpr::VK_Mips_TLSGD:
332 case MCSymbolRefExpr::VK_Mips_GOTTPREL:
333 case MCSymbolRefExpr::VK_Mips_TPREL_HI:
334 case MCSymbolRefExpr::VK_Mips_TPREL_LO:
337 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(symRef.getSymbol());
338 MCELF::SetType(SD, ELF::STT_TLS);
343 fixSymbolsInTLSFixups(cast<MCUnaryExpr>(expr)->getSubExpr());
348 void MCELFStreamer::EmitInstToFragment(const MCInst &Inst) {
349 this->MCObjectStreamer::EmitInstToFragment(Inst);
350 MCRelaxableFragment &F = *cast<MCRelaxableFragment>(getCurrentFragment());
352 for (unsigned i = 0, e = F.getFixups().size(); i != e; ++i)
353 fixSymbolsInTLSFixups(F.getFixups()[i].getValue());
356 void MCELFStreamer::EmitInstToData(const MCInst &Inst) {
357 MCAssembler &Assembler = getAssembler();
358 SmallVector<MCFixup, 4> Fixups;
359 SmallString<256> Code;
360 raw_svector_ostream VecOS(Code);
361 Assembler.getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
364 for (unsigned i = 0, e = Fixups.size(); i != e; ++i)
365 fixSymbolsInTLSFixups(Fixups[i].getValue());
367 // There are several possibilities here:
369 // If bundling is disabled, append the encoded instruction to the current data
370 // fragment (or create a new such fragment if the current fragment is not a
373 // If bundling is enabled:
374 // - If we're not in a bundle-locked group, emit the instruction into a
375 // fragment of its own. If there are no fixups registered for the
376 // instruction, emit a MCCompactEncodedInstFragment. Otherwise, emit a
378 // - If we're in a bundle-locked group, append the instruction to the current
379 // data fragment because we want all the instructions in a group to get into
380 // the same fragment. Be careful not to do that for the first instruction in
381 // the group, though.
384 if (Assembler.isBundlingEnabled()) {
385 MCSectionData *SD = getCurrentSectionData();
386 if (SD->isBundleLocked() && !SD->isBundleGroupBeforeFirstInst())
387 DF = getOrCreateDataFragment();
388 else if (!SD->isBundleLocked() && Fixups.size() == 0) {
389 // Optimize memory usage by emitting the instruction to a
390 // MCCompactEncodedInstFragment when not in a bundle-locked group and
391 // there are no fixups registered.
392 MCCompactEncodedInstFragment *CEIF = new MCCompactEncodedInstFragment(SD);
393 CEIF->getContents().append(Code.begin(), Code.end());
397 DF = new MCDataFragment(SD);
398 if (SD->getBundleLockState() == MCSectionData::BundleLockedAlignToEnd) {
399 // If this is a new fragment created for a bundle-locked group, and the
400 // group was marked as "align_to_end", set a flag in the fragment.
401 DF->setAlignToBundleEnd(true);
405 // We're now emitting an instruction in a bundle group, so this flag has
407 SD->setBundleGroupBeforeFirstInst(false);
409 DF = getOrCreateDataFragment();
412 // Add the fixups and data.
413 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
414 Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
415 DF->getFixups().push_back(Fixups[i]);
417 DF->setHasInstructions(true);
418 DF->getContents().append(Code.begin(), Code.end());
421 void MCELFStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
422 assert(AlignPow2 <= 30 && "Invalid bundle alignment");
423 MCAssembler &Assembler = getAssembler();
424 if (Assembler.getBundleAlignSize() == 0 && AlignPow2 > 0)
425 Assembler.setBundleAlignSize(1 << AlignPow2);
427 report_fatal_error(".bundle_align_mode should be only set once per file");
430 void MCELFStreamer::EmitBundleLock(bool AlignToEnd) {
431 MCSectionData *SD = getCurrentSectionData();
435 if (!getAssembler().isBundlingEnabled())
436 report_fatal_error(".bundle_lock forbidden when bundling is disabled");
437 else if (SD->isBundleLocked())
438 report_fatal_error("Nesting of .bundle_lock is forbidden");
440 SD->setBundleLockState(AlignToEnd ? MCSectionData::BundleLockedAlignToEnd :
441 MCSectionData::BundleLocked);
442 SD->setBundleGroupBeforeFirstInst(true);
445 void MCELFStreamer::EmitBundleUnlock() {
446 MCSectionData *SD = getCurrentSectionData();
449 if (!getAssembler().isBundlingEnabled())
450 report_fatal_error(".bundle_unlock forbidden when bundling is disabled");
451 else if (!SD->isBundleLocked())
452 report_fatal_error(".bundle_unlock without matching lock");
453 else if (SD->isBundleGroupBeforeFirstInst())
454 report_fatal_error("Empty bundle-locked group is forbidden");
456 SD->setBundleLockState(MCSectionData::NotBundleLocked);
459 void MCELFStreamer::FinishImpl() {
462 for (std::vector<LocalCommon>::const_iterator i = LocalCommons.begin(),
463 e = LocalCommons.end();
465 MCSymbolData *SD = i->SD;
466 uint64_t Size = i->Size;
467 unsigned ByteAlignment = i->ByteAlignment;
468 const MCSymbol &Symbol = SD->getSymbol();
469 const MCSection &Section = Symbol.getSection();
471 MCSectionData &SectData = getAssembler().getOrCreateSectionData(Section);
472 new MCAlignFragment(ByteAlignment, 0, 1, ByteAlignment, &SectData);
474 MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
477 // Update the maximum alignment of the section if necessary.
478 if (ByteAlignment > SectData.getAlignment())
479 SectData.setAlignment(ByteAlignment);
482 this->MCObjectStreamer::FinishImpl();
484 void MCELFStreamer::EmitTCEntry(const MCSymbol &S) {
485 // Creates a R_PPC64_TOC relocation
486 MCObjectStreamer::EmitSymbolValue(&S, 8);
489 MCStreamer *llvm::createELFStreamer(MCContext &Context, MCAsmBackend &MAB,
490 raw_ostream &OS, MCCodeEmitter *CE,
491 bool RelaxAll, bool NoExecStack) {
492 MCELFStreamer *S = new MCELFStreamer(Context, MAB, OS, CE);
494 S->getAssembler().setRelaxAll(true);
496 S->getAssembler().setNoExecStack(true);
500 void MCELFStreamer::EmitThumbFunc(MCSymbol *Func) {
501 llvm_unreachable("Generic ELF doesn't support this directive");
504 void MCELFStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
505 llvm_unreachable("ELF doesn't support this directive");
508 void MCELFStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
509 llvm_unreachable("ELF doesn't support this directive");
512 void MCELFStreamer::EmitCOFFSymbolStorageClass(int StorageClass) {
513 llvm_unreachable("ELF doesn't support this directive");
516 void MCELFStreamer::EmitCOFFSymbolType(int Type) {
517 llvm_unreachable("ELF doesn't support this directive");
520 void MCELFStreamer::EndCOFFSymbolDef() {
521 llvm_unreachable("ELF doesn't support this directive");
524 void MCELFStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
525 uint64_t Size, unsigned ByteAlignment) {
526 llvm_unreachable("ELF doesn't support this directive");
529 void MCELFStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
530 uint64_t Size, unsigned ByteAlignment) {
531 llvm_unreachable("ELF doesn't support this directive");