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