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