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