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