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