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