This patch adds statistics for other non-DWARF fragments emitted by
[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(EmittedInstFragments,
38           "Number of emitted assembler fragments - instruction");
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::isFragmentUpToDate(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::Invalidate(MCFragment *F) {
84   // If this fragment wasn't already up-to-date, we don't need to do anything.
85   if (!isFragmentUpToDate(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 up-to-date.
103   while (!isFragmentUpToDate(F)) {
104     const_cast<MCAsmLayout*>(this)->LayoutFragment(Cur);
105     Cur = Cur->getNextNode();
106   }
107 }
108
109 uint64_t MCAsmLayout::getFragmentOffset(const MCFragment *F) const {
110   EnsureValid(F);
111   assert(F->Offset != ~UINT64_C(0) && "Address not set!");
112   return F->Offset;
113 }
114
115 uint64_t MCAsmLayout::getSymbolOffset(const MCSymbolData *SD) const {
116   const MCSymbol &S = SD->getSymbol();
117
118   // If this is a variable, then recursively evaluate now.
119   if (S.isVariable()) {
120     MCValue Target;
121     if (!S.getVariableValue()->EvaluateAsRelocatable(Target, *this))
122       report_fatal_error("unable to evaluate offset for variable '" +
123                          S.getName() + "'");
124
125     // Verify that any used symbols are defined.
126     if (Target.getSymA() && Target.getSymA()->getSymbol().isUndefined())
127       report_fatal_error("unable to evaluate offset to undefined symbol '" +
128                          Target.getSymA()->getSymbol().getName() + "'");
129     if (Target.getSymB() && Target.getSymB()->getSymbol().isUndefined())
130       report_fatal_error("unable to evaluate offset to undefined symbol '" +
131                          Target.getSymB()->getSymbol().getName() + "'");
132
133     uint64_t Offset = Target.getConstant();
134     if (Target.getSymA())
135       Offset += getSymbolOffset(&Assembler.getSymbolData(
136                                   Target.getSymA()->getSymbol()));
137     if (Target.getSymB())
138       Offset -= getSymbolOffset(&Assembler.getSymbolData(
139                                   Target.getSymB()->getSymbol()));
140     return Offset;
141   }
142
143   assert(SD->getFragment() && "Invalid getOffset() on undefined symbol!");
144   return getFragmentOffset(SD->getFragment()) + SD->getOffset();
145 }
146
147 uint64_t MCAsmLayout::getSectionAddressSize(const MCSectionData *SD) const {
148   // The size is the last fragment's end offset.
149   const MCFragment &F = SD->getFragmentList().back();
150   return getFragmentOffset(&F) + getAssembler().computeFragmentSize(*this, F);
151 }
152
153 uint64_t MCAsmLayout::getSectionFileSize(const MCSectionData *SD) const {
154   // Virtual sections have no file size.
155   if (SD->getSection().isVirtualSection())
156     return 0;
157
158   // Otherwise, the file size is the same as the address space size.
159   return getSectionAddressSize(SD);
160 }
161
162 /* *** */
163
164 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
165 }
166
167 MCFragment::~MCFragment() {
168 }
169
170 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
171   : Kind(_Kind), Parent(_Parent), Atom(0), Offset(~UINT64_C(0))
172 {
173   if (Parent)
174     Parent->getFragmentList().push_back(this);
175 }
176
177 /* *** */
178
179 MCEncodedFragment::~MCEncodedFragment() {
180 }
181
182 /* *** */
183
184 MCSectionData::MCSectionData() : Section(0) {}
185
186 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
187   : Section(&_Section),
188     Ordinal(~UINT32_C(0)),
189     Alignment(1),
190     HasInstructions(false)
191 {
192   if (A)
193     A->getSectionList().push_back(this);
194 }
195
196 /* *** */
197
198 MCSymbolData::MCSymbolData() : Symbol(0) {}
199
200 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
201                            uint64_t _Offset, MCAssembler *A)
202   : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
203     IsExternal(false), IsPrivateExtern(false),
204     CommonSize(0), SymbolSize(0), CommonAlign(0),
205     Flags(0), Index(0)
206 {
207   if (A)
208     A->getSymbolList().push_back(this);
209 }
210
211 /* *** */
212
213 MCAssembler::MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
214                          MCCodeEmitter &Emitter_, MCObjectWriter &Writer_,
215                          raw_ostream &OS_)
216   : Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
217     OS(OS_), RelaxAll(false), NoExecStack(false), SubsectionsViaSymbols(false) {
218 }
219
220 MCAssembler::~MCAssembler() {
221 }
222
223 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
224   // Non-temporary labels should always be visible to the linker.
225   if (!Symbol.isTemporary())
226     return true;
227
228   // Absolute temporary labels are never visible.
229   if (!Symbol.isInSection())
230     return false;
231
232   // Otherwise, check if the section requires symbols even for temporary labels.
233   return getBackend().doesSectionRequireSymbols(Symbol.getSection());
234 }
235
236 const MCSymbolData *MCAssembler::getAtom(const MCSymbolData *SD) const {
237   // Linker visible symbols define atoms.
238   if (isSymbolLinkerVisible(SD->getSymbol()))
239     return SD;
240
241   // Absolute and undefined symbols have no defining atom.
242   if (!SD->getFragment())
243     return 0;
244
245   // Non-linker visible symbols in sections which can't be atomized have no
246   // defining atom.
247   if (!getBackend().isSectionAtomizable(
248         SD->getFragment()->getParent()->getSection()))
249     return 0;
250
251   // Otherwise, return the atom for the containing fragment.
252   return SD->getFragment()->getAtom();
253 }
254
255 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
256                                 const MCFixup &Fixup, const MCFragment *DF,
257                                 MCValue &Target, uint64_t &Value) const {
258   ++stats::evaluateFixup;
259
260   if (!Fixup.getValue()->EvaluateAsRelocatable(Target, Layout))
261     getContext().FatalError(Fixup.getLoc(), "expected relocatable expression");
262
263   bool IsPCRel = Backend.getFixupKindInfo(
264     Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
265
266   bool IsResolved;
267   if (IsPCRel) {
268     if (Target.getSymB()) {
269       IsResolved = false;
270     } else if (!Target.getSymA()) {
271       IsResolved = false;
272     } else {
273       const MCSymbolRefExpr *A = Target.getSymA();
274       const MCSymbol &SA = A->getSymbol();
275       if (A->getKind() != MCSymbolRefExpr::VK_None ||
276           SA.AliasedSymbol().isUndefined()) {
277         IsResolved = false;
278       } else {
279         const MCSymbolData &DataA = getSymbolData(SA);
280         IsResolved =
281           getWriter().IsSymbolRefDifferenceFullyResolvedImpl(*this, DataA,
282                                                              *DF, false, true);
283       }
284     }
285   } else {
286     IsResolved = Target.isAbsolute();
287   }
288
289   Value = Target.getConstant();
290
291   if (const MCSymbolRefExpr *A = Target.getSymA()) {
292     const MCSymbol &Sym = A->getSymbol().AliasedSymbol();
293     if (Sym.isDefined())
294       Value += Layout.getSymbolOffset(&getSymbolData(Sym));
295   }
296   if (const MCSymbolRefExpr *B = Target.getSymB()) {
297     const MCSymbol &Sym = B->getSymbol().AliasedSymbol();
298     if (Sym.isDefined())
299       Value -= Layout.getSymbolOffset(&getSymbolData(Sym));
300   }
301
302
303   bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
304                          MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
305   assert((ShouldAlignPC ? IsPCRel : true) &&
306     "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
307
308   if (IsPCRel) {
309     uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
310
311     // A number of ARM fixups in Thumb mode require that the effective PC
312     // address be determined as the 32-bit aligned version of the actual offset.
313     if (ShouldAlignPC) Offset &= ~0x3;
314     Value -= Offset;
315   }
316
317   // Let the backend adjust the fixup value if necessary, including whether
318   // we need a relocation.
319   Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
320                             IsResolved);
321
322   return IsResolved;
323 }
324
325 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
326                                           const MCFragment &F) const {
327   switch (F.getKind()) {
328   case MCFragment::FT_Data:
329     return cast<MCDataFragment>(F).getContents().size();
330   case MCFragment::FT_Fill:
331     return cast<MCFillFragment>(F).getSize();
332   case MCFragment::FT_Inst:
333     return cast<MCInstFragment>(F).getInstSize();
334
335   case MCFragment::FT_LEB:
336     return cast<MCLEBFragment>(F).getContents().size();
337
338   case MCFragment::FT_Align: {
339     const MCAlignFragment &AF = cast<MCAlignFragment>(F);
340     unsigned Offset = Layout.getFragmentOffset(&AF);
341     unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
342     // If we are padding with nops, force the padding to be larger than the
343     // minimum nop size.
344     if (Size > 0 && AF.hasEmitNops()) {
345       while (Size % getBackend().getMinimumNopSize())
346         Size += AF.getAlignment();
347     }
348     if (Size > AF.getMaxBytesToEmit())
349       return 0;
350     return Size;
351   }
352
353   case MCFragment::FT_Org: {
354     MCOrgFragment &OF = cast<MCOrgFragment>(F);
355     int64_t TargetLocation;
356     if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, Layout))
357       report_fatal_error("expected assembly-time absolute expression");
358
359     // FIXME: We need a way to communicate this error.
360     uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
361     int64_t Size = TargetLocation - FragmentOffset;
362     if (Size < 0 || Size >= 0x40000000)
363       report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
364                          "' (at offset '" + Twine(FragmentOffset) + "')");
365     return Size;
366   }
367
368   case MCFragment::FT_Dwarf:
369     return cast<MCDwarfLineAddrFragment>(F).getContents().size();
370   case MCFragment::FT_DwarfFrame:
371     return cast<MCDwarfCallFrameFragment>(F).getContents().size();
372   }
373
374   llvm_unreachable("invalid fragment kind");
375 }
376
377 void MCAsmLayout::LayoutFragment(MCFragment *F) {
378   MCFragment *Prev = F->getPrevNode();
379
380   // We should never try to recompute something which is up-to-date.
381   assert(!isFragmentUpToDate(F) && "Attempt to recompute up-to-date fragment!");
382   // We should never try to compute the fragment layout if it's predecessor
383   // isn't up-to-date.
384   assert((!Prev || isFragmentUpToDate(Prev)) &&
385          "Attempt to compute fragment before it's predecessor!");
386
387   ++stats::FragmentLayouts;
388
389   // Compute fragment offset and size.
390   uint64_t Offset = 0;
391   if (Prev)
392     Offset += Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
393
394   F->Offset = Offset;
395   LastValidFragment[F->getParent()] = F;
396 }
397
398 /// \brief Write the contents of a fragment to the given object writer. Expects
399 ///        a MCEncodedFragment.
400 static void writeFragmentContents(const MCFragment &F, MCObjectWriter *OW) {
401   MCEncodedFragment &EF = cast<MCEncodedFragment>(F);
402   OW->WriteBytes(EF.getContents());
403 }
404
405 /// \brief Write the fragment \p F to the output file.
406 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
407                           const MCFragment &F) {
408   MCObjectWriter *OW = &Asm.getWriter();
409   uint64_t Start = OW->getStream().tell();
410   (void) Start;
411
412   ++stats::EmittedFragments;
413
414   // FIXME: Embed in fragments instead?
415   uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
416   switch (F.getKind()) {
417   case MCFragment::FT_Align: {
418     ++stats::EmittedAlignFragments;
419     MCAlignFragment &AF = cast<MCAlignFragment>(F);
420     uint64_t Count = FragmentSize / AF.getValueSize();
421
422     assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
423
424     // FIXME: This error shouldn't actually occur (the front end should emit
425     // multiple .align directives to enforce the semantics it wants), but is
426     // severe enough that we want to report it. How to handle this?
427     if (Count * AF.getValueSize() != FragmentSize)
428       report_fatal_error("undefined .align directive, value size '" +
429                         Twine(AF.getValueSize()) +
430                         "' is not a divisor of padding size '" +
431                         Twine(FragmentSize) + "'");
432
433     // See if we are aligning with nops, and if so do that first to try to fill
434     // the Count bytes.  Then if that did not fill any bytes or there are any
435     // bytes left to fill use the Value and ValueSize to fill the rest.
436     // If we are aligning with nops, ask that target to emit the right data.
437     if (AF.hasEmitNops()) {
438       if (!Asm.getBackend().writeNopData(Count, OW))
439         report_fatal_error("unable to write nop sequence of " +
440                           Twine(Count) + " bytes");
441       break;
442     }
443
444     // Otherwise, write out in multiples of the value size.
445     for (uint64_t i = 0; i != Count; ++i) {
446       switch (AF.getValueSize()) {
447       default: llvm_unreachable("Invalid size!");
448       case 1: OW->Write8 (uint8_t (AF.getValue())); break;
449       case 2: OW->Write16(uint16_t(AF.getValue())); break;
450       case 4: OW->Write32(uint32_t(AF.getValue())); break;
451       case 8: OW->Write64(uint64_t(AF.getValue())); break;
452       }
453     }
454     break;
455   }
456
457   case MCFragment::FT_Data: 
458     ++stats::EmittedDataFragments;
459     writeFragmentContents(F, OW);
460     break;
461
462   case MCFragment::FT_Inst:
463     ++stats::EmittedInstFragments;
464     writeFragmentContents(F, OW);
465     break;
466
467   case MCFragment::FT_Fill: {
468     ++stats::EmittedFillFragments;
469     MCFillFragment &FF = cast<MCFillFragment>(F);
470
471     assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
472
473     for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
474       switch (FF.getValueSize()) {
475       default: llvm_unreachable("Invalid size!");
476       case 1: OW->Write8 (uint8_t (FF.getValue())); break;
477       case 2: OW->Write16(uint16_t(FF.getValue())); break;
478       case 4: OW->Write32(uint32_t(FF.getValue())); break;
479       case 8: OW->Write64(uint64_t(FF.getValue())); break;
480       }
481     }
482     break;
483   }
484
485   case MCFragment::FT_LEB: {
486     MCLEBFragment &LF = cast<MCLEBFragment>(F);
487     OW->WriteBytes(LF.getContents().str());
488     break;
489   }
490
491   case MCFragment::FT_Org: {
492     ++stats::EmittedOrgFragments;
493     MCOrgFragment &OF = cast<MCOrgFragment>(F);
494
495     for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
496       OW->Write8(uint8_t(OF.getValue()));
497
498     break;
499   }
500
501   case MCFragment::FT_Dwarf: {
502     const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
503     OW->WriteBytes(OF.getContents().str());
504     break;
505   }
506   case MCFragment::FT_DwarfFrame: {
507     const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
508     OW->WriteBytes(CF.getContents().str());
509     break;
510   }
511   }
512
513   assert(OW->getStream().tell() - Start == FragmentSize);
514 }
515
516 void MCAssembler::writeSectionData(const MCSectionData *SD,
517                                    const MCAsmLayout &Layout) const {
518   // Ignore virtual sections.
519   if (SD->getSection().isVirtualSection()) {
520     assert(Layout.getSectionFileSize(SD) == 0 && "Invalid size for section!");
521
522     // Check that contents are only things legal inside a virtual section.
523     for (MCSectionData::const_iterator it = SD->begin(),
524            ie = SD->end(); it != ie; ++it) {
525       switch (it->getKind()) {
526       default: llvm_unreachable("Invalid fragment in virtual section!");
527       case MCFragment::FT_Data: {
528         // Check that we aren't trying to write a non-zero contents (or fixups)
529         // into a virtual section. This is to support clients which use standard
530         // directives to fill the contents of virtual sections.
531         MCDataFragment &DF = cast<MCDataFragment>(*it);
532         assert(DF.fixup_begin() == DF.fixup_end() &&
533                "Cannot have fixups in virtual section!");
534         for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
535           assert(DF.getContents()[i] == 0 &&
536                  "Invalid data value for virtual section!");
537         break;
538       }
539       case MCFragment::FT_Align:
540         // Check that we aren't trying to write a non-zero value into a virtual
541         // section.
542         assert((!cast<MCAlignFragment>(it)->getValueSize() ||
543                 !cast<MCAlignFragment>(it)->getValue()) &&
544                "Invalid align in virtual section!");
545         break;
546       case MCFragment::FT_Fill:
547         assert(!cast<MCFillFragment>(it)->getValueSize() &&
548                "Invalid fill in virtual section!");
549         break;
550       }
551     }
552
553     return;
554   }
555
556   uint64_t Start = getWriter().getStream().tell();
557   (void)Start;
558
559   for (MCSectionData::const_iterator it = SD->begin(), ie = SD->end();
560        it != ie; ++it)
561     writeFragment(*this, Layout, *it);
562
563   assert(getWriter().getStream().tell() - Start ==
564          Layout.getSectionAddressSize(SD));
565 }
566
567
568 uint64_t MCAssembler::handleFixup(const MCAsmLayout &Layout,
569                                   MCFragment &F,
570                                   const MCFixup &Fixup) {
571    // Evaluate the fixup.
572    MCValue Target;
573    uint64_t FixedValue;
574    if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
575      // The fixup was unresolved, we need a relocation. Inform the object
576      // writer of the relocation, and give it an opportunity to adjust the
577      // fixup value if need be.
578      getWriter().RecordRelocation(*this, Layout, &F, Fixup, Target, FixedValue);
579    }
580    return FixedValue;
581  }
582
583 void MCAssembler::Finish() {
584   DEBUG_WITH_TYPE("mc-dump", {
585       llvm::errs() << "assembler backend - pre-layout\n--\n";
586       dump(); });
587
588   // Create the layout object.
589   MCAsmLayout Layout(*this);
590
591   // Create dummy fragments and assign section ordinals.
592   unsigned SectionIndex = 0;
593   for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
594     // Create dummy fragments to eliminate any empty sections, this simplifies
595     // layout.
596     if (it->getFragmentList().empty())
597       new MCDataFragment(it);
598
599     it->setOrdinal(SectionIndex++);
600   }
601
602   // Assign layout order indices to sections and fragments.
603   for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
604     MCSectionData *SD = Layout.getSectionOrder()[i];
605     SD->setLayoutOrder(i);
606
607     unsigned FragmentIndex = 0;
608     for (MCSectionData::iterator it2 = SD->begin(),
609            ie2 = SD->end(); it2 != ie2; ++it2)
610       it2->setLayoutOrder(FragmentIndex++);
611   }
612
613   // Layout until everything fits.
614   while (layoutOnce(Layout))
615     continue;
616
617   DEBUG_WITH_TYPE("mc-dump", {
618       llvm::errs() << "assembler backend - post-relaxation\n--\n";
619       dump(); });
620
621   // Finalize the layout, including fragment lowering.
622   finishLayout(Layout);
623
624   DEBUG_WITH_TYPE("mc-dump", {
625       llvm::errs() << "assembler backend - final-layout\n--\n";
626       dump(); });
627
628   uint64_t StartOffset = OS.tell();
629
630   // Allow the object writer a chance to perform post-layout binding (for
631   // example, to set the index fields in the symbol data).
632   getWriter().ExecutePostLayoutBinding(*this, Layout);
633
634   // Evaluate and apply the fixups, generating relocation entries as necessary.
635   for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
636     for (MCSectionData::iterator it2 = it->begin(),
637            ie2 = it->end(); it2 != ie2; ++it2) {
638       MCEncodedFragment *F = dyn_cast<MCEncodedFragment>(it2);
639       if (F) {
640         for (MCEncodedFragment::fixup_iterator it3 = F->fixup_begin(),
641              ie3 = F->fixup_end(); it3 != ie3; ++it3) {
642           MCFixup &Fixup = *it3;
643           uint64_t FixedValue = handleFixup(Layout, *F, Fixup);
644           getBackend().applyFixup(Fixup, F->getContents().data(),
645                                   F->getContents().size(), FixedValue);
646         }
647       }
648     }
649   }
650
651   // Write the object file.
652   getWriter().WriteObject(*this, Layout);
653
654   stats::ObjectBytes += OS.tell() - StartOffset;
655 }
656
657 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
658                                        const MCInstFragment *DF,
659                                        const MCAsmLayout &Layout) const {
660   if (getRelaxAll())
661     return true;
662
663   // If we cannot resolve the fixup value, it requires relaxation.
664   MCValue Target;
665   uint64_t Value;
666   if (!evaluateFixup(Layout, Fixup, DF, Target, Value))
667     return true;
668
669   return getBackend().fixupNeedsRelaxation(Fixup, Value, DF, Layout);
670 }
671
672 bool MCAssembler::fragmentNeedsRelaxation(const MCInstFragment *IF,
673                                           const MCAsmLayout &Layout) const {
674   // If this inst doesn't ever need relaxation, ignore it. This occurs when we
675   // are intentionally pushing out inst fragments, or because we relaxed a
676   // previous instruction to one that doesn't need relaxation.
677   if (!getBackend().mayNeedRelaxation(IF->getInst()))
678     return false;
679
680   for (MCInstFragment::const_fixup_iterator it = IF->fixup_begin(),
681          ie = IF->fixup_end(); it != ie; ++it)
682     if (fixupNeedsRelaxation(*it, IF, Layout))
683       return true;
684
685   return false;
686 }
687
688 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
689                                    MCInstFragment &IF) {
690   if (!fragmentNeedsRelaxation(&IF, Layout))
691     return false;
692
693   ++stats::RelaxedInstructions;
694
695   // FIXME-PERF: We could immediately lower out instructions if we can tell
696   // they are fully resolved, to avoid retesting on later passes.
697
698   // Relax the fragment.
699
700   MCInst Relaxed;
701   getBackend().relaxInstruction(IF.getInst(), Relaxed);
702
703   // Encode the new instruction.
704   //
705   // FIXME-PERF: If it matters, we could let the target do this. It can
706   // probably do so more efficiently in many cases.
707   SmallVector<MCFixup, 4> Fixups;
708   SmallString<256> Code;
709   raw_svector_ostream VecOS(Code);
710   getEmitter().EncodeInstruction(Relaxed, VecOS, Fixups);
711   VecOS.flush();
712
713   // Update the instruction fragment.
714   IF.setInst(Relaxed);
715   IF.getContents() = Code;
716   IF.getFixups() = Fixups;
717
718   return true;
719 }
720
721 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
722   int64_t Value = 0;
723   uint64_t OldSize = LF.getContents().size();
724   bool IsAbs = LF.getValue().EvaluateAsAbsolute(Value, Layout);
725   (void)IsAbs;
726   assert(IsAbs);
727   SmallString<8> &Data = LF.getContents();
728   Data.clear();
729   raw_svector_ostream OSE(Data);
730   if (LF.isSigned())
731     encodeSLEB128(Value, OSE);
732   else
733     encodeULEB128(Value, OSE);
734   OSE.flush();
735   return OldSize != LF.getContents().size();
736 }
737
738 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
739                                      MCDwarfLineAddrFragment &DF) {
740   int64_t AddrDelta = 0;
741   uint64_t OldSize = DF.getContents().size();
742   bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
743   (void)IsAbs;
744   assert(IsAbs);
745   int64_t LineDelta;
746   LineDelta = DF.getLineDelta();
747   SmallString<8> &Data = DF.getContents();
748   Data.clear();
749   raw_svector_ostream OSE(Data);
750   MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OSE);
751   OSE.flush();
752   return OldSize != Data.size();
753 }
754
755 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
756                                               MCDwarfCallFrameFragment &DF) {
757   int64_t AddrDelta = 0;
758   uint64_t OldSize = DF.getContents().size();
759   bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
760   (void)IsAbs;
761   assert(IsAbs);
762   SmallString<8> &Data = DF.getContents();
763   Data.clear();
764   raw_svector_ostream OSE(Data);
765   MCDwarfFrameEmitter::EncodeAdvanceLoc(AddrDelta, OSE);
766   OSE.flush();
767   return OldSize != Data.size();
768 }
769
770 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout,
771                                     MCSectionData &SD) {
772   MCFragment *FirstInvalidFragment = NULL;
773   // Scan for fragments that need relaxation.
774   for (MCSectionData::iterator it2 = SD.begin(),
775          ie2 = SD.end(); it2 != ie2; ++it2) {
776     // Check if this is an fragment that needs relaxation.
777     bool relaxedFrag = false;
778     switch(it2->getKind()) {
779     default:
780           break;
781     case MCFragment::FT_Inst:
782       relaxedFrag = relaxInstruction(Layout, *cast<MCInstFragment>(it2));
783       break;
784     case MCFragment::FT_Dwarf:
785       relaxedFrag = relaxDwarfLineAddr(Layout,
786                                        *cast<MCDwarfLineAddrFragment>(it2));
787       break;
788     case MCFragment::FT_DwarfFrame:
789       relaxedFrag =
790         relaxDwarfCallFrameFragment(Layout,
791                                     *cast<MCDwarfCallFrameFragment>(it2));
792       break;
793     case MCFragment::FT_LEB:
794       relaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(it2));
795       break;
796     }
797     // Update the layout, and remember that we relaxed.
798     if (relaxedFrag && !FirstInvalidFragment)
799       FirstInvalidFragment = it2;
800   }
801   if (FirstInvalidFragment) {
802     Layout.Invalidate(FirstInvalidFragment);
803     return true;
804   }
805   return false;
806 }
807
808 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
809   ++stats::RelaxationSteps;
810
811   bool WasRelaxed = false;
812   for (iterator it = begin(), ie = end(); it != ie; ++it) {
813     MCSectionData &SD = *it;
814     while(layoutSectionOnce(Layout, SD))
815       WasRelaxed = true;
816   }
817
818   return WasRelaxed;
819 }
820
821 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
822   // The layout is done. Mark every fragment as valid.
823   for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
824     Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
825   }
826 }
827
828 // Debugging methods
829
830 namespace llvm {
831
832 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
833   OS << "<MCFixup" << " Offset:" << AF.getOffset()
834      << " Value:" << *AF.getValue()
835      << " Kind:" << AF.getKind() << ">";
836   return OS;
837 }
838
839 }
840
841 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
842 void MCFragment::dump() {
843   raw_ostream &OS = llvm::errs();
844
845   OS << "<";
846   switch (getKind()) {
847   case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
848   case MCFragment::FT_Data:  OS << "MCDataFragment"; break;
849   case MCFragment::FT_Fill:  OS << "MCFillFragment"; break;
850   case MCFragment::FT_Inst:  OS << "MCInstFragment"; break;
851   case MCFragment::FT_Org:   OS << "MCOrgFragment"; break;
852   case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
853   case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
854   case MCFragment::FT_LEB:   OS << "MCLEBFragment"; break;
855   }
856
857   OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
858      << " Offset:" << Offset << ">";
859
860   switch (getKind()) {
861   case MCFragment::FT_Align: {
862     const MCAlignFragment *AF = cast<MCAlignFragment>(this);
863     if (AF->hasEmitNops())
864       OS << " (emit nops)";
865     OS << "\n       ";
866     OS << " Alignment:" << AF->getAlignment()
867        << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
868        << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
869     break;
870   }
871   case MCFragment::FT_Data:  {
872     const MCDataFragment *DF = cast<MCDataFragment>(this);
873     OS << "\n       ";
874     OS << " Contents:[";
875     const SmallVectorImpl<char> &Contents = DF->getContents();
876     for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
877       if (i) OS << ",";
878       OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
879     }
880     OS << "] (" << Contents.size() << " bytes)";
881
882     if (DF->fixup_begin() != DF->fixup_end()) {
883       OS << ",\n       ";
884       OS << " Fixups:[";
885       for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
886              ie = DF->fixup_end(); it != ie; ++it) {
887         if (it != DF->fixup_begin()) OS << ",\n                ";
888         OS << *it;
889       }
890       OS << "]";
891     }
892     break;
893   }
894   case MCFragment::FT_Fill:  {
895     const MCFillFragment *FF = cast<MCFillFragment>(this);
896     OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
897        << " Size:" << FF->getSize();
898     break;
899   }
900   case MCFragment::FT_Inst:  {
901     const MCInstFragment *IF = cast<MCInstFragment>(this);
902     OS << "\n       ";
903     OS << " Inst:";
904     IF->getInst().dump_pretty(OS);
905     break;
906   }
907   case MCFragment::FT_Org:  {
908     const MCOrgFragment *OF = cast<MCOrgFragment>(this);
909     OS << "\n       ";
910     OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
911     break;
912   }
913   case MCFragment::FT_Dwarf:  {
914     const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
915     OS << "\n       ";
916     OS << " AddrDelta:" << OF->getAddrDelta()
917        << " LineDelta:" << OF->getLineDelta();
918     break;
919   }
920   case MCFragment::FT_DwarfFrame:  {
921     const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
922     OS << "\n       ";
923     OS << " AddrDelta:" << CF->getAddrDelta();
924     break;
925   }
926   case MCFragment::FT_LEB: {
927     const MCLEBFragment *LF = cast<MCLEBFragment>(this);
928     OS << "\n       ";
929     OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
930     break;
931   }
932   }
933   OS << ">";
934 }
935
936 void MCSectionData::dump() {
937   raw_ostream &OS = llvm::errs();
938
939   OS << "<MCSectionData";
940   OS << " Alignment:" << getAlignment() << " Fragments:[\n      ";
941   for (iterator it = begin(), ie = end(); it != ie; ++it) {
942     if (it != begin()) OS << ",\n      ";
943     it->dump();
944   }
945   OS << "]>";
946 }
947
948 void MCSymbolData::dump() {
949   raw_ostream &OS = llvm::errs();
950
951   OS << "<MCSymbolData Symbol:" << getSymbol()
952      << " Fragment:" << getFragment() << " Offset:" << getOffset()
953      << " Flags:" << getFlags() << " Index:" << getIndex();
954   if (isCommon())
955     OS << " (common, size:" << getCommonSize()
956        << " align: " << getCommonAlignment() << ")";
957   if (isExternal())
958     OS << " (external)";
959   if (isPrivateExtern())
960     OS << " (private extern)";
961   OS << ">";
962 }
963
964 void MCAssembler::dump() {
965   raw_ostream &OS = llvm::errs();
966
967   OS << "<MCAssembler\n";
968   OS << "  Sections:[\n    ";
969   for (iterator it = begin(), ie = end(); it != ie; ++it) {
970     if (it != begin()) OS << ",\n    ";
971     it->dump();
972   }
973   OS << "],\n";
974   OS << "  Symbols:[";
975
976   for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
977     if (it != symbol_begin()) OS << ",\n           ";
978     it->dump();
979   }
980   OS << "]>\n";
981 }
982 #endif
983
984 // anchors for MC*Fragment vtables
985 void MCEncodedFragment::anchor() { }
986 void MCDataFragment::anchor() { }
987 void MCInstFragment::anchor() { }
988 void MCAlignFragment::anchor() { }
989 void MCFillFragment::anchor() { }
990 void MCOrgFragment::anchor() { }
991 void MCLEBFragment::anchor() { }
992 void MCDwarfLineAddrFragment::anchor() { }
993 void MCDwarfCallFrameFragment::anchor() { }