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