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