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