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