Revert r240137 (Fixed/added namespace ending comments using clang-tidy. 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 (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
72     if (!it->isVirtualSection())
73       SectionOrder.push_back(&*it);
74   for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
75     if (it->isVirtualSection())
76       SectionOrder.push_back(&*it);
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()->evaluateAsRelocatable(Target, &Layout, nullptr))
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 (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                          raw_ostream &OS_)
330     : Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
331       OS(OS_), BundleAlignSize(0), RelaxAll(false),
332       SubsectionsViaSymbols(false), ELFHeaderEFlags(0) {
333   VersionMinInfo.Major = 0; // Major version == 0 for "none specified"
334 }
335
336 MCAssembler::~MCAssembler() {
337 }
338
339 void MCAssembler::reset() {
340   Sections.clear();
341   Symbols.clear();
342   IndirectSymbols.clear();
343   DataRegions.clear();
344   LinkerOptions.clear();
345   FileNames.clear();
346   ThumbFuncs.clear();
347   BundleAlignSize = 0;
348   RelaxAll = false;
349   SubsectionsViaSymbols = false;
350   ELFHeaderEFlags = 0;
351   LOHContainer.reset();
352   VersionMinInfo.Major = 0;
353
354   // reset objects owned by us
355   getBackend().reset();
356   getEmitter().reset();
357   getWriter().reset();
358   getLOHContainer().reset();
359 }
360
361 bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const {
362   if (ThumbFuncs.count(Symbol))
363     return true;
364
365   if (!Symbol->isVariable())
366     return false;
367
368   // FIXME: It looks like gas supports some cases of the form "foo + 2". It
369   // is not clear if that is a bug or a feature.
370   const MCExpr *Expr = Symbol->getVariableValue();
371   const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr);
372   if (!Ref)
373     return false;
374
375   if (Ref->getKind() != MCSymbolRefExpr::VK_None)
376     return false;
377
378   const MCSymbol &Sym = Ref->getSymbol();
379   if (!isThumbFunc(&Sym))
380     return false;
381
382   ThumbFuncs.insert(Symbol); // Cache it.
383   return true;
384 }
385
386 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
387   // Non-temporary labels should always be visible to the linker.
388   if (!Symbol.isTemporary())
389     return true;
390
391   // Absolute temporary labels are never visible.
392   if (!Symbol.isInSection())
393     return false;
394
395   if (Symbol.isUsedInReloc())
396     return true;
397
398   return false;
399 }
400
401 const MCSymbol *MCAssembler::getAtom(const MCSymbol &S) const {
402   // Linker visible symbols define atoms.
403   if (isSymbolLinkerVisible(S))
404     return &S;
405
406   // Absolute and undefined symbols have no defining atom.
407   if (!S.getFragment())
408     return nullptr;
409
410   // Non-linker visible symbols in sections which can't be atomized have no
411   // defining atom.
412   if (!getContext().getAsmInfo()->isSectionAtomizableBySymbols(
413           *S.getFragment()->getParent()))
414     return nullptr;
415
416   // Otherwise, return the atom for the containing fragment.
417   return S.getFragment()->getAtom();
418 }
419
420 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
421                                 const MCFixup &Fixup, const MCFragment *DF,
422                                 MCValue &Target, uint64_t &Value) const {
423   ++stats::evaluateFixup;
424
425   // FIXME: This code has some duplication with recordRelocation. We should
426   // probably merge the two into a single callback that tries to evaluate a
427   // fixup and records a relocation if one is needed.
428   const MCExpr *Expr = Fixup.getValue();
429   if (!Expr->evaluateAsRelocatable(Target, &Layout, &Fixup))
430     getContext().reportFatalError(Fixup.getLoc(), "expected relocatable expression");
431
432   bool IsPCRel = Backend.getFixupKindInfo(
433     Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
434
435   bool IsResolved;
436   if (IsPCRel) {
437     if (Target.getSymB()) {
438       IsResolved = false;
439     } else if (!Target.getSymA()) {
440       IsResolved = false;
441     } else {
442       const MCSymbolRefExpr *A = Target.getSymA();
443       const MCSymbol &SA = A->getSymbol();
444       if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined()) {
445         IsResolved = false;
446       } else {
447         IsResolved = getWriter().isSymbolRefDifferenceFullyResolvedImpl(
448             *this, SA, *DF, false, true);
449       }
450     }
451   } else {
452     IsResolved = Target.isAbsolute();
453   }
454
455   Value = Target.getConstant();
456
457   if (const MCSymbolRefExpr *A = Target.getSymA()) {
458     const MCSymbol &Sym = A->getSymbol();
459     if (Sym.isDefined())
460       Value += Layout.getSymbolOffset(Sym);
461   }
462   if (const MCSymbolRefExpr *B = Target.getSymB()) {
463     const MCSymbol &Sym = B->getSymbol();
464     if (Sym.isDefined())
465       Value -= Layout.getSymbolOffset(Sym);
466   }
467
468
469   bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
470                          MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
471   assert((ShouldAlignPC ? IsPCRel : true) &&
472     "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
473
474   if (IsPCRel) {
475     uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
476
477     // A number of ARM fixups in Thumb mode require that the effective PC
478     // address be determined as the 32-bit aligned version of the actual offset.
479     if (ShouldAlignPC) Offset &= ~0x3;
480     Value -= Offset;
481   }
482
483   // Let the backend adjust the fixup value if necessary, including whether
484   // we need a relocation.
485   Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
486                             IsResolved);
487
488   return IsResolved;
489 }
490
491 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
492                                           const MCFragment &F) const {
493   switch (F.getKind()) {
494   case MCFragment::FT_Data:
495     return cast<MCDataFragment>(F).getContents().size();
496   case MCFragment::FT_Relaxable:
497     return cast<MCRelaxableFragment>(F).getContents().size();
498   case MCFragment::FT_CompactEncodedInst:
499     return cast<MCCompactEncodedInstFragment>(F).getContents().size();
500   case MCFragment::FT_Fill:
501     return cast<MCFillFragment>(F).getSize();
502
503   case MCFragment::FT_LEB:
504     return cast<MCLEBFragment>(F).getContents().size();
505
506   case MCFragment::FT_SafeSEH:
507     return 4;
508
509   case MCFragment::FT_Align: {
510     const MCAlignFragment &AF = cast<MCAlignFragment>(F);
511     unsigned Offset = Layout.getFragmentOffset(&AF);
512     unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
513     // If we are padding with nops, force the padding to be larger than the
514     // minimum nop size.
515     if (Size > 0 && AF.hasEmitNops()) {
516       while (Size % getBackend().getMinimumNopSize())
517         Size += AF.getAlignment();
518     }
519     if (Size > AF.getMaxBytesToEmit())
520       return 0;
521     return Size;
522   }
523
524   case MCFragment::FT_Org: {
525     const MCOrgFragment &OF = cast<MCOrgFragment>(F);
526     int64_t TargetLocation;
527     if (!OF.getOffset().evaluateAsAbsolute(TargetLocation, Layout))
528       report_fatal_error("expected assembly-time absolute expression");
529
530     // FIXME: We need a way to communicate this error.
531     uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
532     int64_t Size = TargetLocation - FragmentOffset;
533     if (Size < 0 || Size >= 0x40000000)
534       report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
535                          "' (at offset '" + Twine(FragmentOffset) + "')");
536     return Size;
537   }
538
539   case MCFragment::FT_Dwarf:
540     return cast<MCDwarfLineAddrFragment>(F).getContents().size();
541   case MCFragment::FT_DwarfFrame:
542     return cast<MCDwarfCallFrameFragment>(F).getContents().size();
543   }
544
545   llvm_unreachable("invalid fragment kind");
546 }
547
548 void MCAsmLayout::layoutFragment(MCFragment *F) {
549   MCFragment *Prev = F->getPrevNode();
550
551   // We should never try to recompute something which is valid.
552   assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
553   // We should never try to compute the fragment layout if its predecessor
554   // isn't valid.
555   assert((!Prev || isFragmentValid(Prev)) &&
556          "Attempt to compute fragment before its predecessor!");
557
558   ++stats::FragmentLayouts;
559
560   // Compute fragment offset and size.
561   if (Prev)
562     F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
563   else
564     F->Offset = 0;
565   LastValidFragment[F->getParent()] = F;
566
567   // If bundling is enabled and this fragment has instructions in it, it has to
568   // obey the bundling restrictions. With padding, we'll have:
569   //
570   //
571   //        BundlePadding
572   //             |||
573   // -------------------------------------
574   //   Prev  |##########|       F        |
575   // -------------------------------------
576   //                    ^
577   //                    |
578   //                    F->Offset
579   //
580   // The fragment's offset will point to after the padding, and its computed
581   // size won't include the padding.
582   //
583   // When the -mc-relax-all flag is used, we optimize bundling by writting the
584   // bundle padding directly into fragments when the instructions are emitted
585   // inside the streamer.
586   //
587   if (Assembler.isBundlingEnabled() && !Assembler.getRelaxAll() &&
588       F->hasInstructions()) {
589     assert(isa<MCEncodedFragment>(F) &&
590            "Only MCEncodedFragment implementations have instructions");
591     uint64_t FSize = Assembler.computeFragmentSize(*this, *F);
592
593     if (FSize > Assembler.getBundleAlignSize())
594       report_fatal_error("Fragment can't be larger than a bundle size");
595
596     uint64_t RequiredBundlePadding = computeBundlePadding(Assembler, F,
597                                                           F->Offset, FSize);
598     if (RequiredBundlePadding > UINT8_MAX)
599       report_fatal_error("Padding cannot exceed 255 bytes");
600     F->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
601     F->Offset += RequiredBundlePadding;
602   }
603 }
604
605 void MCAssembler::registerSymbol(const MCSymbol &Symbol, bool *Created) {
606   bool New = !Symbol.isRegistered();
607   if (Created)
608     *Created = New;
609   if (New) {
610     Symbol.setIsRegistered(true);
611     Symbols.push_back(&Symbol);
612   }
613 }
614
615 void MCAssembler::writeFragmentPadding(const MCFragment &F, uint64_t FSize,
616                                        MCObjectWriter *OW) const {
617   // Should NOP padding be written out before this fragment?
618   unsigned BundlePadding = F.getBundlePadding();
619   if (BundlePadding > 0) {
620     assert(isBundlingEnabled() &&
621            "Writing bundle padding with disabled bundling");
622     assert(F.hasInstructions() &&
623            "Writing bundle padding for a fragment without instructions");
624
625     unsigned TotalLength = BundlePadding + static_cast<unsigned>(FSize);
626     if (F.alignToBundleEnd() && TotalLength > getBundleAlignSize()) {
627       // If the padding itself crosses a bundle boundary, it must be emitted
628       // in 2 pieces, since even nop instructions must not cross boundaries.
629       //             v--------------v   <- BundleAlignSize
630       //        v---------v             <- BundlePadding
631       // ----------------------------
632       // | Prev |####|####|    F    |
633       // ----------------------------
634       //        ^-------------------^   <- TotalLength
635       unsigned DistanceToBoundary = TotalLength - getBundleAlignSize();
636       if (!getBackend().writeNopData(DistanceToBoundary, OW))
637           report_fatal_error("unable to write NOP sequence of " +
638                              Twine(DistanceToBoundary) + " bytes");
639       BundlePadding -= DistanceToBoundary;
640     }
641     if (!getBackend().writeNopData(BundlePadding, OW))
642       report_fatal_error("unable to write NOP sequence of " +
643                          Twine(BundlePadding) + " bytes");
644   }
645 }
646
647 /// \brief Write the fragment \p F to the output file.
648 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
649                           const MCFragment &F) {
650   MCObjectWriter *OW = &Asm.getWriter();
651
652   // FIXME: Embed in fragments instead?
653   uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
654
655   Asm.writeFragmentPadding(F, FragmentSize, OW);
656
657   // This variable (and its dummy usage) is to participate in the assert at
658   // the end of the function.
659   uint64_t Start = OW->getStream().tell();
660   (void) Start;
661
662   ++stats::EmittedFragments;
663
664   switch (F.getKind()) {
665   case MCFragment::FT_Align: {
666     ++stats::EmittedAlignFragments;
667     const MCAlignFragment &AF = cast<MCAlignFragment>(F);
668     assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
669
670     uint64_t Count = FragmentSize / AF.getValueSize();
671
672     // FIXME: This error shouldn't actually occur (the front end should emit
673     // multiple .align directives to enforce the semantics it wants), but is
674     // severe enough that we want to report it. How to handle this?
675     if (Count * AF.getValueSize() != FragmentSize)
676       report_fatal_error("undefined .align directive, value size '" +
677                         Twine(AF.getValueSize()) +
678                         "' is not a divisor of padding size '" +
679                         Twine(FragmentSize) + "'");
680
681     // See if we are aligning with nops, and if so do that first to try to fill
682     // the Count bytes.  Then if that did not fill any bytes or there are any
683     // bytes left to fill use the Value and ValueSize to fill the rest.
684     // If we are aligning with nops, ask that target to emit the right data.
685     if (AF.hasEmitNops()) {
686       if (!Asm.getBackend().writeNopData(Count, OW))
687         report_fatal_error("unable to write nop sequence of " +
688                           Twine(Count) + " bytes");
689       break;
690     }
691
692     // Otherwise, write out in multiples of the value size.
693     for (uint64_t i = 0; i != Count; ++i) {
694       switch (AF.getValueSize()) {
695       default: llvm_unreachable("Invalid size!");
696       case 1: OW->write8 (uint8_t (AF.getValue())); break;
697       case 2: OW->write16(uint16_t(AF.getValue())); break;
698       case 4: OW->write32(uint32_t(AF.getValue())); break;
699       case 8: OW->write64(uint64_t(AF.getValue())); break;
700       }
701     }
702     break;
703   }
704
705   case MCFragment::FT_Data: 
706     ++stats::EmittedDataFragments;
707     OW->writeBytes(cast<MCDataFragment>(F).getContents());
708     break;
709
710   case MCFragment::FT_Relaxable:
711     ++stats::EmittedRelaxableFragments;
712     OW->writeBytes(cast<MCRelaxableFragment>(F).getContents());
713     break;
714
715   case MCFragment::FT_CompactEncodedInst:
716     ++stats::EmittedCompactEncodedInstFragments;
717     OW->writeBytes(cast<MCCompactEncodedInstFragment>(F).getContents());
718     break;
719
720   case MCFragment::FT_Fill: {
721     ++stats::EmittedFillFragments;
722     const MCFillFragment &FF = cast<MCFillFragment>(F);
723
724     assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
725
726     for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
727       switch (FF.getValueSize()) {
728       default: llvm_unreachable("Invalid size!");
729       case 1: OW->write8 (uint8_t (FF.getValue())); break;
730       case 2: OW->write16(uint16_t(FF.getValue())); break;
731       case 4: OW->write32(uint32_t(FF.getValue())); break;
732       case 8: OW->write64(uint64_t(FF.getValue())); break;
733       }
734     }
735     break;
736   }
737
738   case MCFragment::FT_LEB: {
739     const MCLEBFragment &LF = cast<MCLEBFragment>(F);
740     OW->writeBytes(LF.getContents());
741     break;
742   }
743
744   case MCFragment::FT_SafeSEH: {
745     const MCSafeSEHFragment &SF = cast<MCSafeSEHFragment>(F);
746     OW->write32(SF.getSymbol()->getIndex());
747     break;
748   }
749
750   case MCFragment::FT_Org: {
751     ++stats::EmittedOrgFragments;
752     const MCOrgFragment &OF = cast<MCOrgFragment>(F);
753
754     for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
755       OW->write8(uint8_t(OF.getValue()));
756
757     break;
758   }
759
760   case MCFragment::FT_Dwarf: {
761     const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
762     OW->writeBytes(OF.getContents());
763     break;
764   }
765   case MCFragment::FT_DwarfFrame: {
766     const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
767     OW->writeBytes(CF.getContents());
768     break;
769   }
770   }
771
772   assert(OW->getStream().tell() - Start == FragmentSize &&
773          "The stream should advance by fragment size");
774 }
775
776 void MCAssembler::writeSectionData(const MCSection *Sec,
777                                    const MCAsmLayout &Layout) const {
778   // Ignore virtual sections.
779   if (Sec->isVirtualSection()) {
780     assert(Layout.getSectionFileSize(Sec) == 0 && "Invalid size for section!");
781
782     // Check that contents are only things legal inside a virtual section.
783     for (MCSection::const_iterator it = Sec->begin(), ie = Sec->end(); it != ie;
784          ++it) {
785       switch (it->getKind()) {
786       default: llvm_unreachable("Invalid fragment in virtual section!");
787       case MCFragment::FT_Data: {
788         // Check that we aren't trying to write a non-zero contents (or fixups)
789         // into a virtual section. This is to support clients which use standard
790         // directives to fill the contents of virtual sections.
791         const MCDataFragment &DF = cast<MCDataFragment>(*it);
792         assert(DF.fixup_begin() == DF.fixup_end() &&
793                "Cannot have fixups in virtual section!");
794         for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
795           if (DF.getContents()[i]) {
796             if (auto *ELFSec = dyn_cast<const MCSectionELF>(Sec))
797               report_fatal_error("non-zero initializer found in section '" +
798                   ELFSec->getSectionName() + "'");
799             else
800               report_fatal_error("non-zero initializer found in virtual section");
801           }
802         break;
803       }
804       case MCFragment::FT_Align:
805         // Check that we aren't trying to write a non-zero value into a virtual
806         // section.
807         assert((cast<MCAlignFragment>(it)->getValueSize() == 0 ||
808                 cast<MCAlignFragment>(it)->getValue() == 0) &&
809                "Invalid align in virtual section!");
810         break;
811       case MCFragment::FT_Fill:
812         assert((cast<MCFillFragment>(it)->getValueSize() == 0 ||
813                 cast<MCFillFragment>(it)->getValue() == 0) &&
814                "Invalid fill in virtual section!");
815         break;
816       }
817     }
818
819     return;
820   }
821
822   uint64_t Start = getWriter().getStream().tell();
823   (void)Start;
824
825   for (MCSection::const_iterator it = Sec->begin(), ie = Sec->end(); it != ie;
826        ++it)
827     writeFragment(*this, Layout, *it);
828
829   assert(getWriter().getStream().tell() - Start ==
830          Layout.getSectionAddressSize(Sec));
831 }
832
833 std::pair<uint64_t, bool> MCAssembler::handleFixup(const MCAsmLayout &Layout,
834                                                    MCFragment &F,
835                                                    const MCFixup &Fixup) {
836   // Evaluate the fixup.
837   MCValue Target;
838   uint64_t FixedValue;
839   bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
840                  MCFixupKindInfo::FKF_IsPCRel;
841   if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
842     // The fixup was unresolved, we need a relocation. Inform the object
843     // writer of the relocation, and give it an opportunity to adjust the
844     // fixup value if need be.
845     getWriter().recordRelocation(*this, Layout, &F, Fixup, Target, IsPCRel,
846                                  FixedValue);
847   }
848   return std::make_pair(FixedValue, IsPCRel);
849 }
850
851 void MCAssembler::Finish() {
852   DEBUG_WITH_TYPE("mc-dump", {
853       llvm::errs() << "assembler backend - pre-layout\n--\n";
854       dump(); });
855
856   // Create the layout object.
857   MCAsmLayout Layout(*this);
858
859   // Create dummy fragments and assign section ordinals.
860   unsigned SectionIndex = 0;
861   for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
862     // Create dummy fragments to eliminate any empty sections, this simplifies
863     // layout.
864     if (it->getFragmentList().empty())
865       new MCDataFragment(&*it);
866
867     it->setOrdinal(SectionIndex++);
868   }
869
870   // Assign layout order indices to sections and fragments.
871   for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
872     MCSection *Sec = Layout.getSectionOrder()[i];
873     Sec->setLayoutOrder(i);
874
875     unsigned FragmentIndex = 0;
876     for (MCSection::iterator iFrag = Sec->begin(), iFragEnd = Sec->end();
877          iFrag != iFragEnd; ++iFrag)
878       iFrag->setLayoutOrder(FragmentIndex++);
879   }
880
881   // Layout until everything fits.
882   while (layoutOnce(Layout))
883     continue;
884
885   DEBUG_WITH_TYPE("mc-dump", {
886       llvm::errs() << "assembler backend - post-relaxation\n--\n";
887       dump(); });
888
889   // Finalize the layout, including fragment lowering.
890   finishLayout(Layout);
891
892   DEBUG_WITH_TYPE("mc-dump", {
893       llvm::errs() << "assembler backend - final-layout\n--\n";
894       dump(); });
895
896   uint64_t StartOffset = OS.tell();
897
898   // Allow the object writer a chance to perform post-layout binding (for
899   // example, to set the index fields in the symbol data).
900   getWriter().executePostLayoutBinding(*this, Layout);
901
902   // Evaluate and apply the fixups, generating relocation entries as necessary.
903   for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
904     for (MCSection::iterator it2 = it->begin(), ie2 = it->end(); it2 != ie2;
905          ++it2) {
906       MCEncodedFragment *F = dyn_cast<MCEncodedFragment>(it2);
907       // Data and relaxable fragments both have fixups.  So only process
908       // those here.
909       // FIXME: Is there a better way to do this?  MCEncodedFragmentWithFixups
910       // being templated makes this tricky.
911       if (!F || isa<MCCompactEncodedInstFragment>(F))
912         continue;
913       ArrayRef<MCFixup> Fixups;
914       MutableArrayRef<char> Contents;
915       if (auto *FragWithFixups = dyn_cast<MCDataFragment>(F)) {
916         Fixups = FragWithFixups->getFixups();
917         Contents = FragWithFixups->getContents();
918       } else if (auto *FragWithFixups = dyn_cast<MCRelaxableFragment>(F)) {
919         Fixups = FragWithFixups->getFixups();
920         Contents = FragWithFixups->getContents();
921       } else
922         llvm_unreachable("Unknow fragment with fixups!");
923       for (const MCFixup &Fixup : Fixups) {
924         uint64_t FixedValue;
925         bool IsPCRel;
926         std::tie(FixedValue, IsPCRel) = handleFixup(Layout, *F, Fixup);
927         getBackend().applyFixup(Fixup, Contents.data(),
928                                 Contents.size(), FixedValue, IsPCRel);
929       }
930     }
931   }
932
933   // Write the object file.
934   getWriter().writeObject(*this, Layout);
935
936   stats::ObjectBytes += OS.tell() - StartOffset;
937 }
938
939 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
940                                        const MCRelaxableFragment *DF,
941                                        const MCAsmLayout &Layout) const {
942   MCValue Target;
943   uint64_t Value;
944   bool Resolved = evaluateFixup(Layout, Fixup, DF, Target, Value);
945   return getBackend().fixupNeedsRelaxationAdvanced(Fixup, Resolved, Value, DF,
946                                                    Layout);
947 }
948
949 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
950                                           const MCAsmLayout &Layout) const {
951   // If this inst doesn't ever need relaxation, ignore it. This occurs when we
952   // are intentionally pushing out inst fragments, or because we relaxed a
953   // previous instruction to one that doesn't need relaxation.
954   if (!getBackend().mayNeedRelaxation(F->getInst()))
955     return false;
956
957   for (MCRelaxableFragment::const_fixup_iterator it = F->fixup_begin(),
958        ie = F->fixup_end(); it != ie; ++it)
959     if (fixupNeedsRelaxation(*it, F, Layout))
960       return true;
961
962   return false;
963 }
964
965 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
966                                    MCRelaxableFragment &F) {
967   if (!fragmentNeedsRelaxation(&F, Layout))
968     return false;
969
970   ++stats::RelaxedInstructions;
971
972   // FIXME-PERF: We could immediately lower out instructions if we can tell
973   // they are fully resolved, to avoid retesting on later passes.
974
975   // Relax the fragment.
976
977   MCInst Relaxed;
978   getBackend().relaxInstruction(F.getInst(), Relaxed);
979
980   // Encode the new instruction.
981   //
982   // FIXME-PERF: If it matters, we could let the target do this. It can
983   // probably do so more efficiently in many cases.
984   SmallVector<MCFixup, 4> Fixups;
985   SmallString<256> Code;
986   raw_svector_ostream VecOS(Code);
987   getEmitter().encodeInstruction(Relaxed, VecOS, Fixups, F.getSubtargetInfo());
988   VecOS.flush();
989
990   // Update the fragment.
991   F.setInst(Relaxed);
992   F.getContents() = Code;
993   F.getFixups() = Fixups;
994
995   return true;
996 }
997
998 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
999   uint64_t OldSize = LF.getContents().size();
1000   int64_t Value;
1001   bool Abs = LF.getValue().evaluateKnownAbsolute(Value, Layout);
1002   if (!Abs)
1003     report_fatal_error("sleb128 and uleb128 expressions must be absolute");
1004   SmallString<8> &Data = LF.getContents();
1005   Data.clear();
1006   raw_svector_ostream OSE(Data);
1007   if (LF.isSigned())
1008     encodeSLEB128(Value, OSE);
1009   else
1010     encodeULEB128(Value, OSE);
1011   OSE.flush();
1012   return OldSize != LF.getContents().size();
1013 }
1014
1015 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
1016                                      MCDwarfLineAddrFragment &DF) {
1017   MCContext &Context = Layout.getAssembler().getContext();
1018   uint64_t OldSize = DF.getContents().size();
1019   int64_t AddrDelta;
1020   bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1021   assert(Abs && "We created a line delta with an invalid expression");
1022   (void) Abs;
1023   int64_t LineDelta;
1024   LineDelta = DF.getLineDelta();
1025   SmallString<8> &Data = DF.getContents();
1026   Data.clear();
1027   raw_svector_ostream OSE(Data);
1028   MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OSE);
1029   OSE.flush();
1030   return OldSize != Data.size();
1031 }
1032
1033 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
1034                                               MCDwarfCallFrameFragment &DF) {
1035   MCContext &Context = Layout.getAssembler().getContext();
1036   uint64_t OldSize = DF.getContents().size();
1037   int64_t AddrDelta;
1038   bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1039   assert(Abs && "We created call frame with an invalid expression");
1040   (void) Abs;
1041   SmallString<8> &Data = DF.getContents();
1042   Data.clear();
1043   raw_svector_ostream OSE(Data);
1044   MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
1045   OSE.flush();
1046   return OldSize != Data.size();
1047 }
1048
1049 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec) {
1050   // Holds the first fragment which needed relaxing during this layout. It will
1051   // remain NULL if none were relaxed.
1052   // When a fragment is relaxed, all the fragments following it should get
1053   // invalidated because their offset is going to change.
1054   MCFragment *FirstRelaxedFragment = nullptr;
1055
1056   // Attempt to relax all the fragments in the section.
1057   for (MCSection::iterator I = Sec.begin(), IE = Sec.end(); I != IE; ++I) {
1058     // Check if this is a fragment that needs relaxation.
1059     bool RelaxedFrag = false;
1060     switch(I->getKind()) {
1061     default:
1062       break;
1063     case MCFragment::FT_Relaxable:
1064       assert(!getRelaxAll() &&
1065              "Did not expect a MCRelaxableFragment in RelaxAll mode");
1066       RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
1067       break;
1068     case MCFragment::FT_Dwarf:
1069       RelaxedFrag = relaxDwarfLineAddr(Layout,
1070                                        *cast<MCDwarfLineAddrFragment>(I));
1071       break;
1072     case MCFragment::FT_DwarfFrame:
1073       RelaxedFrag =
1074         relaxDwarfCallFrameFragment(Layout,
1075                                     *cast<MCDwarfCallFrameFragment>(I));
1076       break;
1077     case MCFragment::FT_LEB:
1078       RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
1079       break;
1080     }
1081     if (RelaxedFrag && !FirstRelaxedFragment)
1082       FirstRelaxedFragment = I;
1083   }
1084   if (FirstRelaxedFragment) {
1085     Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
1086     return true;
1087   }
1088   return false;
1089 }
1090
1091 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
1092   ++stats::RelaxationSteps;
1093
1094   bool WasRelaxed = false;
1095   for (iterator it = begin(), ie = end(); it != ie; ++it) {
1096     MCSection &Sec = *it;
1097     while (layoutSectionOnce(Layout, Sec))
1098       WasRelaxed = true;
1099   }
1100
1101   return WasRelaxed;
1102 }
1103
1104 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
1105   // The layout is done. Mark every fragment as valid.
1106   for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
1107     Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
1108   }
1109 }
1110
1111 // Debugging methods
1112
1113 namespace llvm {
1114
1115 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
1116   OS << "<MCFixup" << " Offset:" << AF.getOffset()
1117      << " Value:" << *AF.getValue()
1118      << " Kind:" << AF.getKind() << ">";
1119   return OS;
1120 }
1121
1122 }
1123
1124 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1125 void MCFragment::dump() {
1126   raw_ostream &OS = llvm::errs();
1127
1128   OS << "<";
1129   switch (getKind()) {
1130   case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
1131   case MCFragment::FT_Data:  OS << "MCDataFragment"; break;
1132   case MCFragment::FT_CompactEncodedInst:
1133     OS << "MCCompactEncodedInstFragment"; break;
1134   case MCFragment::FT_Fill:  OS << "MCFillFragment"; break;
1135   case MCFragment::FT_Relaxable:  OS << "MCRelaxableFragment"; break;
1136   case MCFragment::FT_Org:   OS << "MCOrgFragment"; break;
1137   case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
1138   case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
1139   case MCFragment::FT_LEB:   OS << "MCLEBFragment"; break;
1140   case MCFragment::FT_SafeSEH:    OS << "MCSafeSEHFragment"; break;
1141   }
1142
1143   OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
1144      << " Offset:" << Offset
1145      << " HasInstructions:" << hasInstructions() 
1146      << " BundlePadding:" << static_cast<unsigned>(getBundlePadding()) << ">";
1147
1148   switch (getKind()) {
1149   case MCFragment::FT_Align: {
1150     const MCAlignFragment *AF = cast<MCAlignFragment>(this);
1151     if (AF->hasEmitNops())
1152       OS << " (emit nops)";
1153     OS << "\n       ";
1154     OS << " Alignment:" << AF->getAlignment()
1155        << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
1156        << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
1157     break;
1158   }
1159   case MCFragment::FT_Data:  {
1160     const MCDataFragment *DF = cast<MCDataFragment>(this);
1161     OS << "\n       ";
1162     OS << " Contents:[";
1163     const SmallVectorImpl<char> &Contents = DF->getContents();
1164     for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1165       if (i) OS << ",";
1166       OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1167     }
1168     OS << "] (" << Contents.size() << " bytes)";
1169
1170     if (DF->fixup_begin() != DF->fixup_end()) {
1171       OS << ",\n       ";
1172       OS << " Fixups:[";
1173       for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
1174              ie = DF->fixup_end(); it != ie; ++it) {
1175         if (it != DF->fixup_begin()) OS << ",\n                ";
1176         OS << *it;
1177       }
1178       OS << "]";
1179     }
1180     break;
1181   }
1182   case MCFragment::FT_CompactEncodedInst: {
1183     const MCCompactEncodedInstFragment *CEIF =
1184       cast<MCCompactEncodedInstFragment>(this);
1185     OS << "\n       ";
1186     OS << " Contents:[";
1187     const SmallVectorImpl<char> &Contents = CEIF->getContents();
1188     for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1189       if (i) OS << ",";
1190       OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1191     }
1192     OS << "] (" << Contents.size() << " bytes)";
1193     break;
1194   }
1195   case MCFragment::FT_Fill:  {
1196     const MCFillFragment *FF = cast<MCFillFragment>(this);
1197     OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
1198        << " Size:" << FF->getSize();
1199     break;
1200   }
1201   case MCFragment::FT_Relaxable:  {
1202     const MCRelaxableFragment *F = cast<MCRelaxableFragment>(this);
1203     OS << "\n       ";
1204     OS << " Inst:";
1205     F->getInst().dump_pretty(OS);
1206     break;
1207   }
1208   case MCFragment::FT_Org:  {
1209     const MCOrgFragment *OF = cast<MCOrgFragment>(this);
1210     OS << "\n       ";
1211     OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
1212     break;
1213   }
1214   case MCFragment::FT_Dwarf:  {
1215     const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
1216     OS << "\n       ";
1217     OS << " AddrDelta:" << OF->getAddrDelta()
1218        << " LineDelta:" << OF->getLineDelta();
1219     break;
1220   }
1221   case MCFragment::FT_DwarfFrame:  {
1222     const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
1223     OS << "\n       ";
1224     OS << " AddrDelta:" << CF->getAddrDelta();
1225     break;
1226   }
1227   case MCFragment::FT_LEB: {
1228     const MCLEBFragment *LF = cast<MCLEBFragment>(this);
1229     OS << "\n       ";
1230     OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
1231     break;
1232   }
1233   case MCFragment::FT_SafeSEH: {
1234     const MCSafeSEHFragment *F = cast<MCSafeSEHFragment>(this);
1235     OS << "\n       ";
1236     OS << " Sym:" << F->getSymbol();
1237     break;
1238   }
1239   }
1240   OS << ">";
1241 }
1242
1243 void MCAssembler::dump() {
1244   raw_ostream &OS = llvm::errs();
1245
1246   OS << "<MCAssembler\n";
1247   OS << "  Sections:[\n    ";
1248   for (iterator it = begin(), ie = end(); it != ie; ++it) {
1249     if (it != begin()) OS << ",\n    ";
1250     it->dump();
1251   }
1252   OS << "],\n";
1253   OS << "  Symbols:[";
1254
1255   for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1256     if (it != symbol_begin()) OS << ",\n           ";
1257     OS << "(";
1258     it->dump();
1259     OS << ", Index:" << it->getIndex() << ", ";
1260     OS << ")";
1261   }
1262   OS << "]>\n";
1263 }
1264 #endif