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