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