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