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