xref: /openbsd-src/gnu/llvm/llvm/lib/MC/MCELFStreamer.cpp (revision a96b36398fcfb4953e8190127da8bf074c7552f1)
1 //===- lib/MC/MCELFStreamer.cpp - ELF Object Output -----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file assembles .s files and emits ELF .o object files.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/MC/MCELFStreamer.h"
14 #include "llvm/ADT/SmallString.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/BinaryFormat/ELF.h"
17 #include "llvm/MC/MCAsmBackend.h"
18 #include "llvm/MC/MCAsmInfo.h"
19 #include "llvm/MC/MCAssembler.h"
20 #include "llvm/MC/MCCodeEmitter.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCFixup.h"
24 #include "llvm/MC/MCFragment.h"
25 #include "llvm/MC/MCObjectFileInfo.h"
26 #include "llvm/MC/MCObjectWriter.h"
27 #include "llvm/MC/MCSection.h"
28 #include "llvm/MC/MCSectionELF.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/MC/MCSymbol.h"
31 #include "llvm/MC/MCSymbolELF.h"
32 #include "llvm/MC/TargetRegistry.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/LEB128.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include <cassert>
38 #include <cstdint>
39 
40 using namespace llvm;
41 
MCELFStreamer(MCContext & Context,std::unique_ptr<MCAsmBackend> TAB,std::unique_ptr<MCObjectWriter> OW,std::unique_ptr<MCCodeEmitter> Emitter)42 MCELFStreamer::MCELFStreamer(MCContext &Context,
43                              std::unique_ptr<MCAsmBackend> TAB,
44                              std::unique_ptr<MCObjectWriter> OW,
45                              std::unique_ptr<MCCodeEmitter> Emitter)
46     : MCObjectStreamer(Context, std::move(TAB), std::move(OW),
47                        std::move(Emitter)) {}
48 
isBundleLocked() const49 bool MCELFStreamer::isBundleLocked() const {
50   return getCurrentSectionOnly()->isBundleLocked();
51 }
52 
mergeFragment(MCDataFragment * DF,MCDataFragment * EF)53 void MCELFStreamer::mergeFragment(MCDataFragment *DF,
54                                   MCDataFragment *EF) {
55   MCAssembler &Assembler = getAssembler();
56 
57   if (Assembler.isBundlingEnabled() && Assembler.getRelaxAll()) {
58     uint64_t FSize = EF->getContents().size();
59 
60     if (FSize > Assembler.getBundleAlignSize())
61       report_fatal_error("Fragment can't be larger than a bundle size");
62 
63     uint64_t RequiredBundlePadding = computeBundlePadding(
64         Assembler, EF, DF->getContents().size(), FSize);
65 
66     if (RequiredBundlePadding > UINT8_MAX)
67       report_fatal_error("Padding cannot exceed 255 bytes");
68 
69     if (RequiredBundlePadding > 0) {
70       SmallString<256> Code;
71       raw_svector_ostream VecOS(Code);
72       EF->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
73       Assembler.writeFragmentPadding(VecOS, *EF, FSize);
74 
75       DF->getContents().append(Code.begin(), Code.end());
76     }
77   }
78 
79   flushPendingLabels(DF, DF->getContents().size());
80 
81   for (unsigned i = 0, e = EF->getFixups().size(); i != e; ++i) {
82     EF->getFixups()[i].setOffset(EF->getFixups()[i].getOffset() +
83                                  DF->getContents().size());
84     DF->getFixups().push_back(EF->getFixups()[i]);
85   }
86   if (DF->getSubtargetInfo() == nullptr && EF->getSubtargetInfo())
87     DF->setHasInstructions(*EF->getSubtargetInfo());
88   DF->getContents().append(EF->getContents().begin(), EF->getContents().end());
89 }
90 
initSections(bool NoExecStack,const MCSubtargetInfo & STI)91 void MCELFStreamer::initSections(bool NoExecStack, const MCSubtargetInfo &STI) {
92   MCContext &Ctx = getContext();
93   switchSection(Ctx.getObjectFileInfo()->getTextSection());
94   emitCodeAlignment(Align(Ctx.getObjectFileInfo()->getTextSectionAlignment()),
95                     &STI);
96 
97   if (NoExecStack) {
98     MCSection *s = Ctx.getAsmInfo()->getNonexecutableStackSection(Ctx);
99     if (s)
100       switchSection(s);
101   }
102 }
103 
emitLabel(MCSymbol * S,SMLoc Loc)104 void MCELFStreamer::emitLabel(MCSymbol *S, SMLoc Loc) {
105   auto *Symbol = cast<MCSymbolELF>(S);
106   MCObjectStreamer::emitLabel(Symbol, Loc);
107 
108   const MCSectionELF &Section =
109       static_cast<const MCSectionELF &>(*getCurrentSectionOnly());
110   if (Section.getFlags() & ELF::SHF_TLS)
111     Symbol->setType(ELF::STT_TLS);
112 }
113 
emitLabelAtPos(MCSymbol * S,SMLoc Loc,MCFragment * F,uint64_t Offset)114 void MCELFStreamer::emitLabelAtPos(MCSymbol *S, SMLoc Loc, MCFragment *F,
115                                    uint64_t Offset) {
116   auto *Symbol = cast<MCSymbolELF>(S);
117   MCObjectStreamer::emitLabelAtPos(Symbol, Loc, F, Offset);
118 
119   const MCSectionELF &Section =
120       static_cast<const MCSectionELF &>(*getCurrentSectionOnly());
121   if (Section.getFlags() & ELF::SHF_TLS)
122     Symbol->setType(ELF::STT_TLS);
123 }
124 
emitAssemblerFlag(MCAssemblerFlag Flag)125 void MCELFStreamer::emitAssemblerFlag(MCAssemblerFlag Flag) {
126   // Let the target do whatever target specific stuff it needs to do.
127   getAssembler().getBackend().handleAssemblerFlag(Flag);
128   // Do any generic stuff we need to do.
129   switch (Flag) {
130   case MCAF_SyntaxUnified: return; // no-op here.
131   case MCAF_Code16: return; // Change parsing mode; no-op here.
132   case MCAF_Code32: return; // Change parsing mode; no-op here.
133   case MCAF_Code64: return; // Change parsing mode; no-op here.
134   case MCAF_SubsectionsViaSymbols:
135     getAssembler().setSubsectionsViaSymbols(true);
136     return;
137   }
138 
139   llvm_unreachable("invalid assembler flag!");
140 }
141 
142 // If bundle alignment is used and there are any instructions in the section, it
143 // needs to be aligned to at least the bundle size.
setSectionAlignmentForBundling(const MCAssembler & Assembler,MCSection * Section)144 static void setSectionAlignmentForBundling(const MCAssembler &Assembler,
145                                            MCSection *Section) {
146   if (Section && Assembler.isBundlingEnabled() && Section->hasInstructions())
147     Section->ensureMinAlignment(Align(Assembler.getBundleAlignSize()));
148 }
149 
changeSection(MCSection * Section,const MCExpr * Subsection)150 void MCELFStreamer::changeSection(MCSection *Section,
151                                   const MCExpr *Subsection) {
152   MCSection *CurSection = getCurrentSectionOnly();
153   if (CurSection && isBundleLocked())
154     report_fatal_error("Unterminated .bundle_lock when changing a section");
155 
156   MCAssembler &Asm = getAssembler();
157   // Ensure the previous section gets aligned if necessary.
158   setSectionAlignmentForBundling(Asm, CurSection);
159   auto *SectionELF = static_cast<const MCSectionELF *>(Section);
160   const MCSymbol *Grp = SectionELF->getGroup();
161   if (Grp)
162     Asm.registerSymbol(*Grp);
163   if (SectionELF->getFlags() & ELF::SHF_GNU_RETAIN)
164     Asm.getWriter().markGnuAbi();
165 
166   changeSectionImpl(Section, Subsection);
167   Asm.registerSymbol(*Section->getBeginSymbol());
168 }
169 
emitWeakReference(MCSymbol * Alias,const MCSymbol * Symbol)170 void MCELFStreamer::emitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
171   getAssembler().registerSymbol(*Symbol);
172   const MCExpr *Value = MCSymbolRefExpr::create(
173       Symbol, MCSymbolRefExpr::VK_WEAKREF, getContext());
174   Alias->setVariableValue(Value);
175 }
176 
177 // When GNU as encounters more than one .type declaration for an object it seems
178 // to use a mechanism similar to the one below to decide which type is actually
179 // used in the object file.  The greater of T1 and T2 is selected based on the
180 // following ordering:
181 //  STT_NOTYPE < STT_OBJECT < STT_FUNC < STT_GNU_IFUNC < STT_TLS < anything else
182 // If neither T1 < T2 nor T2 < T1 according to this ordering, use T2 (the user
183 // provided type).
CombineSymbolTypes(unsigned T1,unsigned T2)184 static unsigned CombineSymbolTypes(unsigned T1, unsigned T2) {
185   for (unsigned Type : {ELF::STT_NOTYPE, ELF::STT_OBJECT, ELF::STT_FUNC,
186                         ELF::STT_GNU_IFUNC, ELF::STT_TLS}) {
187     if (T1 == Type)
188       return T2;
189     if (T2 == Type)
190       return T1;
191   }
192 
193   return T2;
194 }
195 
emitSymbolAttribute(MCSymbol * S,MCSymbolAttr Attribute)196 bool MCELFStreamer::emitSymbolAttribute(MCSymbol *S, MCSymbolAttr Attribute) {
197   auto *Symbol = cast<MCSymbolELF>(S);
198 
199   // Adding a symbol attribute always introduces the symbol, note that an
200   // important side effect of calling registerSymbol here is to register
201   // the symbol with the assembler.
202   getAssembler().registerSymbol(*Symbol);
203 
204   // The implementation of symbol attributes is designed to match 'as', but it
205   // leaves much to desired. It doesn't really make sense to arbitrarily add and
206   // remove flags, but 'as' allows this (in particular, see .desc).
207   //
208   // In the future it might be worth trying to make these operations more well
209   // defined.
210   switch (Attribute) {
211   case MCSA_Cold:
212   case MCSA_Extern:
213   case MCSA_LazyReference:
214   case MCSA_Reference:
215   case MCSA_SymbolResolver:
216   case MCSA_PrivateExtern:
217   case MCSA_WeakDefinition:
218   case MCSA_WeakDefAutoPrivate:
219   case MCSA_Invalid:
220   case MCSA_IndirectSymbol:
221   case MCSA_Exported:
222     return false;
223 
224   case MCSA_NoDeadStrip:
225     // Ignore for now.
226     break;
227 
228   case MCSA_ELF_TypeGnuUniqueObject:
229     Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_OBJECT));
230     Symbol->setBinding(ELF::STB_GNU_UNIQUE);
231     getAssembler().getWriter().markGnuAbi();
232     break;
233 
234   case MCSA_Global:
235     // For `.weak x; .global x`, GNU as sets the binding to STB_WEAK while we
236     // traditionally set the binding to STB_GLOBAL. This is error-prone, so we
237     // error on such cases. Note, we also disallow changed binding from .local.
238     if (Symbol->isBindingSet() && Symbol->getBinding() != ELF::STB_GLOBAL)
239       getContext().reportError(getStartTokLoc(),
240                                Symbol->getName() +
241                                    " changed binding to STB_GLOBAL");
242     Symbol->setBinding(ELF::STB_GLOBAL);
243     break;
244 
245   case MCSA_WeakReference:
246   case MCSA_Weak:
247     // For `.global x; .weak x`, both MC and GNU as set the binding to STB_WEAK.
248     // We emit a warning for now but may switch to an error in the future.
249     if (Symbol->isBindingSet() && Symbol->getBinding() != ELF::STB_WEAK)
250       getContext().reportWarning(
251           getStartTokLoc(), Symbol->getName() + " changed binding to STB_WEAK");
252     Symbol->setBinding(ELF::STB_WEAK);
253     break;
254 
255   case MCSA_Local:
256     if (Symbol->isBindingSet() && Symbol->getBinding() != ELF::STB_LOCAL)
257       getContext().reportError(getStartTokLoc(),
258                                Symbol->getName() +
259                                    " changed binding to STB_LOCAL");
260     Symbol->setBinding(ELF::STB_LOCAL);
261     break;
262 
263   case MCSA_ELF_TypeFunction:
264     Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_FUNC));
265     break;
266 
267   case MCSA_ELF_TypeIndFunction:
268     Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_GNU_IFUNC));
269     getAssembler().getWriter().markGnuAbi();
270     break;
271 
272   case MCSA_ELF_TypeObject:
273     Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_OBJECT));
274     break;
275 
276   case MCSA_ELF_TypeTLS:
277     Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_TLS));
278     break;
279 
280   case MCSA_ELF_TypeCommon:
281     // TODO: Emit these as a common symbol.
282     Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_OBJECT));
283     break;
284 
285   case MCSA_ELF_TypeNoType:
286     Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_NOTYPE));
287     break;
288 
289   case MCSA_Protected:
290     Symbol->setVisibility(ELF::STV_PROTECTED);
291     break;
292 
293   case MCSA_Memtag:
294     Symbol->setMemtag(true);
295     break;
296 
297   case MCSA_Hidden:
298     Symbol->setVisibility(ELF::STV_HIDDEN);
299     break;
300 
301   case MCSA_Internal:
302     Symbol->setVisibility(ELF::STV_INTERNAL);
303     break;
304 
305   case MCSA_AltEntry:
306     llvm_unreachable("ELF doesn't support the .alt_entry attribute");
307 
308   case MCSA_LGlobal:
309     llvm_unreachable("ELF doesn't support the .lglobl attribute");
310   }
311 
312   return true;
313 }
314 
emitCommonSymbol(MCSymbol * S,uint64_t Size,Align ByteAlignment)315 void MCELFStreamer::emitCommonSymbol(MCSymbol *S, uint64_t Size,
316                                      Align ByteAlignment) {
317   auto *Symbol = cast<MCSymbolELF>(S);
318   getAssembler().registerSymbol(*Symbol);
319 
320   if (!Symbol->isBindingSet())
321     Symbol->setBinding(ELF::STB_GLOBAL);
322 
323   Symbol->setType(ELF::STT_OBJECT);
324 
325   if (Symbol->getBinding() == ELF::STB_LOCAL) {
326     MCSection &Section = *getAssembler().getContext().getELFSection(
327         ".bss", ELF::SHT_NOBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
328     MCSectionSubPair P = getCurrentSection();
329     switchSection(&Section);
330 
331     emitValueToAlignment(ByteAlignment, 0, 1, 0);
332     emitLabel(Symbol);
333     emitZeros(Size);
334 
335     switchSection(P.first, P.second);
336   } else {
337     if (Symbol->declareCommon(Size, ByteAlignment))
338       report_fatal_error(Twine("Symbol: ") + Symbol->getName() +
339                          " redeclared as different type");
340   }
341 
342   cast<MCSymbolELF>(Symbol)
343       ->setSize(MCConstantExpr::create(Size, getContext()));
344 }
345 
emitELFSize(MCSymbol * Symbol,const MCExpr * Value)346 void MCELFStreamer::emitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
347   cast<MCSymbolELF>(Symbol)->setSize(Value);
348 }
349 
emitELFSymverDirective(const MCSymbol * OriginalSym,StringRef Name,bool KeepOriginalSym)350 void MCELFStreamer::emitELFSymverDirective(const MCSymbol *OriginalSym,
351                                            StringRef Name,
352                                            bool KeepOriginalSym) {
353   getAssembler().Symvers.push_back(MCAssembler::Symver{
354       getStartTokLoc(), OriginalSym, Name, KeepOriginalSym});
355 }
356 
emitLocalCommonSymbol(MCSymbol * S,uint64_t Size,Align ByteAlignment)357 void MCELFStreamer::emitLocalCommonSymbol(MCSymbol *S, uint64_t Size,
358                                           Align ByteAlignment) {
359   auto *Symbol = cast<MCSymbolELF>(S);
360   // FIXME: Should this be caught and done earlier?
361   getAssembler().registerSymbol(*Symbol);
362   Symbol->setBinding(ELF::STB_LOCAL);
363   emitCommonSymbol(Symbol, Size, ByteAlignment);
364 }
365 
emitValueImpl(const MCExpr * Value,unsigned Size,SMLoc Loc)366 void MCELFStreamer::emitValueImpl(const MCExpr *Value, unsigned Size,
367                                   SMLoc Loc) {
368   if (isBundleLocked())
369     report_fatal_error("Emitting values inside a locked bundle is forbidden");
370   fixSymbolsInTLSFixups(Value);
371   MCObjectStreamer::emitValueImpl(Value, Size, Loc);
372 }
373 
emitValueToAlignment(Align Alignment,int64_t Value,unsigned ValueSize,unsigned MaxBytesToEmit)374 void MCELFStreamer::emitValueToAlignment(Align Alignment, int64_t Value,
375                                          unsigned ValueSize,
376                                          unsigned MaxBytesToEmit) {
377   if (isBundleLocked())
378     report_fatal_error("Emitting values inside a locked bundle is forbidden");
379   MCObjectStreamer::emitValueToAlignment(Alignment, Value, ValueSize,
380                                          MaxBytesToEmit);
381 }
382 
emitCGProfileEntry(const MCSymbolRefExpr * From,const MCSymbolRefExpr * To,uint64_t Count)383 void MCELFStreamer::emitCGProfileEntry(const MCSymbolRefExpr *From,
384                                        const MCSymbolRefExpr *To,
385                                        uint64_t Count) {
386   getAssembler().CGProfile.push_back({From, To, Count});
387 }
388 
emitIdent(StringRef IdentString)389 void MCELFStreamer::emitIdent(StringRef IdentString) {
390   MCSection *Comment = getAssembler().getContext().getELFSection(
391       ".comment", ELF::SHT_PROGBITS, ELF::SHF_MERGE | ELF::SHF_STRINGS, 1);
392   pushSection();
393   switchSection(Comment);
394   if (!SeenIdent) {
395     emitInt8(0);
396     SeenIdent = true;
397   }
398   emitBytes(IdentString);
399   emitInt8(0);
400   popSection();
401 }
402 
fixSymbolsInTLSFixups(const MCExpr * expr)403 void MCELFStreamer::fixSymbolsInTLSFixups(const MCExpr *expr) {
404   switch (expr->getKind()) {
405   case MCExpr::Target:
406     cast<MCTargetExpr>(expr)->fixELFSymbolsInTLSFixups(getAssembler());
407     break;
408   case MCExpr::Constant:
409     break;
410 
411   case MCExpr::Binary: {
412     const MCBinaryExpr *be = cast<MCBinaryExpr>(expr);
413     fixSymbolsInTLSFixups(be->getLHS());
414     fixSymbolsInTLSFixups(be->getRHS());
415     break;
416   }
417 
418   case MCExpr::SymbolRef: {
419     const MCSymbolRefExpr &symRef = *cast<MCSymbolRefExpr>(expr);
420     switch (symRef.getKind()) {
421     default:
422       return;
423     case MCSymbolRefExpr::VK_GOTTPOFF:
424     case MCSymbolRefExpr::VK_INDNTPOFF:
425     case MCSymbolRefExpr::VK_NTPOFF:
426     case MCSymbolRefExpr::VK_GOTNTPOFF:
427     case MCSymbolRefExpr::VK_TLSCALL:
428     case MCSymbolRefExpr::VK_TLSDESC:
429     case MCSymbolRefExpr::VK_TLSGD:
430     case MCSymbolRefExpr::VK_TLSLD:
431     case MCSymbolRefExpr::VK_TLSLDM:
432     case MCSymbolRefExpr::VK_TPOFF:
433     case MCSymbolRefExpr::VK_TPREL:
434     case MCSymbolRefExpr::VK_DTPOFF:
435     case MCSymbolRefExpr::VK_DTPREL:
436     case MCSymbolRefExpr::VK_PPC_DTPMOD:
437     case MCSymbolRefExpr::VK_PPC_TPREL_LO:
438     case MCSymbolRefExpr::VK_PPC_TPREL_HI:
439     case MCSymbolRefExpr::VK_PPC_TPREL_HA:
440     case MCSymbolRefExpr::VK_PPC_TPREL_HIGH:
441     case MCSymbolRefExpr::VK_PPC_TPREL_HIGHA:
442     case MCSymbolRefExpr::VK_PPC_TPREL_HIGHER:
443     case MCSymbolRefExpr::VK_PPC_TPREL_HIGHERA:
444     case MCSymbolRefExpr::VK_PPC_TPREL_HIGHEST:
445     case MCSymbolRefExpr::VK_PPC_TPREL_HIGHESTA:
446     case MCSymbolRefExpr::VK_PPC_DTPREL_LO:
447     case MCSymbolRefExpr::VK_PPC_DTPREL_HI:
448     case MCSymbolRefExpr::VK_PPC_DTPREL_HA:
449     case MCSymbolRefExpr::VK_PPC_DTPREL_HIGH:
450     case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHA:
451     case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHER:
452     case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHERA:
453     case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHEST:
454     case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHESTA:
455     case MCSymbolRefExpr::VK_PPC_GOT_TPREL:
456     case MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO:
457     case MCSymbolRefExpr::VK_PPC_GOT_TPREL_HI:
458     case MCSymbolRefExpr::VK_PPC_GOT_TPREL_HA:
459     case MCSymbolRefExpr::VK_PPC_GOT_TPREL_PCREL:
460     case MCSymbolRefExpr::VK_PPC_GOT_DTPREL:
461     case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_LO:
462     case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_HI:
463     case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_HA:
464     case MCSymbolRefExpr::VK_PPC_TLS:
465     case MCSymbolRefExpr::VK_PPC_TLS_PCREL:
466     case MCSymbolRefExpr::VK_PPC_GOT_TLSGD:
467     case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO:
468     case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HI:
469     case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HA:
470     case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_PCREL:
471     case MCSymbolRefExpr::VK_PPC_TLSGD:
472     case MCSymbolRefExpr::VK_PPC_GOT_TLSLD:
473     case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO:
474     case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HI:
475     case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HA:
476     case MCSymbolRefExpr::VK_PPC_TLSLD:
477       break;
478     }
479     getAssembler().registerSymbol(symRef.getSymbol());
480     cast<MCSymbolELF>(symRef.getSymbol()).setType(ELF::STT_TLS);
481     break;
482   }
483 
484   case MCExpr::Unary:
485     fixSymbolsInTLSFixups(cast<MCUnaryExpr>(expr)->getSubExpr());
486     break;
487   }
488 }
489 
finalizeCGProfileEntry(const MCSymbolRefExpr * & SRE,uint64_t Offset)490 void MCELFStreamer::finalizeCGProfileEntry(const MCSymbolRefExpr *&SRE,
491                                            uint64_t Offset) {
492   const MCSymbol *S = &SRE->getSymbol();
493   if (S->isTemporary()) {
494     if (!S->isInSection()) {
495       getContext().reportError(
496           SRE->getLoc(), Twine("Reference to undefined temporary symbol ") +
497                              "`" + S->getName() + "`");
498       return;
499     }
500     S = S->getSection().getBeginSymbol();
501     S->setUsedInReloc();
502     SRE = MCSymbolRefExpr::create(S, MCSymbolRefExpr::VK_None, getContext(),
503                                   SRE->getLoc());
504   }
505   const MCConstantExpr *MCOffset = MCConstantExpr::create(Offset, getContext());
506   MCObjectStreamer::visitUsedExpr(*SRE);
507   if (std::optional<std::pair<bool, std::string>> Err =
508           MCObjectStreamer::emitRelocDirective(
509               *MCOffset, "BFD_RELOC_NONE", SRE, SRE->getLoc(),
510               *getContext().getSubtargetInfo()))
511     report_fatal_error("Relocation for CG Profile could not be created: " +
512                        Twine(Err->second));
513 }
514 
finalizeCGProfile()515 void MCELFStreamer::finalizeCGProfile() {
516   MCAssembler &Asm = getAssembler();
517   if (Asm.CGProfile.empty())
518     return;
519   MCSection *CGProfile = getAssembler().getContext().getELFSection(
520       ".llvm.call-graph-profile", ELF::SHT_LLVM_CALL_GRAPH_PROFILE,
521       ELF::SHF_EXCLUDE, /*sizeof(Elf_CGProfile_Impl<>)=*/8);
522   pushSection();
523   switchSection(CGProfile);
524   uint64_t Offset = 0;
525   for (MCAssembler::CGProfileEntry &E : Asm.CGProfile) {
526     finalizeCGProfileEntry(E.From, Offset);
527     finalizeCGProfileEntry(E.To, Offset);
528     emitIntValue(E.Count, sizeof(uint64_t));
529     Offset += sizeof(uint64_t);
530   }
531   popSection();
532 }
533 
emitInstToFragment(const MCInst & Inst,const MCSubtargetInfo & STI)534 void MCELFStreamer::emitInstToFragment(const MCInst &Inst,
535                                        const MCSubtargetInfo &STI) {
536   this->MCObjectStreamer::emitInstToFragment(Inst, STI);
537   MCRelaxableFragment &F = *cast<MCRelaxableFragment>(getCurrentFragment());
538 
539   for (auto &Fixup : F.getFixups())
540     fixSymbolsInTLSFixups(Fixup.getValue());
541 }
542 
543 // A fragment can only have one Subtarget, and when bundling is enabled we
544 // sometimes need to use the same fragment. We give an error if there
545 // are conflicting Subtargets.
CheckBundleSubtargets(const MCSubtargetInfo * OldSTI,const MCSubtargetInfo * NewSTI)546 static void CheckBundleSubtargets(const MCSubtargetInfo *OldSTI,
547                                   const MCSubtargetInfo *NewSTI) {
548   if (OldSTI && NewSTI && OldSTI != NewSTI)
549     report_fatal_error("A Bundle can only have one Subtarget.");
550 }
551 
emitInstToData(const MCInst & Inst,const MCSubtargetInfo & STI)552 void MCELFStreamer::emitInstToData(const MCInst &Inst,
553                                    const MCSubtargetInfo &STI) {
554   MCAssembler &Assembler = getAssembler();
555   SmallVector<MCFixup, 4> Fixups;
556   SmallString<256> Code;
557   raw_svector_ostream VecOS(Code);
558   Assembler.getEmitter().encodeInstruction(Inst, VecOS, Fixups, STI);
559 
560   for (auto &Fixup : Fixups)
561     fixSymbolsInTLSFixups(Fixup.getValue());
562 
563   // There are several possibilities here:
564   //
565   // If bundling is disabled, append the encoded instruction to the current data
566   // fragment (or create a new such fragment if the current fragment is not a
567   // data fragment, or the Subtarget has changed).
568   //
569   // If bundling is enabled:
570   // - If we're not in a bundle-locked group, emit the instruction into a
571   //   fragment of its own. If there are no fixups registered for the
572   //   instruction, emit a MCCompactEncodedInstFragment. Otherwise, emit a
573   //   MCDataFragment.
574   // - If we're in a bundle-locked group, append the instruction to the current
575   //   data fragment because we want all the instructions in a group to get into
576   //   the same fragment. Be careful not to do that for the first instruction in
577   //   the group, though.
578   MCDataFragment *DF;
579 
580   if (Assembler.isBundlingEnabled()) {
581     MCSection &Sec = *getCurrentSectionOnly();
582     if (Assembler.getRelaxAll() && isBundleLocked()) {
583       // If the -mc-relax-all flag is used and we are bundle-locked, we re-use
584       // the current bundle group.
585       DF = BundleGroups.back();
586       CheckBundleSubtargets(DF->getSubtargetInfo(), &STI);
587     }
588     else if (Assembler.getRelaxAll() && !isBundleLocked())
589       // When not in a bundle-locked group and the -mc-relax-all flag is used,
590       // we create a new temporary fragment which will be later merged into
591       // the current fragment.
592       DF = new MCDataFragment();
593     else if (isBundleLocked() && !Sec.isBundleGroupBeforeFirstInst()) {
594       // If we are bundle-locked, we re-use the current fragment.
595       // The bundle-locking directive ensures this is a new data fragment.
596       DF = cast<MCDataFragment>(getCurrentFragment());
597       CheckBundleSubtargets(DF->getSubtargetInfo(), &STI);
598     }
599     else if (!isBundleLocked() && Fixups.size() == 0) {
600       // Optimize memory usage by emitting the instruction to a
601       // MCCompactEncodedInstFragment when not in a bundle-locked group and
602       // there are no fixups registered.
603       MCCompactEncodedInstFragment *CEIF = new MCCompactEncodedInstFragment();
604       insert(CEIF);
605       CEIF->getContents().append(Code.begin(), Code.end());
606       CEIF->setHasInstructions(STI);
607       return;
608     } else {
609       DF = new MCDataFragment();
610       insert(DF);
611     }
612     if (Sec.getBundleLockState() == MCSection::BundleLockedAlignToEnd) {
613       // If this fragment is for a group marked "align_to_end", set a flag
614       // in the fragment. This can happen after the fragment has already been
615       // created if there are nested bundle_align groups and an inner one
616       // is the one marked align_to_end.
617       DF->setAlignToBundleEnd(true);
618     }
619 
620     // We're now emitting an instruction in a bundle group, so this flag has
621     // to be turned off.
622     Sec.setBundleGroupBeforeFirstInst(false);
623   } else {
624     DF = getOrCreateDataFragment(&STI);
625   }
626 
627   // Add the fixups and data.
628   for (auto &Fixup : Fixups) {
629     Fixup.setOffset(Fixup.getOffset() + DF->getContents().size());
630     DF->getFixups().push_back(Fixup);
631   }
632 
633   DF->setHasInstructions(STI);
634   DF->getContents().append(Code.begin(), Code.end());
635 
636   if (Assembler.isBundlingEnabled() && Assembler.getRelaxAll()) {
637     if (!isBundleLocked()) {
638       mergeFragment(getOrCreateDataFragment(&STI), DF);
639       delete DF;
640     }
641   }
642 }
643 
emitBundleAlignMode(Align Alignment)644 void MCELFStreamer::emitBundleAlignMode(Align Alignment) {
645   assert(Log2(Alignment) <= 30 && "Invalid bundle alignment");
646   MCAssembler &Assembler = getAssembler();
647   if (Alignment > 1 && (Assembler.getBundleAlignSize() == 0 ||
648                         Assembler.getBundleAlignSize() == Alignment.value()))
649     Assembler.setBundleAlignSize(Alignment.value());
650   else
651     report_fatal_error(".bundle_align_mode cannot be changed once set");
652 }
653 
emitBundleLock(bool AlignToEnd)654 void MCELFStreamer::emitBundleLock(bool AlignToEnd) {
655   MCSection &Sec = *getCurrentSectionOnly();
656 
657   if (!getAssembler().isBundlingEnabled())
658     report_fatal_error(".bundle_lock forbidden when bundling is disabled");
659 
660   if (!isBundleLocked())
661     Sec.setBundleGroupBeforeFirstInst(true);
662 
663   if (getAssembler().getRelaxAll() && !isBundleLocked()) {
664     // TODO: drop the lock state and set directly in the fragment
665     MCDataFragment *DF = new MCDataFragment();
666     BundleGroups.push_back(DF);
667   }
668 
669   Sec.setBundleLockState(AlignToEnd ? MCSection::BundleLockedAlignToEnd
670                                     : MCSection::BundleLocked);
671 }
672 
emitBundleUnlock()673 void MCELFStreamer::emitBundleUnlock() {
674   MCSection &Sec = *getCurrentSectionOnly();
675 
676   if (!getAssembler().isBundlingEnabled())
677     report_fatal_error(".bundle_unlock forbidden when bundling is disabled");
678   else if (!isBundleLocked())
679     report_fatal_error(".bundle_unlock without matching lock");
680   else if (Sec.isBundleGroupBeforeFirstInst())
681     report_fatal_error("Empty bundle-locked group is forbidden");
682 
683   // When the -mc-relax-all flag is used, we emit instructions to fragments
684   // stored on a stack. When the bundle unlock is emitted, we pop a fragment
685   // from the stack a merge it to the one below.
686   if (getAssembler().getRelaxAll()) {
687     assert(!BundleGroups.empty() && "There are no bundle groups");
688     MCDataFragment *DF = BundleGroups.back();
689 
690     // FIXME: Use BundleGroups to track the lock state instead.
691     Sec.setBundleLockState(MCSection::NotBundleLocked);
692 
693     // FIXME: Use more separate fragments for nested groups.
694     if (!isBundleLocked()) {
695       mergeFragment(getOrCreateDataFragment(DF->getSubtargetInfo()), DF);
696       BundleGroups.pop_back();
697       delete DF;
698     }
699 
700     if (Sec.getBundleLockState() != MCSection::BundleLockedAlignToEnd)
701       getOrCreateDataFragment()->setAlignToBundleEnd(false);
702   } else
703     Sec.setBundleLockState(MCSection::NotBundleLocked);
704 }
705 
finishImpl()706 void MCELFStreamer::finishImpl() {
707   // Emit the .gnu attributes section if any attributes have been added.
708   if (!GNUAttributes.empty()) {
709     MCSection *DummyAttributeSection = nullptr;
710     createAttributesSection("gnu", ".gnu.attributes", ELF::SHT_GNU_ATTRIBUTES,
711                             DummyAttributeSection, GNUAttributes);
712   }
713 
714   // Ensure the last section gets aligned if necessary.
715   MCSection *CurSection = getCurrentSectionOnly();
716   setSectionAlignmentForBundling(getAssembler(), CurSection);
717 
718   finalizeCGProfile();
719   emitFrames(nullptr);
720 
721   this->MCObjectStreamer::finishImpl();
722 }
723 
emitThumbFunc(MCSymbol * Func)724 void MCELFStreamer::emitThumbFunc(MCSymbol *Func) {
725   llvm_unreachable("Generic ELF doesn't support this directive");
726 }
727 
emitSymbolDesc(MCSymbol * Symbol,unsigned DescValue)728 void MCELFStreamer::emitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
729   llvm_unreachable("ELF doesn't support this directive");
730 }
731 
emitZerofill(MCSection * Section,MCSymbol * Symbol,uint64_t Size,Align ByteAlignment,SMLoc Loc)732 void MCELFStreamer::emitZerofill(MCSection *Section, MCSymbol *Symbol,
733                                  uint64_t Size, Align ByteAlignment,
734                                  SMLoc Loc) {
735   llvm_unreachable("ELF doesn't support this directive");
736 }
737 
emitTBSSSymbol(MCSection * Section,MCSymbol * Symbol,uint64_t Size,Align ByteAlignment)738 void MCELFStreamer::emitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
739                                    uint64_t Size, Align ByteAlignment) {
740   llvm_unreachable("ELF doesn't support this directive");
741 }
742 
setAttributeItem(unsigned Attribute,unsigned Value,bool OverwriteExisting)743 void MCELFStreamer::setAttributeItem(unsigned Attribute, unsigned Value,
744                                      bool OverwriteExisting) {
745   // Look for existing attribute item
746   if (AttributeItem *Item = getAttributeItem(Attribute)) {
747     if (!OverwriteExisting)
748       return;
749     Item->Type = AttributeItem::NumericAttribute;
750     Item->IntValue = Value;
751     return;
752   }
753 
754   // Create new attribute item
755   AttributeItem Item = {AttributeItem::NumericAttribute, Attribute, Value,
756                         std::string(StringRef(""))};
757   Contents.push_back(Item);
758 }
759 
setAttributeItem(unsigned Attribute,StringRef Value,bool OverwriteExisting)760 void MCELFStreamer::setAttributeItem(unsigned Attribute, StringRef Value,
761                                      bool OverwriteExisting) {
762   // Look for existing attribute item
763   if (AttributeItem *Item = getAttributeItem(Attribute)) {
764     if (!OverwriteExisting)
765       return;
766     Item->Type = AttributeItem::TextAttribute;
767     Item->StringValue = std::string(Value);
768     return;
769   }
770 
771   // Create new attribute item
772   AttributeItem Item = {AttributeItem::TextAttribute, Attribute, 0,
773                         std::string(Value)};
774   Contents.push_back(Item);
775 }
776 
setAttributeItems(unsigned Attribute,unsigned IntValue,StringRef StringValue,bool OverwriteExisting)777 void MCELFStreamer::setAttributeItems(unsigned Attribute, unsigned IntValue,
778                                       StringRef StringValue,
779                                       bool OverwriteExisting) {
780   // Look for existing attribute item
781   if (AttributeItem *Item = getAttributeItem(Attribute)) {
782     if (!OverwriteExisting)
783       return;
784     Item->Type = AttributeItem::NumericAndTextAttributes;
785     Item->IntValue = IntValue;
786     Item->StringValue = std::string(StringValue);
787     return;
788   }
789 
790   // Create new attribute item
791   AttributeItem Item = {AttributeItem::NumericAndTextAttributes, Attribute,
792                         IntValue, std::string(StringValue)};
793   Contents.push_back(Item);
794 }
795 
796 MCELFStreamer::AttributeItem *
getAttributeItem(unsigned Attribute)797 MCELFStreamer::getAttributeItem(unsigned Attribute) {
798   for (size_t I = 0; I < Contents.size(); ++I)
799     if (Contents[I].Tag == Attribute)
800       return &Contents[I];
801   return nullptr;
802 }
803 
804 size_t
calculateContentSize(SmallVector<AttributeItem,64> & AttrsVec)805 MCELFStreamer::calculateContentSize(SmallVector<AttributeItem, 64> &AttrsVec) {
806   size_t Result = 0;
807   for (size_t I = 0; I < AttrsVec.size(); ++I) {
808     AttributeItem Item = AttrsVec[I];
809     switch (Item.Type) {
810     case AttributeItem::HiddenAttribute:
811       break;
812     case AttributeItem::NumericAttribute:
813       Result += getULEB128Size(Item.Tag);
814       Result += getULEB128Size(Item.IntValue);
815       break;
816     case AttributeItem::TextAttribute:
817       Result += getULEB128Size(Item.Tag);
818       Result += Item.StringValue.size() + 1; // string + '\0'
819       break;
820     case AttributeItem::NumericAndTextAttributes:
821       Result += getULEB128Size(Item.Tag);
822       Result += getULEB128Size(Item.IntValue);
823       Result += Item.StringValue.size() + 1; // string + '\0';
824       break;
825     }
826   }
827   return Result;
828 }
829 
createAttributesSection(StringRef Vendor,const Twine & Section,unsigned Type,MCSection * & AttributeSection,SmallVector<AttributeItem,64> & AttrsVec)830 void MCELFStreamer::createAttributesSection(
831     StringRef Vendor, const Twine &Section, unsigned Type,
832     MCSection *&AttributeSection, SmallVector<AttributeItem, 64> &AttrsVec) {
833   // <format-version>
834   // [ <section-length> "vendor-name"
835   // [ <file-tag> <size> <attribute>*
836   //   | <section-tag> <size> <section-number>* 0 <attribute>*
837   //   | <symbol-tag> <size> <symbol-number>* 0 <attribute>*
838   //   ]+
839   // ]*
840 
841   // Switch section to AttributeSection or get/create the section.
842   if (AttributeSection) {
843     switchSection(AttributeSection);
844   } else {
845     AttributeSection = getContext().getELFSection(Section, Type, 0);
846     switchSection(AttributeSection);
847 
848     // Format version
849     emitInt8(0x41);
850   }
851 
852   // Vendor size + Vendor name + '\0'
853   const size_t VendorHeaderSize = 4 + Vendor.size() + 1;
854 
855   // Tag + Tag Size
856   const size_t TagHeaderSize = 1 + 4;
857 
858   const size_t ContentsSize = calculateContentSize(AttrsVec);
859 
860   emitInt32(VendorHeaderSize + TagHeaderSize + ContentsSize);
861   emitBytes(Vendor);
862   emitInt8(0); // '\0'
863 
864   emitInt8(ARMBuildAttrs::File);
865   emitInt32(TagHeaderSize + ContentsSize);
866 
867   // Size should have been accounted for already, now
868   // emit each field as its type (ULEB or String)
869   for (size_t I = 0; I < AttrsVec.size(); ++I) {
870     AttributeItem Item = AttrsVec[I];
871     emitULEB128IntValue(Item.Tag);
872     switch (Item.Type) {
873     default:
874       llvm_unreachable("Invalid attribute type");
875     case AttributeItem::NumericAttribute:
876       emitULEB128IntValue(Item.IntValue);
877       break;
878     case AttributeItem::TextAttribute:
879       emitBytes(Item.StringValue);
880       emitInt8(0); // '\0'
881       break;
882     case AttributeItem::NumericAndTextAttributes:
883       emitULEB128IntValue(Item.IntValue);
884       emitBytes(Item.StringValue);
885       emitInt8(0); // '\0'
886       break;
887     }
888   }
889 
890   AttrsVec.clear();
891 }
892 
createELFStreamer(MCContext & Context,std::unique_ptr<MCAsmBackend> && MAB,std::unique_ptr<MCObjectWriter> && OW,std::unique_ptr<MCCodeEmitter> && CE,bool RelaxAll)893 MCStreamer *llvm::createELFStreamer(MCContext &Context,
894                                     std::unique_ptr<MCAsmBackend> &&MAB,
895                                     std::unique_ptr<MCObjectWriter> &&OW,
896                                     std::unique_ptr<MCCodeEmitter> &&CE,
897                                     bool RelaxAll) {
898   MCELFStreamer *S =
899       new MCELFStreamer(Context, std::move(MAB), std::move(OW), std::move(CE));
900   if (RelaxAll)
901     S->getAssembler().setRelaxAll(true);
902   return S;
903 }
904