Tidy up. MCAsmBackend naming conventions.
[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     report_fatal_error("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   assert(0 && "invalid fragment kind");
352   return 0;
353 }
354
355 void MCAsmLayout::LayoutFragment(MCFragment *F) {
356   MCFragment *Prev = F->getPrevNode();
357
358   // We should never try to recompute something which is up-to-date.
359   assert(!isFragmentUpToDate(F) && "Attempt to recompute up-to-date fragment!");
360   // We should never try to compute the fragment layout if it's predecessor
361   // isn't up-to-date.
362   assert((!Prev || isFragmentUpToDate(Prev)) &&
363          "Attempt to compute fragment before it's predecessor!");
364
365   ++stats::FragmentLayouts;
366
367   // Compute fragment offset and size.
368   uint64_t Offset = 0;
369   if (Prev)
370     Offset += Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
371
372   F->Offset = Offset;
373   LastValidFragment[F->getParent()] = F;
374 }
375
376 /// WriteFragmentData - Write the \arg F data to the output file.
377 static void WriteFragmentData(const MCAssembler &Asm, const MCAsmLayout &Layout,
378                               const MCFragment &F) {
379   MCObjectWriter *OW = &Asm.getWriter();
380   uint64_t Start = OW->getStream().tell();
381   (void) Start;
382
383   ++stats::EmittedFragments;
384
385   // FIXME: Embed in fragments instead?
386   uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
387   switch (F.getKind()) {
388   case MCFragment::FT_Align: {
389     MCAlignFragment &AF = cast<MCAlignFragment>(F);
390     uint64_t Count = FragmentSize / AF.getValueSize();
391
392     assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
393
394     // FIXME: This error shouldn't actually occur (the front end should emit
395     // multiple .align directives to enforce the semantics it wants), but is
396     // severe enough that we want to report it. How to handle this?
397     if (Count * AF.getValueSize() != FragmentSize)
398       report_fatal_error("undefined .align directive, value size '" +
399                         Twine(AF.getValueSize()) +
400                         "' is not a divisor of padding size '" +
401                         Twine(FragmentSize) + "'");
402
403     // See if we are aligning with nops, and if so do that first to try to fill
404     // the Count bytes.  Then if that did not fill any bytes or there are any
405     // bytes left to fill use the the Value and ValueSize to fill the rest.
406     // If we are aligning with nops, ask that target to emit the right data.
407     if (AF.hasEmitNops()) {
408       if (!Asm.getBackend().writeNopData(Count, OW))
409         report_fatal_error("unable to write nop sequence of " +
410                           Twine(Count) + " bytes");
411       break;
412     }
413
414     // Otherwise, write out in multiples of the value size.
415     for (uint64_t i = 0; i != Count; ++i) {
416       switch (AF.getValueSize()) {
417       default:
418         assert(0 && "Invalid size!");
419       case 1: OW->Write8 (uint8_t (AF.getValue())); break;
420       case 2: OW->Write16(uint16_t(AF.getValue())); break;
421       case 4: OW->Write32(uint32_t(AF.getValue())); break;
422       case 8: OW->Write64(uint64_t(AF.getValue())); break;
423       }
424     }
425     break;
426   }
427
428   case MCFragment::FT_Data: {
429     MCDataFragment &DF = cast<MCDataFragment>(F);
430     assert(FragmentSize == DF.getContents().size() && "Invalid size!");
431     OW->WriteBytes(DF.getContents().str());
432     break;
433   }
434
435   case MCFragment::FT_Fill: {
436     MCFillFragment &FF = cast<MCFillFragment>(F);
437
438     assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
439
440     for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
441       switch (FF.getValueSize()) {
442       default:
443         assert(0 && "Invalid size!");
444       case 1: OW->Write8 (uint8_t (FF.getValue())); break;
445       case 2: OW->Write16(uint16_t(FF.getValue())); break;
446       case 4: OW->Write32(uint32_t(FF.getValue())); break;
447       case 8: OW->Write64(uint64_t(FF.getValue())); break;
448       }
449     }
450     break;
451   }
452
453   case MCFragment::FT_Inst: {
454     MCInstFragment &IF = cast<MCInstFragment>(F);
455     OW->WriteBytes(StringRef(IF.getCode().begin(), IF.getCode().size()));
456     break;
457   }
458
459   case MCFragment::FT_LEB: {
460     MCLEBFragment &LF = cast<MCLEBFragment>(F);
461     OW->WriteBytes(LF.getContents().str());
462     break;
463   }
464
465   case MCFragment::FT_Org: {
466     MCOrgFragment &OF = cast<MCOrgFragment>(F);
467
468     for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
469       OW->Write8(uint8_t(OF.getValue()));
470
471     break;
472   }
473
474   case MCFragment::FT_Dwarf: {
475     const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
476     OW->WriteBytes(OF.getContents().str());
477     break;
478   }
479   case MCFragment::FT_DwarfFrame: {
480     const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
481     OW->WriteBytes(CF.getContents().str());
482     break;
483   }
484   }
485
486   assert(OW->getStream().tell() - Start == FragmentSize);
487 }
488
489 void MCAssembler::writeSectionData(const MCSectionData *SD,
490                                    const MCAsmLayout &Layout) const {
491   // Ignore virtual sections.
492   if (SD->getSection().isVirtualSection()) {
493     assert(Layout.getSectionFileSize(SD) == 0 && "Invalid size for section!");
494
495     // Check that contents are only things legal inside a virtual section.
496     for (MCSectionData::const_iterator it = SD->begin(),
497            ie = SD->end(); it != ie; ++it) {
498       switch (it->getKind()) {
499       default:
500         assert(0 && "Invalid fragment in virtual section!");
501       case MCFragment::FT_Data: {
502         // Check that we aren't trying to write a non-zero contents (or fixups)
503         // into a virtual section. This is to support clients which use standard
504         // directives to fill the contents of virtual sections.
505         MCDataFragment &DF = cast<MCDataFragment>(*it);
506         assert(DF.fixup_begin() == DF.fixup_end() &&
507                "Cannot have fixups in virtual section!");
508         for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
509           assert(DF.getContents()[i] == 0 &&
510                  "Invalid data value for virtual section!");
511         break;
512       }
513       case MCFragment::FT_Align:
514         // Check that we aren't trying to write a non-zero value into a virtual
515         // section.
516         assert((!cast<MCAlignFragment>(it)->getValueSize() ||
517                 !cast<MCAlignFragment>(it)->getValue()) &&
518                "Invalid align in virtual section!");
519         break;
520       case MCFragment::FT_Fill:
521         assert(!cast<MCFillFragment>(it)->getValueSize() &&
522                "Invalid fill in virtual section!");
523         break;
524       }
525     }
526
527     return;
528   }
529
530   uint64_t Start = getWriter().getStream().tell();
531   (void) Start;
532
533   for (MCSectionData::const_iterator it = SD->begin(),
534          ie = SD->end(); it != ie; ++it)
535     WriteFragmentData(*this, Layout, *it);
536
537   assert(getWriter().getStream().tell() - Start ==
538          Layout.getSectionAddressSize(SD));
539 }
540
541
542 uint64_t MCAssembler::handleFixup(const MCAsmLayout &Layout,
543                                   MCFragment &F,
544                                   const MCFixup &Fixup) {
545    // Evaluate the fixup.
546    MCValue Target;
547    uint64_t FixedValue;
548    if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
549      // The fixup was unresolved, we need a relocation. Inform the object
550      // writer of the relocation, and give it an opportunity to adjust the
551      // fixup value if need be.
552      getWriter().RecordRelocation(*this, Layout, &F, Fixup, Target, FixedValue);
553    }
554    return FixedValue;
555  }
556
557 void MCAssembler::Finish() {
558   DEBUG_WITH_TYPE("mc-dump", {
559       llvm::errs() << "assembler backend - pre-layout\n--\n";
560       dump(); });
561
562   // Create the layout object.
563   MCAsmLayout Layout(*this);
564
565   // Create dummy fragments and assign section ordinals.
566   unsigned SectionIndex = 0;
567   for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
568     // Create dummy fragments to eliminate any empty sections, this simplifies
569     // layout.
570     if (it->getFragmentList().empty())
571       new MCDataFragment(it);
572
573     it->setOrdinal(SectionIndex++);
574   }
575
576   // Assign layout order indices to sections and fragments.
577   for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
578     MCSectionData *SD = Layout.getSectionOrder()[i];
579     SD->setLayoutOrder(i);
580
581     unsigned FragmentIndex = 0;
582     for (MCSectionData::iterator it2 = SD->begin(),
583            ie2 = SD->end(); it2 != ie2; ++it2)
584       it2->setLayoutOrder(FragmentIndex++);
585   }
586
587   // Layout until everything fits.
588   while (layoutOnce(Layout))
589     continue;
590
591   DEBUG_WITH_TYPE("mc-dump", {
592       llvm::errs() << "assembler backend - post-relaxation\n--\n";
593       dump(); });
594
595   // Finalize the layout, including fragment lowering.
596   finishLayout(Layout);
597
598   DEBUG_WITH_TYPE("mc-dump", {
599       llvm::errs() << "assembler backend - final-layout\n--\n";
600       dump(); });
601
602   uint64_t StartOffset = OS.tell();
603
604   // Allow the object writer a chance to perform post-layout binding (for
605   // example, to set the index fields in the symbol data).
606   getWriter().ExecutePostLayoutBinding(*this, Layout);
607
608   // Evaluate and apply the fixups, generating relocation entries as necessary.
609   for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
610     for (MCSectionData::iterator it2 = it->begin(),
611            ie2 = it->end(); it2 != ie2; ++it2) {
612       MCDataFragment *DF = dyn_cast<MCDataFragment>(it2);
613       if (DF) {
614         for (MCDataFragment::fixup_iterator it3 = DF->fixup_begin(),
615                ie3 = DF->fixup_end(); it3 != ie3; ++it3) {
616           MCFixup &Fixup = *it3;
617           uint64_t FixedValue = handleFixup(Layout, *DF, Fixup);
618           getBackend().applyFixup(Fixup, DF->getContents().data(),
619                                   DF->getContents().size(), FixedValue);
620         }
621       }
622       MCInstFragment *IF = dyn_cast<MCInstFragment>(it2);
623       if (IF) {
624         for (MCInstFragment::fixup_iterator it3 = IF->fixup_begin(),
625                ie3 = IF->fixup_end(); it3 != ie3; ++it3) {
626           MCFixup &Fixup = *it3;
627           uint64_t FixedValue = handleFixup(Layout, *IF, Fixup);
628           getBackend().applyFixup(Fixup, IF->getCode().data(),
629                                   IF->getCode().size(), FixedValue);
630         }
631       }
632     }
633   }
634
635   // Write the object file.
636   getWriter().WriteObject(*this, Layout);
637
638   stats::ObjectBytes += OS.tell() - StartOffset;
639 }
640
641 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
642                                        const MCInstFragment *DF,
643                                        const MCAsmLayout &Layout) const {
644   if (getRelaxAll())
645     return true;
646
647   // If we cannot resolve the fixup value, it requires relaxation.
648   MCValue Target;
649   uint64_t Value;
650   if (!evaluateFixup(Layout, Fixup, DF, Target, Value))
651     return true;
652
653   return getBackend().fixupNeedsRelaxation(Fixup, Value, DF, Layout);
654 }
655
656 bool MCAssembler::fragmentNeedsRelaxation(const MCInstFragment *IF,
657                                           const MCAsmLayout &Layout) const {
658   // If this inst doesn't ever need relaxation, ignore it. This occurs when we
659   // are intentionally pushing out inst fragments, or because we relaxed a
660   // previous instruction to one that doesn't need relaxation.
661   if (!getBackend().mayNeedRelaxation(IF->getInst()))
662     return false;
663
664   for (MCInstFragment::const_fixup_iterator it = IF->fixup_begin(),
665          ie = IF->fixup_end(); it != ie; ++it)
666     if (fixupNeedsRelaxation(*it, IF, Layout))
667       return true;
668
669   return false;
670 }
671
672 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
673                                    MCInstFragment &IF) {
674   if (!fragmentNeedsRelaxation(&IF, Layout))
675     return false;
676
677   ++stats::RelaxedInstructions;
678
679   // FIXME-PERF: We could immediately lower out instructions if we can tell
680   // they are fully resolved, to avoid retesting on later passes.
681
682   // Relax the fragment.
683
684   MCInst Relaxed;
685   getBackend().relaxInstruction(IF.getInst(), Relaxed);
686
687   // Encode the new instruction.
688   //
689   // FIXME-PERF: If it matters, we could let the target do this. It can
690   // probably do so more efficiently in many cases.
691   SmallVector<MCFixup, 4> Fixups;
692   SmallString<256> Code;
693   raw_svector_ostream VecOS(Code);
694   getEmitter().EncodeInstruction(Relaxed, VecOS, Fixups);
695   VecOS.flush();
696
697   // Update the instruction fragment.
698   IF.setInst(Relaxed);
699   IF.getCode() = Code;
700   IF.getFixups().clear();
701   // FIXME: Eliminate copy.
702   for (unsigned i = 0, e = Fixups.size(); i != e; ++i)
703     IF.getFixups().push_back(Fixups[i]);
704
705   return true;
706 }
707
708 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
709   int64_t Value = 0;
710   uint64_t OldSize = LF.getContents().size();
711   bool IsAbs = LF.getValue().EvaluateAsAbsolute(Value, Layout);
712   (void)IsAbs;
713   assert(IsAbs);
714   SmallString<8> &Data = LF.getContents();
715   Data.clear();
716   raw_svector_ostream OSE(Data);
717   if (LF.isSigned())
718     MCObjectWriter::EncodeSLEB128(Value, OSE);
719   else
720     MCObjectWriter::EncodeULEB128(Value, OSE);
721   OSE.flush();
722   return OldSize != LF.getContents().size();
723 }
724
725 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
726                                      MCDwarfLineAddrFragment &DF) {
727   int64_t AddrDelta = 0;
728   uint64_t OldSize = DF.getContents().size();
729   bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
730   (void)IsAbs;
731   assert(IsAbs);
732   int64_t LineDelta;
733   LineDelta = DF.getLineDelta();
734   SmallString<8> &Data = DF.getContents();
735   Data.clear();
736   raw_svector_ostream OSE(Data);
737   MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OSE);
738   OSE.flush();
739   return OldSize != Data.size();
740 }
741
742 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
743                                               MCDwarfCallFrameFragment &DF) {
744   int64_t AddrDelta = 0;
745   uint64_t OldSize = DF.getContents().size();
746   bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
747   (void)IsAbs;
748   assert(IsAbs);
749   SmallString<8> &Data = DF.getContents();
750   Data.clear();
751   raw_svector_ostream OSE(Data);
752   MCDwarfFrameEmitter::EncodeAdvanceLoc(AddrDelta, OSE);
753   OSE.flush();
754   return OldSize != Data.size();
755 }
756
757 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout,
758                                     MCSectionData &SD) {
759   MCFragment *FirstInvalidFragment = NULL;
760   // Scan for fragments that need relaxation.
761   for (MCSectionData::iterator it2 = SD.begin(),
762          ie2 = SD.end(); it2 != ie2; ++it2) {
763     // Check if this is an fragment that needs relaxation.
764     bool relaxedFrag = false;
765     switch(it2->getKind()) {
766     default:
767           break;
768     case MCFragment::FT_Inst:
769       relaxedFrag = relaxInstruction(Layout, *cast<MCInstFragment>(it2));
770       break;
771     case MCFragment::FT_Dwarf:
772       relaxedFrag = relaxDwarfLineAddr(Layout,
773                                        *cast<MCDwarfLineAddrFragment>(it2));
774       break;
775     case MCFragment::FT_DwarfFrame:
776       relaxedFrag =
777         relaxDwarfCallFrameFragment(Layout,
778                                     *cast<MCDwarfCallFrameFragment>(it2));
779       break;
780     case MCFragment::FT_LEB:
781       relaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(it2));
782       break;
783     }
784     // Update the layout, and remember that we relaxed.
785     if (relaxedFrag && !FirstInvalidFragment)
786       FirstInvalidFragment = it2;
787   }
788   if (FirstInvalidFragment) {
789     Layout.Invalidate(FirstInvalidFragment);
790     return true;
791   }
792   return false;
793 }
794
795 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
796   ++stats::RelaxationSteps;
797
798   bool WasRelaxed = false;
799   for (iterator it = begin(), ie = end(); it != ie; ++it) {
800     MCSectionData &SD = *it;
801     while(layoutSectionOnce(Layout, SD))
802       WasRelaxed = true;
803   }
804
805   return WasRelaxed;
806 }
807
808 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
809   // The layout is done. Mark every fragment as valid.
810   for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
811     Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
812   }
813 }
814
815 // Debugging methods
816
817 namespace llvm {
818
819 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
820   OS << "<MCFixup" << " Offset:" << AF.getOffset()
821      << " Value:" << *AF.getValue()
822      << " Kind:" << AF.getKind() << ">";
823   return OS;
824 }
825
826 }
827
828 void MCFragment::dump() {
829   raw_ostream &OS = llvm::errs();
830
831   OS << "<";
832   switch (getKind()) {
833   case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
834   case MCFragment::FT_Data:  OS << "MCDataFragment"; break;
835   case MCFragment::FT_Fill:  OS << "MCFillFragment"; break;
836   case MCFragment::FT_Inst:  OS << "MCInstFragment"; break;
837   case MCFragment::FT_Org:   OS << "MCOrgFragment"; break;
838   case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
839   case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
840   case MCFragment::FT_LEB:   OS << "MCLEBFragment"; break;
841   }
842
843   OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
844      << " Offset:" << Offset << ">";
845
846   switch (getKind()) {
847   case MCFragment::FT_Align: {
848     const MCAlignFragment *AF = cast<MCAlignFragment>(this);
849     if (AF->hasEmitNops())
850       OS << " (emit nops)";
851     OS << "\n       ";
852     OS << " Alignment:" << AF->getAlignment()
853        << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
854        << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
855     break;
856   }
857   case MCFragment::FT_Data:  {
858     const MCDataFragment *DF = cast<MCDataFragment>(this);
859     OS << "\n       ";
860     OS << " Contents:[";
861     const SmallVectorImpl<char> &Contents = DF->getContents();
862     for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
863       if (i) OS << ",";
864       OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
865     }
866     OS << "] (" << Contents.size() << " bytes)";
867
868     if (!DF->getFixups().empty()) {
869       OS << ",\n       ";
870       OS << " Fixups:[";
871       for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
872              ie = DF->fixup_end(); it != ie; ++it) {
873         if (it != DF->fixup_begin()) OS << ",\n                ";
874         OS << *it;
875       }
876       OS << "]";
877     }
878     break;
879   }
880   case MCFragment::FT_Fill:  {
881     const MCFillFragment *FF = cast<MCFillFragment>(this);
882     OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
883        << " Size:" << FF->getSize();
884     break;
885   }
886   case MCFragment::FT_Inst:  {
887     const MCInstFragment *IF = cast<MCInstFragment>(this);
888     OS << "\n       ";
889     OS << " Inst:";
890     IF->getInst().dump_pretty(OS);
891     break;
892   }
893   case MCFragment::FT_Org:  {
894     const MCOrgFragment *OF = cast<MCOrgFragment>(this);
895     OS << "\n       ";
896     OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
897     break;
898   }
899   case MCFragment::FT_Dwarf:  {
900     const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
901     OS << "\n       ";
902     OS << " AddrDelta:" << OF->getAddrDelta()
903        << " LineDelta:" << OF->getLineDelta();
904     break;
905   }
906   case MCFragment::FT_DwarfFrame:  {
907     const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
908     OS << "\n       ";
909     OS << " AddrDelta:" << CF->getAddrDelta();
910     break;
911   }
912   case MCFragment::FT_LEB: {
913     const MCLEBFragment *LF = cast<MCLEBFragment>(this);
914     OS << "\n       ";
915     OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
916     break;
917   }
918   }
919   OS << ">";
920 }
921
922 void MCSectionData::dump() {
923   raw_ostream &OS = llvm::errs();
924
925   OS << "<MCSectionData";
926   OS << " Alignment:" << getAlignment() << " Fragments:[\n      ";
927   for (iterator it = begin(), ie = end(); it != ie; ++it) {
928     if (it != begin()) OS << ",\n      ";
929     it->dump();
930   }
931   OS << "]>";
932 }
933
934 void MCSymbolData::dump() {
935   raw_ostream &OS = llvm::errs();
936
937   OS << "<MCSymbolData Symbol:" << getSymbol()
938      << " Fragment:" << getFragment() << " Offset:" << getOffset()
939      << " Flags:" << getFlags() << " Index:" << getIndex();
940   if (isCommon())
941     OS << " (common, size:" << getCommonSize()
942        << " align: " << getCommonAlignment() << ")";
943   if (isExternal())
944     OS << " (external)";
945   if (isPrivateExtern())
946     OS << " (private extern)";
947   OS << ">";
948 }
949
950 void MCAssembler::dump() {
951   raw_ostream &OS = llvm::errs();
952
953   OS << "<MCAssembler\n";
954   OS << "  Sections:[\n    ";
955   for (iterator it = begin(), ie = end(); it != ie; ++it) {
956     if (it != begin()) OS << ",\n    ";
957     it->dump();
958   }
959   OS << "],\n";
960   OS << "  Symbols:[";
961
962   for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
963     if (it != symbol_begin()) OS << ",\n           ";
964     it->dump();
965   }
966   OS << "]>\n";
967 }
968
969 // anchors for MC*Fragment vtables
970 void MCDataFragment::anchor() { }
971 void MCInstFragment::anchor() { }
972 void MCAlignFragment::anchor() { }
973 void MCFillFragment::anchor() { }
974 void MCOrgFragment::anchor() { }
975 void MCLEBFragment::anchor() { }
976 void MCDwarfLineAddrFragment::anchor() { }
977 void MCDwarfCallFrameFragment::anchor() { }