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