Move registerSection out of line and reduce #includes. NFC.
[oota-llvm.git] / lib / MC / MCAssembler.cpp
1 //===- lib/MC/MCAssembler.cpp - Assembler Backend Implementation ----------===//
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 #include "llvm/MC/MCAssembler.h"
11 #include "llvm/ADT/Statistic.h"
12 #include "llvm/ADT/StringExtras.h"
13 #include "llvm/ADT/Twine.h"
14 #include "llvm/MC/MCAsmBackend.h"
15 #include "llvm/MC/MCAsmInfo.h"
16 #include "llvm/MC/MCAsmLayout.h"
17 #include "llvm/MC/MCCodeEmitter.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCDwarf.h"
20 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCFixupKindInfo.h"
22 #include "llvm/MC/MCObjectWriter.h"
23 #include "llvm/MC/MCSection.h"
24 #include "llvm/MC/MCSectionELF.h"
25 #include "llvm/MC/MCSymbol.h"
26 #include "llvm/MC/MCValue.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/LEB128.h"
30 #include "llvm/Support/TargetRegistry.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include <tuple>
33 using namespace llvm;
34
35 #define DEBUG_TYPE "assembler"
36
37 namespace {
38 namespace stats {
39 STATISTIC(EmittedFragments, "Number of emitted assembler fragments - total");
40 STATISTIC(EmittedRelaxableFragments,
41           "Number of emitted assembler fragments - relaxable");
42 STATISTIC(EmittedDataFragments,
43           "Number of emitted assembler fragments - data");
44 STATISTIC(EmittedCompactEncodedInstFragments,
45           "Number of emitted assembler fragments - compact encoded inst");
46 STATISTIC(EmittedAlignFragments,
47           "Number of emitted assembler fragments - align");
48 STATISTIC(EmittedFillFragments,
49           "Number of emitted assembler fragments - fill");
50 STATISTIC(EmittedOrgFragments,
51           "Number of emitted assembler fragments - org");
52 STATISTIC(evaluateFixup, "Number of evaluated fixups");
53 STATISTIC(FragmentLayouts, "Number of fragment layouts");
54 STATISTIC(ObjectBytes, "Number of emitted object file bytes");
55 STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
56 STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
57 }
58 }
59
60 // FIXME FIXME FIXME: There are number of places in this file where we convert
61 // what is a 64-bit assembler value used for computation into a value in the
62 // object file, which may truncate it. We should detect that truncation where
63 // invalid and report errors back.
64
65 /* *** */
66
67 MCAsmLayout::MCAsmLayout(MCAssembler &Asm)
68   : Assembler(Asm), LastValidFragment()
69  {
70   // Compute the section layout order. Virtual sections must go last.
71   for (MCSection &Sec : Asm)
72     if (!Sec.isVirtualSection())
73       SectionOrder.push_back(&Sec);
74   for (MCSection &Sec : Asm)
75     if (Sec.isVirtualSection())
76       SectionOrder.push_back(&Sec);
77 }
78
79 bool MCAsmLayout::isFragmentValid(const MCFragment *F) const {
80   const MCSection *Sec = F->getParent();
81   const MCFragment *LastValid = LastValidFragment.lookup(Sec);
82   if (!LastValid)
83     return false;
84   assert(LastValid->getParent() == Sec);
85   return F->getLayoutOrder() <= LastValid->getLayoutOrder();
86 }
87
88 void MCAsmLayout::invalidateFragmentsFrom(MCFragment *F) {
89   // If this fragment wasn't already valid, we don't need to do anything.
90   if (!isFragmentValid(F))
91     return;
92
93   // Otherwise, reset the last valid fragment to the previous fragment
94   // (if this is the first fragment, it will be NULL).
95   LastValidFragment[F->getParent()] = F->getPrevNode();
96 }
97
98 void MCAsmLayout::ensureValid(const MCFragment *F) const {
99   MCSection *Sec = F->getParent();
100   MCFragment *Cur = LastValidFragment[Sec];
101   if (!Cur)
102     Cur = Sec->begin();
103   else
104     Cur = Cur->getNextNode();
105
106   // Advance the layout position until the fragment is valid.
107   while (!isFragmentValid(F)) {
108     assert(Cur && "Layout bookkeeping error");
109     const_cast<MCAsmLayout*>(this)->layoutFragment(Cur);
110     Cur = Cur->getNextNode();
111   }
112 }
113
114 uint64_t MCAsmLayout::getFragmentOffset(const MCFragment *F) const {
115   ensureValid(F);
116   assert(F->Offset != ~UINT64_C(0) && "Address not set!");
117   return F->Offset;
118 }
119
120 // Simple getSymbolOffset helper for the non-varibale case.
121 static bool getLabelOffset(const MCAsmLayout &Layout, const MCSymbol &S,
122                            bool ReportError, uint64_t &Val) {
123   if (!S.getFragment()) {
124     if (ReportError)
125       report_fatal_error("unable to evaluate offset to undefined symbol '" +
126                          S.getName() + "'");
127     return false;
128   }
129   Val = Layout.getFragmentOffset(S.getFragment()) + S.getOffset();
130   return true;
131 }
132
133 static bool getSymbolOffsetImpl(const MCAsmLayout &Layout, const MCSymbol &S,
134                                 bool ReportError, uint64_t &Val) {
135   if (!S.isVariable())
136     return getLabelOffset(Layout, S, ReportError, Val);
137
138   // If SD is a variable, evaluate it.
139   MCValue Target;
140   if (!S.getVariableValue()->evaluateAsValue(Target, Layout))
141     report_fatal_error("unable to evaluate offset for variable '" +
142                        S.getName() + "'");
143
144   uint64_t Offset = Target.getConstant();
145
146   const MCSymbolRefExpr *A = Target.getSymA();
147   if (A) {
148     uint64_t ValA;
149     if (!getLabelOffset(Layout, A->getSymbol(), ReportError, ValA))
150       return false;
151     Offset += ValA;
152   }
153
154   const MCSymbolRefExpr *B = Target.getSymB();
155   if (B) {
156     uint64_t ValB;
157     if (!getLabelOffset(Layout, B->getSymbol(), ReportError, ValB))
158       return false;
159     Offset -= ValB;
160   }
161
162   Val = Offset;
163   return true;
164 }
165
166 bool MCAsmLayout::getSymbolOffset(const MCSymbol &S, uint64_t &Val) const {
167   return getSymbolOffsetImpl(*this, S, false, Val);
168 }
169
170 uint64_t MCAsmLayout::getSymbolOffset(const MCSymbol &S) const {
171   uint64_t Val;
172   getSymbolOffsetImpl(*this, S, true, Val);
173   return Val;
174 }
175
176 const MCSymbol *MCAsmLayout::getBaseSymbol(const MCSymbol &Symbol) const {
177   if (!Symbol.isVariable())
178     return &Symbol;
179
180   const MCExpr *Expr = Symbol.getVariableValue();
181   MCValue Value;
182   if (!Expr->evaluateAsValue(Value, *this))
183     llvm_unreachable("Invalid Expression");
184
185   const MCSymbolRefExpr *RefB = Value.getSymB();
186   if (RefB)
187     Assembler.getContext().reportFatalError(
188         SMLoc(), Twine("symbol '") + RefB->getSymbol().getName() +
189                      "' could not be evaluated in a subtraction expression");
190
191   const MCSymbolRefExpr *A = Value.getSymA();
192   if (!A)
193     return nullptr;
194
195   const MCSymbol &ASym = A->getSymbol();
196   const MCAssembler &Asm = getAssembler();
197   if (ASym.isCommon()) {
198     // FIXME: we should probably add a SMLoc to MCExpr.
199     Asm.getContext().reportFatalError(SMLoc(),
200                                 "Common symbol " + ASym.getName() +
201                                     " cannot be used in assignment expr");
202   }
203
204   return &ASym;
205 }
206
207 uint64_t MCAsmLayout::getSectionAddressSize(const MCSection *Sec) const {
208   // The size is the last fragment's end offset.
209   const MCFragment &F = Sec->getFragmentList().back();
210   return getFragmentOffset(&F) + getAssembler().computeFragmentSize(*this, F);
211 }
212
213 uint64_t MCAsmLayout::getSectionFileSize(const MCSection *Sec) const {
214   // Virtual sections have no file size.
215   if (Sec->isVirtualSection())
216     return 0;
217
218   // Otherwise, the file size is the same as the address space size.
219   return getSectionAddressSize(Sec);
220 }
221
222 uint64_t llvm::computeBundlePadding(const MCAssembler &Assembler,
223                                     const MCFragment *F,
224                                     uint64_t FOffset, uint64_t FSize) {
225   uint64_t BundleSize = Assembler.getBundleAlignSize();
226   assert(BundleSize > 0 &&
227          "computeBundlePadding should only be called if bundling is enabled");
228   uint64_t BundleMask = BundleSize - 1;
229   uint64_t OffsetInBundle = FOffset & BundleMask;
230   uint64_t EndOfFragment = OffsetInBundle + FSize;
231
232   // There are two kinds of bundling restrictions:
233   //
234   // 1) For alignToBundleEnd(), add padding to ensure that the fragment will
235   //    *end* on a bundle boundary.
236   // 2) Otherwise, check if the fragment would cross a bundle boundary. If it
237   //    would, add padding until the end of the bundle so that the fragment
238   //    will start in a new one.
239   if (F->alignToBundleEnd()) {
240     // Three possibilities here:
241     //
242     // A) The fragment just happens to end at a bundle boundary, so we're good.
243     // B) The fragment ends before the current bundle boundary: pad it just
244     //    enough to reach the boundary.
245     // C) The fragment ends after the current bundle boundary: pad it until it
246     //    reaches the end of the next bundle boundary.
247     //
248     // Note: this code could be made shorter with some modulo trickery, but it's
249     // intentionally kept in its more explicit form for simplicity.
250     if (EndOfFragment == BundleSize)
251       return 0;
252     else if (EndOfFragment < BundleSize)
253       return BundleSize - EndOfFragment;
254     else { // EndOfFragment > BundleSize
255       return 2 * BundleSize - EndOfFragment;
256     }
257   } else if (OffsetInBundle > 0 && EndOfFragment > BundleSize)
258     return BundleSize - OffsetInBundle;
259   else
260     return 0;
261 }
262
263 /* *** */
264
265 void ilist_node_traits<MCFragment>::deleteNode(MCFragment *V) {
266   V->destroy();
267 }
268
269 MCFragment::MCFragment() : Kind(FragmentType(~0)), HasInstructions(false),
270                            AlignToBundleEnd(false), BundlePadding(0) {
271 }
272
273 MCFragment::~MCFragment() { }
274
275 MCFragment::MCFragment(FragmentType Kind, bool HasInstructions,
276                        uint8_t BundlePadding, MCSection *Parent)
277     : Kind(Kind), HasInstructions(HasInstructions), AlignToBundleEnd(false),
278       BundlePadding(BundlePadding), Parent(Parent), Atom(nullptr),
279       Offset(~UINT64_C(0)) {
280   if (Parent)
281     Parent->getFragmentList().push_back(this);
282 }
283
284 void MCFragment::destroy() {
285   // First check if we are the sentinal.
286   if (Kind == FragmentType(~0)) {
287     delete this;
288     return;
289   }
290
291   switch (Kind) {
292     case FT_Align:
293       delete cast<MCAlignFragment>(this);
294       return;
295     case FT_Data:
296       delete cast<MCDataFragment>(this);
297       return;
298     case FT_CompactEncodedInst:
299       delete cast<MCCompactEncodedInstFragment>(this);
300       return;
301     case FT_Fill:
302       delete cast<MCFillFragment>(this);
303       return;
304     case FT_Relaxable:
305       delete cast<MCRelaxableFragment>(this);
306       return;
307     case FT_Org:
308       delete cast<MCOrgFragment>(this);
309       return;
310     case FT_Dwarf:
311       delete cast<MCDwarfLineAddrFragment>(this);
312       return;
313     case FT_DwarfFrame:
314       delete cast<MCDwarfCallFrameFragment>(this);
315       return;
316     case FT_LEB:
317       delete cast<MCLEBFragment>(this);
318       return;
319     case FT_SafeSEH:
320       delete cast<MCSafeSEHFragment>(this);
321       return;
322   }
323 }
324
325 /* *** */
326
327 MCAssembler::MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
328                          MCCodeEmitter &Emitter_, MCObjectWriter &Writer_)
329     : Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
330       BundleAlignSize(0), RelaxAll(false), SubsectionsViaSymbols(false),
331       ELFHeaderEFlags(0) {
332   VersionMinInfo.Major = 0; // Major version == 0 for "none specified"
333 }
334
335 MCAssembler::~MCAssembler() {
336 }
337
338 void MCAssembler::reset() {
339   Sections.clear();
340   Symbols.clear();
341   IndirectSymbols.clear();
342   DataRegions.clear();
343   LinkerOptions.clear();
344   FileNames.clear();
345   ThumbFuncs.clear();
346   BundleAlignSize = 0;
347   RelaxAll = false;
348   SubsectionsViaSymbols = false;
349   ELFHeaderEFlags = 0;
350   LOHContainer.reset();
351   VersionMinInfo.Major = 0;
352
353   // reset objects owned by us
354   getBackend().reset();
355   getEmitter().reset();
356   getWriter().reset();
357   getLOHContainer().reset();
358 }
359
360 bool MCAssembler::registerSection(MCSection &Section) {
361   if (Section.isRegistered())
362     return false;
363   Sections.push_back(&Section);
364   Section.setIsRegistered(true);
365   return true;
366 }
367
368 bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const {
369   if (ThumbFuncs.count(Symbol))
370     return true;
371
372   if (!Symbol->isVariable())
373     return false;
374
375   // FIXME: It looks like gas supports some cases of the form "foo + 2". It
376   // is not clear if that is a bug or a feature.
377   const MCExpr *Expr = Symbol->getVariableValue();
378   const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr);
379   if (!Ref)
380     return false;
381
382   if (Ref->getKind() != MCSymbolRefExpr::VK_None)
383     return false;
384
385   const MCSymbol &Sym = Ref->getSymbol();
386   if (!isThumbFunc(&Sym))
387     return false;
388
389   ThumbFuncs.insert(Symbol); // Cache it.
390   return true;
391 }
392
393 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
394   // Non-temporary labels should always be visible to the linker.
395   if (!Symbol.isTemporary())
396     return true;
397
398   // Absolute temporary labels are never visible.
399   if (!Symbol.isInSection())
400     return false;
401
402   if (Symbol.isUsedInReloc())
403     return true;
404
405   return false;
406 }
407
408 const MCSymbol *MCAssembler::getAtom(const MCSymbol &S) const {
409   // Linker visible symbols define atoms.
410   if (isSymbolLinkerVisible(S))
411     return &S;
412
413   // Absolute and undefined symbols have no defining atom.
414   if (!S.getFragment())
415     return nullptr;
416
417   // Non-linker visible symbols in sections which can't be atomized have no
418   // defining atom.
419   if (!getContext().getAsmInfo()->isSectionAtomizableBySymbols(
420           *S.getFragment()->getParent()))
421     return nullptr;
422
423   // Otherwise, return the atom for the containing fragment.
424   return S.getFragment()->getAtom();
425 }
426
427 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
428                                 const MCFixup &Fixup, const MCFragment *DF,
429                                 MCValue &Target, uint64_t &Value) const {
430   ++stats::evaluateFixup;
431
432   // FIXME: This code has some duplication with recordRelocation. We should
433   // probably merge the two into a single callback that tries to evaluate a
434   // fixup and records a relocation if one is needed.
435   const MCExpr *Expr = Fixup.getValue();
436   if (!Expr->evaluateAsRelocatable(Target, &Layout, &Fixup))
437     getContext().reportFatalError(Fixup.getLoc(), "expected relocatable expression");
438
439   bool IsPCRel = Backend.getFixupKindInfo(
440     Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
441
442   bool IsResolved;
443   if (IsPCRel) {
444     if (Target.getSymB()) {
445       IsResolved = false;
446     } else if (!Target.getSymA()) {
447       IsResolved = false;
448     } else {
449       const MCSymbolRefExpr *A = Target.getSymA();
450       const MCSymbol &SA = A->getSymbol();
451       if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined()) {
452         IsResolved = false;
453       } else {
454         IsResolved = getWriter().isSymbolRefDifferenceFullyResolvedImpl(
455             *this, SA, *DF, false, true);
456       }
457     }
458   } else {
459     IsResolved = Target.isAbsolute();
460   }
461
462   Value = Target.getConstant();
463
464   if (const MCSymbolRefExpr *A = Target.getSymA()) {
465     const MCSymbol &Sym = A->getSymbol();
466     if (Sym.isDefined())
467       Value += Layout.getSymbolOffset(Sym);
468   }
469   if (const MCSymbolRefExpr *B = Target.getSymB()) {
470     const MCSymbol &Sym = B->getSymbol();
471     if (Sym.isDefined())
472       Value -= Layout.getSymbolOffset(Sym);
473   }
474
475
476   bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
477                          MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
478   assert((ShouldAlignPC ? IsPCRel : true) &&
479     "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
480
481   if (IsPCRel) {
482     uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
483
484     // A number of ARM fixups in Thumb mode require that the effective PC
485     // address be determined as the 32-bit aligned version of the actual offset.
486     if (ShouldAlignPC) Offset &= ~0x3;
487     Value -= Offset;
488   }
489
490   // Let the backend adjust the fixup value if necessary, including whether
491   // we need a relocation.
492   Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
493                             IsResolved);
494
495   return IsResolved;
496 }
497
498 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
499                                           const MCFragment &F) const {
500   switch (F.getKind()) {
501   case MCFragment::FT_Data:
502     return cast<MCDataFragment>(F).getContents().size();
503   case MCFragment::FT_Relaxable:
504     return cast<MCRelaxableFragment>(F).getContents().size();
505   case MCFragment::FT_CompactEncodedInst:
506     return cast<MCCompactEncodedInstFragment>(F).getContents().size();
507   case MCFragment::FT_Fill:
508     return cast<MCFillFragment>(F).getSize();
509
510   case MCFragment::FT_LEB:
511     return cast<MCLEBFragment>(F).getContents().size();
512
513   case MCFragment::FT_SafeSEH:
514     return 4;
515
516   case MCFragment::FT_Align: {
517     const MCAlignFragment &AF = cast<MCAlignFragment>(F);
518     unsigned Offset = Layout.getFragmentOffset(&AF);
519     unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
520     // If we are padding with nops, force the padding to be larger than the
521     // minimum nop size.
522     if (Size > 0 && AF.hasEmitNops()) {
523       while (Size % getBackend().getMinimumNopSize())
524         Size += AF.getAlignment();
525     }
526     if (Size > AF.getMaxBytesToEmit())
527       return 0;
528     return Size;
529   }
530
531   case MCFragment::FT_Org: {
532     const MCOrgFragment &OF = cast<MCOrgFragment>(F);
533     int64_t TargetLocation;
534     if (!OF.getOffset().evaluateAsAbsolute(TargetLocation, Layout))
535       report_fatal_error("expected assembly-time absolute expression");
536
537     // FIXME: We need a way to communicate this error.
538     uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
539     int64_t Size = TargetLocation - FragmentOffset;
540     if (Size < 0 || Size >= 0x40000000)
541       report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
542                          "' (at offset '" + Twine(FragmentOffset) + "')");
543     return Size;
544   }
545
546   case MCFragment::FT_Dwarf:
547     return cast<MCDwarfLineAddrFragment>(F).getContents().size();
548   case MCFragment::FT_DwarfFrame:
549     return cast<MCDwarfCallFrameFragment>(F).getContents().size();
550   }
551
552   llvm_unreachable("invalid fragment kind");
553 }
554
555 void MCAsmLayout::layoutFragment(MCFragment *F) {
556   MCFragment *Prev = F->getPrevNode();
557
558   // We should never try to recompute something which is valid.
559   assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
560   // We should never try to compute the fragment layout if its predecessor
561   // isn't valid.
562   assert((!Prev || isFragmentValid(Prev)) &&
563          "Attempt to compute fragment before its predecessor!");
564
565   ++stats::FragmentLayouts;
566
567   // Compute fragment offset and size.
568   if (Prev)
569     F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
570   else
571     F->Offset = 0;
572   LastValidFragment[F->getParent()] = F;
573
574   // If bundling is enabled and this fragment has instructions in it, it has to
575   // obey the bundling restrictions. With padding, we'll have:
576   //
577   //
578   //        BundlePadding
579   //             |||
580   // -------------------------------------
581   //   Prev  |##########|       F        |
582   // -------------------------------------
583   //                    ^
584   //                    |
585   //                    F->Offset
586   //
587   // The fragment's offset will point to after the padding, and its computed
588   // size won't include the padding.
589   //
590   // When the -mc-relax-all flag is used, we optimize bundling by writting the
591   // padding directly into fragments when the instructions are emitted inside
592   // the streamer. When the fragment is larger than the bundle size, we need to
593   // ensure that it's bundle aligned. This means that if we end up with
594   // multiple fragments, we must emit bundle padding between fragments.
595   //
596   // ".align N" is an example of a directive that introduces multiple
597   // fragments. We could add a special case to handle ".align N" by emitting
598   // within-fragment padding (which would produce less padding when N is less
599   // than the bundle size), but for now we don't.
600   //
601   if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
602     assert(isa<MCEncodedFragment>(F) &&
603            "Only MCEncodedFragment implementations have instructions");
604     uint64_t FSize = Assembler.computeFragmentSize(*this, *F);
605
606     if (!Assembler.getRelaxAll() && FSize > Assembler.getBundleAlignSize())
607       report_fatal_error("Fragment can't be larger than a bundle size");
608
609     uint64_t RequiredBundlePadding = computeBundlePadding(Assembler, F,
610                                                           F->Offset, FSize);
611     if (RequiredBundlePadding > UINT8_MAX)
612       report_fatal_error("Padding cannot exceed 255 bytes");
613     F->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
614     F->Offset += RequiredBundlePadding;
615   }
616 }
617
618 void MCAssembler::registerSymbol(const MCSymbol &Symbol, bool *Created) {
619   bool New = !Symbol.isRegistered();
620   if (Created)
621     *Created = New;
622   if (New) {
623     Symbol.setIsRegistered(true);
624     Symbols.push_back(&Symbol);
625   }
626 }
627
628 void MCAssembler::writeFragmentPadding(const MCFragment &F, uint64_t FSize,
629                                        MCObjectWriter *OW) const {
630   // Should NOP padding be written out before this fragment?
631   unsigned BundlePadding = F.getBundlePadding();
632   if (BundlePadding > 0) {
633     assert(isBundlingEnabled() &&
634            "Writing bundle padding with disabled bundling");
635     assert(F.hasInstructions() &&
636            "Writing bundle padding for a fragment without instructions");
637
638     unsigned TotalLength = BundlePadding + static_cast<unsigned>(FSize);
639     if (F.alignToBundleEnd() && TotalLength > getBundleAlignSize()) {
640       // If the padding itself crosses a bundle boundary, it must be emitted
641       // in 2 pieces, since even nop instructions must not cross boundaries.
642       //             v--------------v   <- BundleAlignSize
643       //        v---------v             <- BundlePadding
644       // ----------------------------
645       // | Prev |####|####|    F    |
646       // ----------------------------
647       //        ^-------------------^   <- TotalLength
648       unsigned DistanceToBoundary = TotalLength - getBundleAlignSize();
649       if (!getBackend().writeNopData(DistanceToBoundary, OW))
650           report_fatal_error("unable to write NOP sequence of " +
651                              Twine(DistanceToBoundary) + " bytes");
652       BundlePadding -= DistanceToBoundary;
653     }
654     if (!getBackend().writeNopData(BundlePadding, OW))
655       report_fatal_error("unable to write NOP sequence of " +
656                          Twine(BundlePadding) + " bytes");
657   }
658 }
659
660 /// \brief Write the fragment \p F to the output file.
661 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
662                           const MCFragment &F) {
663   MCObjectWriter *OW = &Asm.getWriter();
664
665   // FIXME: Embed in fragments instead?
666   uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
667
668   Asm.writeFragmentPadding(F, FragmentSize, OW);
669
670   // This variable (and its dummy usage) is to participate in the assert at
671   // the end of the function.
672   uint64_t Start = OW->getStream().tell();
673   (void) Start;
674
675   ++stats::EmittedFragments;
676
677   switch (F.getKind()) {
678   case MCFragment::FT_Align: {
679     ++stats::EmittedAlignFragments;
680     const MCAlignFragment &AF = cast<MCAlignFragment>(F);
681     assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
682
683     uint64_t Count = FragmentSize / AF.getValueSize();
684
685     // FIXME: This error shouldn't actually occur (the front end should emit
686     // multiple .align directives to enforce the semantics it wants), but is
687     // severe enough that we want to report it. How to handle this?
688     if (Count * AF.getValueSize() != FragmentSize)
689       report_fatal_error("undefined .align directive, value size '" +
690                         Twine(AF.getValueSize()) +
691                         "' is not a divisor of padding size '" +
692                         Twine(FragmentSize) + "'");
693
694     // See if we are aligning with nops, and if so do that first to try to fill
695     // the Count bytes.  Then if that did not fill any bytes or there are any
696     // bytes left to fill use the Value and ValueSize to fill the rest.
697     // If we are aligning with nops, ask that target to emit the right data.
698     if (AF.hasEmitNops()) {
699       if (!Asm.getBackend().writeNopData(Count, OW))
700         report_fatal_error("unable to write nop sequence of " +
701                           Twine(Count) + " bytes");
702       break;
703     }
704
705     // Otherwise, write out in multiples of the value size.
706     for (uint64_t i = 0; i != Count; ++i) {
707       switch (AF.getValueSize()) {
708       default: llvm_unreachable("Invalid size!");
709       case 1: OW->write8 (uint8_t (AF.getValue())); break;
710       case 2: OW->write16(uint16_t(AF.getValue())); break;
711       case 4: OW->write32(uint32_t(AF.getValue())); break;
712       case 8: OW->write64(uint64_t(AF.getValue())); break;
713       }
714     }
715     break;
716   }
717
718   case MCFragment::FT_Data: 
719     ++stats::EmittedDataFragments;
720     OW->writeBytes(cast<MCDataFragment>(F).getContents());
721     break;
722
723   case MCFragment::FT_Relaxable:
724     ++stats::EmittedRelaxableFragments;
725     OW->writeBytes(cast<MCRelaxableFragment>(F).getContents());
726     break;
727
728   case MCFragment::FT_CompactEncodedInst:
729     ++stats::EmittedCompactEncodedInstFragments;
730     OW->writeBytes(cast<MCCompactEncodedInstFragment>(F).getContents());
731     break;
732
733   case MCFragment::FT_Fill: {
734     ++stats::EmittedFillFragments;
735     const MCFillFragment &FF = cast<MCFillFragment>(F);
736
737     assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
738
739     for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
740       switch (FF.getValueSize()) {
741       default: llvm_unreachable("Invalid size!");
742       case 1: OW->write8 (uint8_t (FF.getValue())); break;
743       case 2: OW->write16(uint16_t(FF.getValue())); break;
744       case 4: OW->write32(uint32_t(FF.getValue())); break;
745       case 8: OW->write64(uint64_t(FF.getValue())); break;
746       }
747     }
748     break;
749   }
750
751   case MCFragment::FT_LEB: {
752     const MCLEBFragment &LF = cast<MCLEBFragment>(F);
753     OW->writeBytes(LF.getContents());
754     break;
755   }
756
757   case MCFragment::FT_SafeSEH: {
758     const MCSafeSEHFragment &SF = cast<MCSafeSEHFragment>(F);
759     OW->write32(SF.getSymbol()->getIndex());
760     break;
761   }
762
763   case MCFragment::FT_Org: {
764     ++stats::EmittedOrgFragments;
765     const MCOrgFragment &OF = cast<MCOrgFragment>(F);
766
767     for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
768       OW->write8(uint8_t(OF.getValue()));
769
770     break;
771   }
772
773   case MCFragment::FT_Dwarf: {
774     const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
775     OW->writeBytes(OF.getContents());
776     break;
777   }
778   case MCFragment::FT_DwarfFrame: {
779     const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
780     OW->writeBytes(CF.getContents());
781     break;
782   }
783   }
784
785   assert(OW->getStream().tell() - Start == FragmentSize &&
786          "The stream should advance by fragment size");
787 }
788
789 void MCAssembler::writeSectionData(const MCSection *Sec,
790                                    const MCAsmLayout &Layout) const {
791   // Ignore virtual sections.
792   if (Sec->isVirtualSection()) {
793     assert(Layout.getSectionFileSize(Sec) == 0 && "Invalid size for section!");
794
795     // Check that contents are only things legal inside a virtual section.
796     for (const MCFragment &F : *Sec) {
797       switch (F.getKind()) {
798       default: llvm_unreachable("Invalid fragment in virtual section!");
799       case MCFragment::FT_Data: {
800         // Check that we aren't trying to write a non-zero contents (or fixups)
801         // into a virtual section. This is to support clients which use standard
802         // directives to fill the contents of virtual sections.
803         const MCDataFragment &DF = cast<MCDataFragment>(F);
804         assert(DF.fixup_begin() == DF.fixup_end() &&
805                "Cannot have fixups in virtual section!");
806         for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
807           if (DF.getContents()[i]) {
808             if (auto *ELFSec = dyn_cast<const MCSectionELF>(Sec))
809               report_fatal_error("non-zero initializer found in section '" +
810                   ELFSec->getSectionName() + "'");
811             else
812               report_fatal_error("non-zero initializer found in virtual section");
813           }
814         break;
815       }
816       case MCFragment::FT_Align:
817         // Check that we aren't trying to write a non-zero value into a virtual
818         // section.
819         assert((cast<MCAlignFragment>(F).getValueSize() == 0 ||
820                 cast<MCAlignFragment>(F).getValue() == 0) &&
821                "Invalid align in virtual section!");
822         break;
823       case MCFragment::FT_Fill:
824         assert((cast<MCFillFragment>(F).getValueSize() == 0 ||
825                 cast<MCFillFragment>(F).getValue() == 0) &&
826                "Invalid fill in virtual section!");
827         break;
828       }
829     }
830
831     return;
832   }
833
834   uint64_t Start = getWriter().getStream().tell();
835   (void)Start;
836
837   for (const MCFragment &F : *Sec)
838     writeFragment(*this, Layout, F);
839
840   assert(getWriter().getStream().tell() - Start ==
841          Layout.getSectionAddressSize(Sec));
842 }
843
844 std::pair<uint64_t, bool> MCAssembler::handleFixup(const MCAsmLayout &Layout,
845                                                    MCFragment &F,
846                                                    const MCFixup &Fixup) {
847   // Evaluate the fixup.
848   MCValue Target;
849   uint64_t FixedValue;
850   bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
851                  MCFixupKindInfo::FKF_IsPCRel;
852   if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
853     // The fixup was unresolved, we need a relocation. Inform the object
854     // writer of the relocation, and give it an opportunity to adjust the
855     // fixup value if need be.
856     getWriter().recordRelocation(*this, Layout, &F, Fixup, Target, IsPCRel,
857                                  FixedValue);
858   }
859   return std::make_pair(FixedValue, IsPCRel);
860 }
861
862 void MCAssembler::layout(MCAsmLayout &Layout) {
863   DEBUG_WITH_TYPE("mc-dump", {
864       llvm::errs() << "assembler backend - pre-layout\n--\n";
865       dump(); });
866
867   // Create dummy fragments and assign section ordinals.
868   unsigned SectionIndex = 0;
869   for (MCSection &Sec : *this) {
870     // Create dummy fragments to eliminate any empty sections, this simplifies
871     // layout.
872     if (Sec.getFragmentList().empty())
873       new MCDataFragment(&Sec);
874
875     Sec.setOrdinal(SectionIndex++);
876   }
877
878   // Assign layout order indices to sections and fragments.
879   for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
880     MCSection *Sec = Layout.getSectionOrder()[i];
881     Sec->setLayoutOrder(i);
882
883     unsigned FragmentIndex = 0;
884     for (MCFragment &Frag : *Sec)
885       Frag.setLayoutOrder(FragmentIndex++);
886   }
887
888   // Layout until everything fits.
889   while (layoutOnce(Layout))
890     continue;
891
892   DEBUG_WITH_TYPE("mc-dump", {
893       llvm::errs() << "assembler backend - post-relaxation\n--\n";
894       dump(); });
895
896   // Finalize the layout, including fragment lowering.
897   finishLayout(Layout);
898
899   DEBUG_WITH_TYPE("mc-dump", {
900       llvm::errs() << "assembler backend - final-layout\n--\n";
901       dump(); });
902
903   // Allow the object writer a chance to perform post-layout binding (for
904   // example, to set the index fields in the symbol data).
905   getWriter().executePostLayoutBinding(*this, Layout);
906
907   // Evaluate and apply the fixups, generating relocation entries as necessary.
908   for (MCSection &Sec : *this) {
909     for (MCFragment &Frag : Sec) {
910       MCEncodedFragment *F = dyn_cast<MCEncodedFragment>(&Frag);
911       // Data and relaxable fragments both have fixups.  So only process
912       // those here.
913       // FIXME: Is there a better way to do this?  MCEncodedFragmentWithFixups
914       // being templated makes this tricky.
915       if (!F || isa<MCCompactEncodedInstFragment>(F))
916         continue;
917       ArrayRef<MCFixup> Fixups;
918       MutableArrayRef<char> Contents;
919       if (auto *FragWithFixups = dyn_cast<MCDataFragment>(F)) {
920         Fixups = FragWithFixups->getFixups();
921         Contents = FragWithFixups->getContents();
922       } else if (auto *FragWithFixups = dyn_cast<MCRelaxableFragment>(F)) {
923         Fixups = FragWithFixups->getFixups();
924         Contents = FragWithFixups->getContents();
925       } else
926         llvm_unreachable("Unknown fragment with fixups!");
927       for (const MCFixup &Fixup : Fixups) {
928         uint64_t FixedValue;
929         bool IsPCRel;
930         std::tie(FixedValue, IsPCRel) = handleFixup(Layout, *F, Fixup);
931         getBackend().applyFixup(Fixup, Contents.data(),
932                                 Contents.size(), FixedValue, IsPCRel);
933       }
934     }
935   }
936 }
937
938 void MCAssembler::Finish() {
939   // Create the layout object.
940   MCAsmLayout Layout(*this);
941   layout(Layout);
942
943   raw_ostream &OS = getWriter().getStream();
944   uint64_t StartOffset = OS.tell();
945
946   // Write the object file.
947   getWriter().writeObject(*this, Layout);
948
949   stats::ObjectBytes += OS.tell() - StartOffset;
950 }
951
952 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
953                                        const MCRelaxableFragment *DF,
954                                        const MCAsmLayout &Layout) const {
955   MCValue Target;
956   uint64_t Value;
957   bool Resolved = evaluateFixup(Layout, Fixup, DF, Target, Value);
958   return getBackend().fixupNeedsRelaxationAdvanced(Fixup, Resolved, Value, DF,
959                                                    Layout);
960 }
961
962 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
963                                           const MCAsmLayout &Layout) const {
964   // If this inst doesn't ever need relaxation, ignore it. This occurs when we
965   // are intentionally pushing out inst fragments, or because we relaxed a
966   // previous instruction to one that doesn't need relaxation.
967   if (!getBackend().mayNeedRelaxation(F->getInst()))
968     return false;
969
970   for (const MCFixup &Fixup : F->getFixups())
971     if (fixupNeedsRelaxation(Fixup, F, Layout))
972       return true;
973
974   return false;
975 }
976
977 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
978                                    MCRelaxableFragment &F) {
979   if (!fragmentNeedsRelaxation(&F, Layout))
980     return false;
981
982   ++stats::RelaxedInstructions;
983
984   // FIXME-PERF: We could immediately lower out instructions if we can tell
985   // they are fully resolved, to avoid retesting on later passes.
986
987   // Relax the fragment.
988
989   MCInst Relaxed;
990   getBackend().relaxInstruction(F.getInst(), Relaxed);
991
992   // Encode the new instruction.
993   //
994   // FIXME-PERF: If it matters, we could let the target do this. It can
995   // probably do so more efficiently in many cases.
996   SmallVector<MCFixup, 4> Fixups;
997   SmallString<256> Code;
998   raw_svector_ostream VecOS(Code);
999   getEmitter().encodeInstruction(Relaxed, VecOS, Fixups, F.getSubtargetInfo());
1000
1001   // Update the fragment.
1002   F.setInst(Relaxed);
1003   F.getContents() = Code;
1004   F.getFixups() = Fixups;
1005
1006   return true;
1007 }
1008
1009 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
1010   uint64_t OldSize = LF.getContents().size();
1011   int64_t Value;
1012   bool Abs = LF.getValue().evaluateKnownAbsolute(Value, Layout);
1013   if (!Abs)
1014     report_fatal_error("sleb128 and uleb128 expressions must be absolute");
1015   SmallString<8> &Data = LF.getContents();
1016   Data.clear();
1017   raw_svector_ostream OSE(Data);
1018   if (LF.isSigned())
1019     encodeSLEB128(Value, OSE);
1020   else
1021     encodeULEB128(Value, OSE);
1022   return OldSize != LF.getContents().size();
1023 }
1024
1025 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
1026                                      MCDwarfLineAddrFragment &DF) {
1027   MCContext &Context = Layout.getAssembler().getContext();
1028   uint64_t OldSize = DF.getContents().size();
1029   int64_t AddrDelta;
1030   bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1031   assert(Abs && "We created a line delta with an invalid expression");
1032   (void) Abs;
1033   int64_t LineDelta;
1034   LineDelta = DF.getLineDelta();
1035   SmallString<8> &Data = DF.getContents();
1036   Data.clear();
1037   raw_svector_ostream OSE(Data);
1038   MCDwarfLineAddr::Encode(Context, getDWARFLinetableParams(), LineDelta,
1039                           AddrDelta, OSE);
1040   return OldSize != Data.size();
1041 }
1042
1043 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
1044                                               MCDwarfCallFrameFragment &DF) {
1045   MCContext &Context = Layout.getAssembler().getContext();
1046   uint64_t OldSize = DF.getContents().size();
1047   int64_t AddrDelta;
1048   bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1049   assert(Abs && "We created call frame with an invalid expression");
1050   (void) Abs;
1051   SmallString<8> &Data = DF.getContents();
1052   Data.clear();
1053   raw_svector_ostream OSE(Data);
1054   MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
1055   return OldSize != Data.size();
1056 }
1057
1058 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec) {
1059   // Holds the first fragment which needed relaxing during this layout. It will
1060   // remain NULL if none were relaxed.
1061   // When a fragment is relaxed, all the fragments following it should get
1062   // invalidated because their offset is going to change.
1063   MCFragment *FirstRelaxedFragment = nullptr;
1064
1065   // Attempt to relax all the fragments in the section.
1066   for (MCSection::iterator I = Sec.begin(), IE = Sec.end(); I != IE; ++I) {
1067     // Check if this is a fragment that needs relaxation.
1068     bool RelaxedFrag = false;
1069     switch(I->getKind()) {
1070     default:
1071       break;
1072     case MCFragment::FT_Relaxable:
1073       assert(!getRelaxAll() &&
1074              "Did not expect a MCRelaxableFragment in RelaxAll mode");
1075       RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
1076       break;
1077     case MCFragment::FT_Dwarf:
1078       RelaxedFrag = relaxDwarfLineAddr(Layout,
1079                                        *cast<MCDwarfLineAddrFragment>(I));
1080       break;
1081     case MCFragment::FT_DwarfFrame:
1082       RelaxedFrag =
1083         relaxDwarfCallFrameFragment(Layout,
1084                                     *cast<MCDwarfCallFrameFragment>(I));
1085       break;
1086     case MCFragment::FT_LEB:
1087       RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
1088       break;
1089     }
1090     if (RelaxedFrag && !FirstRelaxedFragment)
1091       FirstRelaxedFragment = I;
1092   }
1093   if (FirstRelaxedFragment) {
1094     Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
1095     return true;
1096   }
1097   return false;
1098 }
1099
1100 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
1101   ++stats::RelaxationSteps;
1102
1103   bool WasRelaxed = false;
1104   for (iterator it = begin(), ie = end(); it != ie; ++it) {
1105     MCSection &Sec = *it;
1106     while (layoutSectionOnce(Layout, Sec))
1107       WasRelaxed = true;
1108   }
1109
1110   return WasRelaxed;
1111 }
1112
1113 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
1114   // The layout is done. Mark every fragment as valid.
1115   for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
1116     Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
1117   }
1118 }
1119
1120 // Debugging methods
1121
1122 namespace llvm {
1123
1124 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
1125   OS << "<MCFixup" << " Offset:" << AF.getOffset()
1126      << " Value:" << *AF.getValue()
1127      << " Kind:" << AF.getKind() << ">";
1128   return OS;
1129 }
1130
1131 }
1132
1133 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1134 void MCFragment::dump() {
1135   raw_ostream &OS = llvm::errs();
1136
1137   OS << "<";
1138   switch (getKind()) {
1139   case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
1140   case MCFragment::FT_Data:  OS << "MCDataFragment"; break;
1141   case MCFragment::FT_CompactEncodedInst:
1142     OS << "MCCompactEncodedInstFragment"; break;
1143   case MCFragment::FT_Fill:  OS << "MCFillFragment"; break;
1144   case MCFragment::FT_Relaxable:  OS << "MCRelaxableFragment"; break;
1145   case MCFragment::FT_Org:   OS << "MCOrgFragment"; break;
1146   case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
1147   case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
1148   case MCFragment::FT_LEB:   OS << "MCLEBFragment"; break;
1149   case MCFragment::FT_SafeSEH:    OS << "MCSafeSEHFragment"; break;
1150   }
1151
1152   OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
1153      << " Offset:" << Offset
1154      << " HasInstructions:" << hasInstructions() 
1155      << " BundlePadding:" << static_cast<unsigned>(getBundlePadding()) << ">";
1156
1157   switch (getKind()) {
1158   case MCFragment::FT_Align: {
1159     const MCAlignFragment *AF = cast<MCAlignFragment>(this);
1160     if (AF->hasEmitNops())
1161       OS << " (emit nops)";
1162     OS << "\n       ";
1163     OS << " Alignment:" << AF->getAlignment()
1164        << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
1165        << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
1166     break;
1167   }
1168   case MCFragment::FT_Data:  {
1169     const MCDataFragment *DF = cast<MCDataFragment>(this);
1170     OS << "\n       ";
1171     OS << " Contents:[";
1172     const SmallVectorImpl<char> &Contents = DF->getContents();
1173     for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1174       if (i) OS << ",";
1175       OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1176     }
1177     OS << "] (" << Contents.size() << " bytes)";
1178
1179     if (DF->fixup_begin() != DF->fixup_end()) {
1180       OS << ",\n       ";
1181       OS << " Fixups:[";
1182       for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
1183              ie = DF->fixup_end(); it != ie; ++it) {
1184         if (it != DF->fixup_begin()) OS << ",\n                ";
1185         OS << *it;
1186       }
1187       OS << "]";
1188     }
1189     break;
1190   }
1191   case MCFragment::FT_CompactEncodedInst: {
1192     const MCCompactEncodedInstFragment *CEIF =
1193       cast<MCCompactEncodedInstFragment>(this);
1194     OS << "\n       ";
1195     OS << " Contents:[";
1196     const SmallVectorImpl<char> &Contents = CEIF->getContents();
1197     for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1198       if (i) OS << ",";
1199       OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1200     }
1201     OS << "] (" << Contents.size() << " bytes)";
1202     break;
1203   }
1204   case MCFragment::FT_Fill:  {
1205     const MCFillFragment *FF = cast<MCFillFragment>(this);
1206     OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
1207        << " Size:" << FF->getSize();
1208     break;
1209   }
1210   case MCFragment::FT_Relaxable:  {
1211     const MCRelaxableFragment *F = cast<MCRelaxableFragment>(this);
1212     OS << "\n       ";
1213     OS << " Inst:";
1214     F->getInst().dump_pretty(OS);
1215     break;
1216   }
1217   case MCFragment::FT_Org:  {
1218     const MCOrgFragment *OF = cast<MCOrgFragment>(this);
1219     OS << "\n       ";
1220     OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
1221     break;
1222   }
1223   case MCFragment::FT_Dwarf:  {
1224     const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
1225     OS << "\n       ";
1226     OS << " AddrDelta:" << OF->getAddrDelta()
1227        << " LineDelta:" << OF->getLineDelta();
1228     break;
1229   }
1230   case MCFragment::FT_DwarfFrame:  {
1231     const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
1232     OS << "\n       ";
1233     OS << " AddrDelta:" << CF->getAddrDelta();
1234     break;
1235   }
1236   case MCFragment::FT_LEB: {
1237     const MCLEBFragment *LF = cast<MCLEBFragment>(this);
1238     OS << "\n       ";
1239     OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
1240     break;
1241   }
1242   case MCFragment::FT_SafeSEH: {
1243     const MCSafeSEHFragment *F = cast<MCSafeSEHFragment>(this);
1244     OS << "\n       ";
1245     OS << " Sym:" << F->getSymbol();
1246     break;
1247   }
1248   }
1249   OS << ">";
1250 }
1251
1252 void MCAssembler::dump() {
1253   raw_ostream &OS = llvm::errs();
1254
1255   OS << "<MCAssembler\n";
1256   OS << "  Sections:[\n    ";
1257   for (iterator it = begin(), ie = end(); it != ie; ++it) {
1258     if (it != begin()) OS << ",\n    ";
1259     it->dump();
1260   }
1261   OS << "],\n";
1262   OS << "  Symbols:[";
1263
1264   for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1265     if (it != symbol_begin()) OS << ",\n           ";
1266     OS << "(";
1267     it->dump();
1268     OS << ", Index:" << it->getIndex() << ", ";
1269     OS << ")";
1270   }
1271   OS << "]>\n";
1272 }
1273 #endif