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