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