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