1 //===- lib/MC/MCELFStreamer.cpp - ELF Object Output -----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file assembles .s files and emits ELF .o object files.
11 //
12 //===----------------------------------------------------------------------===//
13 
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/MCAsmLayout.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCAssembler.h"
21 #include "llvm/MC/MCCodeEmitter.h"
22 #include "llvm/MC/MCContext.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/MCSymbolELF.h"
30 #include "llvm/MC/MCSymbol.h"
31 #include "llvm/MC/MCValue.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ELF.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/TargetRegistry.h"
36 #include "llvm/Support/raw_ostream.h"
37 
38 using namespace llvm;
39 
40 bool MCELFStreamer::isBundleLocked() const {
41   return getCurrentSectionOnly()->isBundleLocked();
42 }
43 
44 MCELFStreamer::~MCELFStreamer() {
45 }
46 
47 void MCELFStreamer::mergeFragment(MCDataFragment *DF,
48                                   MCDataFragment *EF) {
49   MCAssembler &Assembler = getAssembler();
50 
51   if (Assembler.isBundlingEnabled() && Assembler.getRelaxAll()) {
52     uint64_t FSize = EF->getContents().size();
53 
54     if (FSize > Assembler.getBundleAlignSize())
55       report_fatal_error("Fragment can't be larger than a bundle size");
56 
57     uint64_t RequiredBundlePadding = computeBundlePadding(
58         Assembler, EF, DF->getContents().size(), FSize);
59 
60     if (RequiredBundlePadding > UINT8_MAX)
61       report_fatal_error("Padding cannot exceed 255 bytes");
62 
63     if (RequiredBundlePadding > 0) {
64       SmallString<256> Code;
65       raw_svector_ostream VecOS(Code);
66       MCObjectWriter *OW = Assembler.getBackend().createObjectWriter(VecOS);
67 
68       EF->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
69 
70       Assembler.writeFragmentPadding(*EF, FSize, OW);
71       delete OW;
72 
73       DF->getContents().append(Code.begin(), Code.end());
74     }
75   }
76 
77   flushPendingLabels(DF, DF->getContents().size());
78 
79   for (unsigned i = 0, e = EF->getFixups().size(); i != e; ++i) {
80     EF->getFixups()[i].setOffset(EF->getFixups()[i].getOffset() +
81                                  DF->getContents().size());
82     DF->getFixups().push_back(EF->getFixups()[i]);
83   }
84   DF->setHasInstructions(true);
85   DF->getContents().append(EF->getContents().begin(), EF->getContents().end());
86 }
87 
88 void MCELFStreamer::InitSections(bool NoExecStack) {
89   MCContext &Ctx = getContext();
90   SwitchSection(Ctx.getObjectFileInfo()->getTextSection());
91   EmitCodeAlignment(4);
92 
93   if (NoExecStack)
94     SwitchSection(Ctx.getAsmInfo()->getNonexecutableStackSection(Ctx));
95 }
96 
97 void MCELFStreamer::EmitLabel(MCSymbol *S) {
98   auto *Symbol = cast<MCSymbolELF>(S);
99   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
100 
101   MCObjectStreamer::EmitLabel(Symbol);
102 
103   const MCSectionELF &Section =
104       static_cast<const MCSectionELF &>(*getCurrentSectionOnly());
105   if (Section.getFlags() & ELF::SHF_TLS)
106     Symbol->setType(ELF::STT_TLS);
107 }
108 
109 void MCELFStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
110   // Let the target do whatever target specific stuff it needs to do.
111   getAssembler().getBackend().handleAssemblerFlag(Flag);
112   // Do any generic stuff we need to do.
113   switch (Flag) {
114   case MCAF_SyntaxUnified: return; // no-op here.
115   case MCAF_Code16: return; // Change parsing mode; no-op here.
116   case MCAF_Code32: return; // Change parsing mode; no-op here.
117   case MCAF_Code64: return; // Change parsing mode; no-op here.
118   case MCAF_SubsectionsViaSymbols:
119     getAssembler().setSubsectionsViaSymbols(true);
120     return;
121   }
122 
123   llvm_unreachable("invalid assembler flag!");
124 }
125 
126 // If bundle alignment is used and there are any instructions in the section, it
127 // needs to be aligned to at least the bundle size.
128 static void setSectionAlignmentForBundling(const MCAssembler &Assembler,
129                                            MCSection *Section) {
130   if (Section && Assembler.isBundlingEnabled() && Section->hasInstructions() &&
131       Section->getAlignment() < Assembler.getBundleAlignSize())
132     Section->setAlignment(Assembler.getBundleAlignSize());
133 }
134 
135 void MCELFStreamer::ChangeSection(MCSection *Section,
136                                   const MCExpr *Subsection) {
137   MCSection *CurSection = getCurrentSectionOnly();
138   if (CurSection && isBundleLocked())
139     report_fatal_error("Unterminated .bundle_lock when changing a section");
140 
141   MCAssembler &Asm = getAssembler();
142   // Ensure the previous section gets aligned if necessary.
143   setSectionAlignmentForBundling(Asm, CurSection);
144   auto *SectionELF = static_cast<const MCSectionELF *>(Section);
145   const MCSymbol *Grp = SectionELF->getGroup();
146   if (Grp)
147     Asm.registerSymbol(*Grp);
148 
149   this->MCObjectStreamer::ChangeSection(Section, Subsection);
150   MCContext &Ctx = getContext();
151   auto *Begin = cast_or_null<MCSymbolELF>(Section->getBeginSymbol());
152   if (!Begin) {
153     Begin = Ctx.getOrCreateSectionSymbol(*SectionELF);
154     Section->setBeginSymbol(Begin);
155   }
156   if (Begin->isUndefined()) {
157     Asm.registerSymbol(*Begin);
158     Begin->setType(ELF::STT_SECTION);
159   }
160 }
161 
162 void MCELFStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
163   getAssembler().registerSymbol(*Symbol);
164   const MCExpr *Value = MCSymbolRefExpr::create(
165       Symbol, MCSymbolRefExpr::VK_WEAKREF, getContext());
166   Alias->setVariableValue(Value);
167 }
168 
169 // When GNU as encounters more than one .type declaration for an object it seems
170 // to use a mechanism similar to the one below to decide which type is actually
171 // used in the object file.  The greater of T1 and T2 is selected based on the
172 // following ordering:
173 //  STT_NOTYPE < STT_OBJECT < STT_FUNC < STT_GNU_IFUNC < STT_TLS < anything else
174 // If neither T1 < T2 nor T2 < T1 according to this ordering, use T2 (the user
175 // provided type).
176 static unsigned CombineSymbolTypes(unsigned T1, unsigned T2) {
177   for (unsigned Type : {ELF::STT_NOTYPE, ELF::STT_OBJECT, ELF::STT_FUNC,
178                         ELF::STT_GNU_IFUNC, ELF::STT_TLS}) {
179     if (T1 == Type)
180       return T2;
181     if (T2 == Type)
182       return T1;
183   }
184 
185   return T2;
186 }
187 
188 bool MCELFStreamer::EmitSymbolAttribute(MCSymbol *S, MCSymbolAttr Attribute) {
189   auto *Symbol = cast<MCSymbolELF>(S);
190   // Indirect symbols are handled differently, to match how 'as' handles
191   // them. This makes writing matching .o files easier.
192   if (Attribute == MCSA_IndirectSymbol) {
193     // Note that we intentionally cannot use the symbol data here; this is
194     // important for matching the string table that 'as' generates.
195     IndirectSymbolData ISD;
196     ISD.Symbol = Symbol;
197     ISD.Section = getCurrentSectionOnly();
198     getAssembler().getIndirectSymbols().push_back(ISD);
199     return true;
200   }
201 
202   // Adding a symbol attribute always introduces the symbol, note that an
203   // important side effect of calling registerSymbol here is to register
204   // the symbol with the assembler.
205   getAssembler().registerSymbol(*Symbol);
206 
207   // The implementation of symbol attributes is designed to match 'as', but it
208   // leaves much to desired. It doesn't really make sense to arbitrarily add and
209   // remove flags, but 'as' allows this (in particular, see .desc).
210   //
211   // In the future it might be worth trying to make these operations more well
212   // defined.
213   switch (Attribute) {
214   case MCSA_LazyReference:
215   case MCSA_Reference:
216   case MCSA_SymbolResolver:
217   case MCSA_PrivateExtern:
218   case MCSA_WeakDefinition:
219   case MCSA_WeakDefAutoPrivate:
220   case MCSA_Invalid:
221   case MCSA_IndirectSymbol:
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     Symbol->setExternal(true);
232     break;
233 
234   case MCSA_Global:
235     Symbol->setBinding(ELF::STB_GLOBAL);
236     Symbol->setExternal(true);
237     break;
238 
239   case MCSA_WeakReference:
240   case MCSA_Weak:
241     Symbol->setBinding(ELF::STB_WEAK);
242     Symbol->setExternal(true);
243     break;
244 
245   case MCSA_Local:
246     Symbol->setBinding(ELF::STB_LOCAL);
247     Symbol->setExternal(false);
248     break;
249 
250   case MCSA_ELF_TypeFunction:
251     Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_FUNC));
252     break;
253 
254   case MCSA_ELF_TypeIndFunction:
255     Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_GNU_IFUNC));
256     break;
257 
258   case MCSA_ELF_TypeObject:
259     Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_OBJECT));
260     break;
261 
262   case MCSA_ELF_TypeTLS:
263     Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_TLS));
264     break;
265 
266   case MCSA_ELF_TypeCommon:
267     // TODO: Emit these as a common symbol.
268     Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_OBJECT));
269     break;
270 
271   case MCSA_ELF_TypeNoType:
272     Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_NOTYPE));
273     break;
274 
275   case MCSA_Protected:
276     Symbol->setVisibility(ELF::STV_PROTECTED);
277     break;
278 
279   case MCSA_Hidden:
280     Symbol->setVisibility(ELF::STV_HIDDEN);
281     break;
282 
283   case MCSA_Internal:
284     Symbol->setVisibility(ELF::STV_INTERNAL);
285     break;
286 
287   case MCSA_AltEntry:
288     llvm_unreachable("ELF doesn't support this attribute");
289   }
290 
291   return true;
292 }
293 
294 void MCELFStreamer::EmitCommonSymbol(MCSymbol *S, uint64_t Size,
295                                      unsigned ByteAlignment) {
296   auto *Symbol = cast<MCSymbolELF>(S);
297   getAssembler().registerSymbol(*Symbol);
298 
299   if (!Symbol->isBindingSet()) {
300     Symbol->setBinding(ELF::STB_GLOBAL);
301     Symbol->setExternal(true);
302   }
303 
304   Symbol->setType(ELF::STT_OBJECT);
305 
306   if (Symbol->getBinding() == ELF::STB_LOCAL) {
307     MCSection &Section = *getAssembler().getContext().getELFSection(
308         ".bss", ELF::SHT_NOBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
309     MCSectionSubPair P = getCurrentSection();
310     SwitchSection(&Section);
311 
312     EmitValueToAlignment(ByteAlignment, 0, 1, 0);
313     EmitLabel(Symbol);
314     EmitZeros(Size);
315 
316     // Update the maximum alignment of the section if necessary.
317     if (ByteAlignment > Section.getAlignment())
318       Section.setAlignment(ByteAlignment);
319 
320     SwitchSection(P.first, P.second);
321   } else {
322     if(Symbol->declareCommon(Size, ByteAlignment))
323       report_fatal_error("Symbol: " + Symbol->getName() +
324                          " redeclared as different type");
325   }
326 
327   cast<MCSymbolELF>(Symbol)
328       ->setSize(MCConstantExpr::create(Size, getContext()));
329 }
330 
331 void MCELFStreamer::emitELFSize(MCSymbolELF *Symbol, const MCExpr *Value) {
332   Symbol->setSize(Value);
333 }
334 
335 void MCELFStreamer::EmitLocalCommonSymbol(MCSymbol *S, uint64_t Size,
336                                           unsigned ByteAlignment) {
337   auto *Symbol = cast<MCSymbolELF>(S);
338   // FIXME: Should this be caught and done earlier?
339   getAssembler().registerSymbol(*Symbol);
340   Symbol->setBinding(ELF::STB_LOCAL);
341   Symbol->setExternal(false);
342   EmitCommonSymbol(Symbol, Size, ByteAlignment);
343 }
344 
345 void MCELFStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
346                                   SMLoc Loc) {
347   if (isBundleLocked())
348     report_fatal_error("Emitting values inside a locked bundle is forbidden");
349   fixSymbolsInTLSFixups(Value);
350   MCObjectStreamer::EmitValueImpl(Value, Size, Loc);
351 }
352 
353 void MCELFStreamer::EmitValueToAlignment(unsigned ByteAlignment,
354                                          int64_t Value,
355                                          unsigned ValueSize,
356                                          unsigned MaxBytesToEmit) {
357   if (isBundleLocked())
358     report_fatal_error("Emitting values inside a locked bundle is forbidden");
359   MCObjectStreamer::EmitValueToAlignment(ByteAlignment, Value,
360                                          ValueSize, MaxBytesToEmit);
361 }
362 
363 // Add a symbol for the file name of this module. They start after the
364 // null symbol and don't count as normal symbol, i.e. a non-STT_FILE symbol
365 // with the same name may appear.
366 void MCELFStreamer::EmitFileDirective(StringRef Filename) {
367   getAssembler().addFileName(Filename);
368 }
369 
370 void MCELFStreamer::EmitIdent(StringRef IdentString) {
371   MCSection *Comment = getAssembler().getContext().getELFSection(
372       ".comment", ELF::SHT_PROGBITS, ELF::SHF_MERGE | ELF::SHF_STRINGS, 1, "");
373   PushSection();
374   SwitchSection(Comment);
375   if (!SeenIdent) {
376     EmitIntValue(0, 1);
377     SeenIdent = true;
378   }
379   EmitBytes(IdentString);
380   EmitIntValue(0, 1);
381   PopSection();
382 }
383 
384 void MCELFStreamer::fixSymbolsInTLSFixups(const MCExpr *expr) {
385   switch (expr->getKind()) {
386   case MCExpr::Target:
387     cast<MCTargetExpr>(expr)->fixELFSymbolsInTLSFixups(getAssembler());
388     break;
389   case MCExpr::Constant:
390     break;
391 
392   case MCExpr::Binary: {
393     const MCBinaryExpr *be = cast<MCBinaryExpr>(expr);
394     fixSymbolsInTLSFixups(be->getLHS());
395     fixSymbolsInTLSFixups(be->getRHS());
396     break;
397   }
398 
399   case MCExpr::SymbolRef: {
400     const MCSymbolRefExpr &symRef = *cast<MCSymbolRefExpr>(expr);
401     switch (symRef.getKind()) {
402     default:
403       return;
404     case MCSymbolRefExpr::VK_GOTTPOFF:
405     case MCSymbolRefExpr::VK_INDNTPOFF:
406     case MCSymbolRefExpr::VK_NTPOFF:
407     case MCSymbolRefExpr::VK_GOTNTPOFF:
408     case MCSymbolRefExpr::VK_TLSGD:
409     case MCSymbolRefExpr::VK_TLSLD:
410     case MCSymbolRefExpr::VK_TLSLDM:
411     case MCSymbolRefExpr::VK_TPOFF:
412     case MCSymbolRefExpr::VK_TPREL:
413     case MCSymbolRefExpr::VK_DTPOFF:
414     case MCSymbolRefExpr::VK_DTPREL:
415     case MCSymbolRefExpr::VK_Mips_TLSGD:
416     case MCSymbolRefExpr::VK_Mips_GOTTPREL:
417     case MCSymbolRefExpr::VK_Mips_TPREL_HI:
418     case MCSymbolRefExpr::VK_Mips_TPREL_LO:
419     case MCSymbolRefExpr::VK_PPC_DTPMOD:
420     case MCSymbolRefExpr::VK_PPC_TPREL_LO:
421     case MCSymbolRefExpr::VK_PPC_TPREL_HI:
422     case MCSymbolRefExpr::VK_PPC_TPREL_HA:
423     case MCSymbolRefExpr::VK_PPC_TPREL_HIGHER:
424     case MCSymbolRefExpr::VK_PPC_TPREL_HIGHERA:
425     case MCSymbolRefExpr::VK_PPC_TPREL_HIGHEST:
426     case MCSymbolRefExpr::VK_PPC_TPREL_HIGHESTA:
427     case MCSymbolRefExpr::VK_PPC_DTPREL_LO:
428     case MCSymbolRefExpr::VK_PPC_DTPREL_HI:
429     case MCSymbolRefExpr::VK_PPC_DTPREL_HA:
430     case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHER:
431     case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHERA:
432     case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHEST:
433     case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHESTA:
434     case MCSymbolRefExpr::VK_PPC_GOT_TPREL:
435     case MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO:
436     case MCSymbolRefExpr::VK_PPC_GOT_TPREL_HI:
437     case MCSymbolRefExpr::VK_PPC_GOT_TPREL_HA:
438     case MCSymbolRefExpr::VK_PPC_GOT_DTPREL:
439     case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_LO:
440     case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_HI:
441     case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_HA:
442     case MCSymbolRefExpr::VK_PPC_TLS:
443     case MCSymbolRefExpr::VK_PPC_GOT_TLSGD:
444     case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO:
445     case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HI:
446     case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HA:
447     case MCSymbolRefExpr::VK_PPC_TLSGD:
448     case MCSymbolRefExpr::VK_PPC_GOT_TLSLD:
449     case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO:
450     case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HI:
451     case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HA:
452     case MCSymbolRefExpr::VK_PPC_TLSLD:
453       break;
454     }
455     getAssembler().registerSymbol(symRef.getSymbol());
456     cast<MCSymbolELF>(symRef.getSymbol()).setType(ELF::STT_TLS);
457     break;
458   }
459 
460   case MCExpr::Unary:
461     fixSymbolsInTLSFixups(cast<MCUnaryExpr>(expr)->getSubExpr());
462     break;
463   }
464 }
465 
466 void MCELFStreamer::EmitInstToFragment(const MCInst &Inst,
467                                        const MCSubtargetInfo &STI) {
468   this->MCObjectStreamer::EmitInstToFragment(Inst, STI);
469   MCRelaxableFragment &F = *cast<MCRelaxableFragment>(getCurrentFragment());
470 
471   for (unsigned i = 0, e = F.getFixups().size(); i != e; ++i)
472     fixSymbolsInTLSFixups(F.getFixups()[i].getValue());
473 }
474 
475 void MCELFStreamer::EmitInstToData(const MCInst &Inst,
476                                    const MCSubtargetInfo &STI) {
477   MCAssembler &Assembler = getAssembler();
478   SmallVector<MCFixup, 4> Fixups;
479   SmallString<256> Code;
480   raw_svector_ostream VecOS(Code);
481   Assembler.getEmitter().encodeInstruction(Inst, VecOS, Fixups, STI);
482 
483   for (unsigned i = 0, e = Fixups.size(); i != e; ++i)
484     fixSymbolsInTLSFixups(Fixups[i].getValue());
485 
486   // There are several possibilities here:
487   //
488   // If bundling is disabled, append the encoded instruction to the current data
489   // fragment (or create a new such fragment if the current fragment is not a
490   // data fragment).
491   //
492   // If bundling is enabled:
493   // - If we're not in a bundle-locked group, emit the instruction into a
494   //   fragment of its own. If there are no fixups registered for the
495   //   instruction, emit a MCCompactEncodedInstFragment. Otherwise, emit a
496   //   MCDataFragment.
497   // - If we're in a bundle-locked group, append the instruction to the current
498   //   data fragment because we want all the instructions in a group to get into
499   //   the same fragment. Be careful not to do that for the first instruction in
500   //   the group, though.
501   MCDataFragment *DF;
502 
503   if (Assembler.isBundlingEnabled()) {
504     MCSection &Sec = *getCurrentSectionOnly();
505     if (Assembler.getRelaxAll() && isBundleLocked())
506       // If the -mc-relax-all flag is used and we are bundle-locked, we re-use
507       // the current bundle group.
508       DF = BundleGroups.back();
509     else if (Assembler.getRelaxAll() && !isBundleLocked())
510       // When not in a bundle-locked group and the -mc-relax-all flag is used,
511       // we create a new temporary fragment which will be later merged into
512       // the current fragment.
513       DF = new MCDataFragment();
514     else if (isBundleLocked() && !Sec.isBundleGroupBeforeFirstInst())
515       // If we are bundle-locked, we re-use the current fragment.
516       // The bundle-locking directive ensures this is a new data fragment.
517       DF = cast<MCDataFragment>(getCurrentFragment());
518     else if (!isBundleLocked() && Fixups.size() == 0) {
519       // Optimize memory usage by emitting the instruction to a
520       // MCCompactEncodedInstFragment when not in a bundle-locked group and
521       // there are no fixups registered.
522       MCCompactEncodedInstFragment *CEIF = new MCCompactEncodedInstFragment();
523       insert(CEIF);
524       CEIF->getContents().append(Code.begin(), Code.end());
525       return;
526     } else {
527       DF = new MCDataFragment();
528       insert(DF);
529     }
530     if (Sec.getBundleLockState() == MCSection::BundleLockedAlignToEnd) {
531       // If this fragment is for a group marked "align_to_end", set a flag
532       // in the fragment. This can happen after the fragment has already been
533       // created if there are nested bundle_align groups and an inner one
534       // is the one marked align_to_end.
535       DF->setAlignToBundleEnd(true);
536     }
537 
538     // We're now emitting an instruction in a bundle group, so this flag has
539     // to be turned off.
540     Sec.setBundleGroupBeforeFirstInst(false);
541   } else {
542     DF = getOrCreateDataFragment();
543   }
544 
545   // Add the fixups and data.
546   for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
547     Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
548     DF->getFixups().push_back(Fixups[i]);
549   }
550   DF->setHasInstructions(true);
551   DF->getContents().append(Code.begin(), Code.end());
552 
553   if (Assembler.isBundlingEnabled() && Assembler.getRelaxAll()) {
554     if (!isBundleLocked()) {
555       mergeFragment(getOrCreateDataFragment(), DF);
556       delete DF;
557     }
558   }
559 }
560 
561 void MCELFStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
562   assert(AlignPow2 <= 30 && "Invalid bundle alignment");
563   MCAssembler &Assembler = getAssembler();
564   if (AlignPow2 > 0 && (Assembler.getBundleAlignSize() == 0 ||
565                         Assembler.getBundleAlignSize() == 1U << AlignPow2))
566     Assembler.setBundleAlignSize(1U << AlignPow2);
567   else
568     report_fatal_error(".bundle_align_mode cannot be changed once set");
569 }
570 
571 void MCELFStreamer::EmitBundleLock(bool AlignToEnd) {
572   MCSection &Sec = *getCurrentSectionOnly();
573 
574   // Sanity checks
575   //
576   if (!getAssembler().isBundlingEnabled())
577     report_fatal_error(".bundle_lock forbidden when bundling is disabled");
578 
579   if (!isBundleLocked())
580     Sec.setBundleGroupBeforeFirstInst(true);
581 
582   if (getAssembler().getRelaxAll() && !isBundleLocked()) {
583     // TODO: drop the lock state and set directly in the fragment
584     MCDataFragment *DF = new MCDataFragment();
585     BundleGroups.push_back(DF);
586   }
587 
588   Sec.setBundleLockState(AlignToEnd ? MCSection::BundleLockedAlignToEnd
589                                     : MCSection::BundleLocked);
590 }
591 
592 void MCELFStreamer::EmitBundleUnlock() {
593   MCSection &Sec = *getCurrentSectionOnly();
594 
595   // Sanity checks
596   if (!getAssembler().isBundlingEnabled())
597     report_fatal_error(".bundle_unlock forbidden when bundling is disabled");
598   else if (!isBundleLocked())
599     report_fatal_error(".bundle_unlock without matching lock");
600   else if (Sec.isBundleGroupBeforeFirstInst())
601     report_fatal_error("Empty bundle-locked group is forbidden");
602 
603   // When the -mc-relax-all flag is used, we emit instructions to fragments
604   // stored on a stack. When the bundle unlock is emitted, we pop a fragment
605   // from the stack a merge it to the one below.
606   if (getAssembler().getRelaxAll()) {
607     assert(!BundleGroups.empty() && "There are no bundle groups");
608     MCDataFragment *DF = BundleGroups.back();
609 
610     // FIXME: Use BundleGroups to track the lock state instead.
611     Sec.setBundleLockState(MCSection::NotBundleLocked);
612 
613     // FIXME: Use more separate fragments for nested groups.
614     if (!isBundleLocked()) {
615       mergeFragment(getOrCreateDataFragment(), DF);
616       BundleGroups.pop_back();
617       delete DF;
618     }
619 
620     if (Sec.getBundleLockState() != MCSection::BundleLockedAlignToEnd)
621       getOrCreateDataFragment()->setAlignToBundleEnd(false);
622   } else
623     Sec.setBundleLockState(MCSection::NotBundleLocked);
624 }
625 
626 void MCELFStreamer::FinishImpl() {
627   // Ensure the last section gets aligned if necessary.
628   MCSection *CurSection = getCurrentSectionOnly();
629   setSectionAlignmentForBundling(getAssembler(), CurSection);
630 
631   EmitFrames(nullptr);
632 
633   this->MCObjectStreamer::FinishImpl();
634 }
635 
636 MCStreamer *llvm::createELFStreamer(MCContext &Context, MCAsmBackend &MAB,
637                                     raw_pwrite_stream &OS, MCCodeEmitter *CE,
638                                     bool RelaxAll) {
639   MCELFStreamer *S = new MCELFStreamer(Context, MAB, OS, CE);
640   if (RelaxAll)
641     S->getAssembler().setRelaxAll(true);
642   return S;
643 }
644 
645 void MCELFStreamer::EmitThumbFunc(MCSymbol *Func) {
646   llvm_unreachable("Generic ELF doesn't support this directive");
647 }
648 
649 void MCELFStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
650   llvm_unreachable("ELF doesn't support this directive");
651 }
652 
653 void MCELFStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
654   llvm_unreachable("ELF doesn't support this directive");
655 }
656 
657 void MCELFStreamer::EmitCOFFSymbolStorageClass(int StorageClass) {
658   llvm_unreachable("ELF doesn't support this directive");
659 }
660 
661 void MCELFStreamer::EmitCOFFSymbolType(int Type) {
662   llvm_unreachable("ELF doesn't support this directive");
663 }
664 
665 void MCELFStreamer::EndCOFFSymbolDef() {
666   llvm_unreachable("ELF doesn't support this directive");
667 }
668 
669 void MCELFStreamer::EmitZerofill(MCSection *Section, MCSymbol *Symbol,
670                                  uint64_t Size, unsigned ByteAlignment) {
671   llvm_unreachable("ELF doesn't support this directive");
672 }
673 
674 void MCELFStreamer::EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
675                                    uint64_t Size, unsigned ByteAlignment) {
676   llvm_unreachable("ELF doesn't support this directive");
677 }
678