This patch reworks how llvm targets set
[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   // Should NOP padding be written out before this fragment?
510   unsigned BundlePadding = F.getBundlePadding();
511   if (BundlePadding > 0) {
512     assert(Asm.isBundlingEnabled() &&
513            "Writing bundle padding with disabled bundling");
514     assert(F.hasInstructions() &&
515            "Writing bundle padding for a fragment without instructions");
516
517     if (!Asm.getBackend().writeNopData(BundlePadding, OW))
518       report_fatal_error("unable to write NOP sequence of " +
519                          Twine(BundlePadding) + " bytes");
520   }
521
522   // This variable (and its dummy usage) is to participate in the assert at
523   // the end of the function.
524   uint64_t Start = OW->getStream().tell();
525   (void) Start;
526
527   ++stats::EmittedFragments;
528
529   // FIXME: Embed in fragments instead?
530   uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
531   switch (F.getKind()) {
532   case MCFragment::FT_Align: {
533     ++stats::EmittedAlignFragments;
534     MCAlignFragment &AF = cast<MCAlignFragment>(F);
535     uint64_t Count = FragmentSize / AF.getValueSize();
536
537     assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
538
539     // FIXME: This error shouldn't actually occur (the front end should emit
540     // multiple .align directives to enforce the semantics it wants), but is
541     // severe enough that we want to report it. How to handle this?
542     if (Count * AF.getValueSize() != FragmentSize)
543       report_fatal_error("undefined .align directive, value size '" +
544                         Twine(AF.getValueSize()) +
545                         "' is not a divisor of padding size '" +
546                         Twine(FragmentSize) + "'");
547
548     // See if we are aligning with nops, and if so do that first to try to fill
549     // the Count bytes.  Then if that did not fill any bytes or there are any
550     // bytes left to fill use the Value and ValueSize to fill the rest.
551     // If we are aligning with nops, ask that target to emit the right data.
552     if (AF.hasEmitNops()) {
553       if (!Asm.getBackend().writeNopData(Count, OW))
554         report_fatal_error("unable to write nop sequence of " +
555                           Twine(Count) + " bytes");
556       break;
557     }
558
559     // Otherwise, write out in multiples of the value size.
560     for (uint64_t i = 0; i != Count; ++i) {
561       switch (AF.getValueSize()) {
562       default: llvm_unreachable("Invalid size!");
563       case 1: OW->Write8 (uint8_t (AF.getValue())); break;
564       case 2: OW->Write16(uint16_t(AF.getValue())); break;
565       case 4: OW->Write32(uint32_t(AF.getValue())); break;
566       case 8: OW->Write64(uint64_t(AF.getValue())); break;
567       }
568     }
569     break;
570   }
571
572   case MCFragment::FT_Data: 
573     ++stats::EmittedDataFragments;
574     writeFragmentContents(F, OW);
575     break;
576
577   case MCFragment::FT_Relaxable:
578     ++stats::EmittedRelaxableFragments;
579     writeFragmentContents(F, OW);
580     break;
581
582   case MCFragment::FT_CompactEncodedInst:
583     ++stats::EmittedCompactEncodedInstFragments;
584     writeFragmentContents(F, OW);
585     break;
586
587   case MCFragment::FT_Fill: {
588     ++stats::EmittedFillFragments;
589     MCFillFragment &FF = cast<MCFillFragment>(F);
590
591     assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
592
593     for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
594       switch (FF.getValueSize()) {
595       default: llvm_unreachable("Invalid size!");
596       case 1: OW->Write8 (uint8_t (FF.getValue())); break;
597       case 2: OW->Write16(uint16_t(FF.getValue())); break;
598       case 4: OW->Write32(uint32_t(FF.getValue())); break;
599       case 8: OW->Write64(uint64_t(FF.getValue())); break;
600       }
601     }
602     break;
603   }
604
605   case MCFragment::FT_LEB: {
606     MCLEBFragment &LF = cast<MCLEBFragment>(F);
607     OW->WriteBytes(LF.getContents().str());
608     break;
609   }
610
611   case MCFragment::FT_Org: {
612     ++stats::EmittedOrgFragments;
613     MCOrgFragment &OF = cast<MCOrgFragment>(F);
614
615     for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
616       OW->Write8(uint8_t(OF.getValue()));
617
618     break;
619   }
620
621   case MCFragment::FT_Dwarf: {
622     const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
623     OW->WriteBytes(OF.getContents().str());
624     break;
625   }
626   case MCFragment::FT_DwarfFrame: {
627     const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
628     OW->WriteBytes(CF.getContents().str());
629     break;
630   }
631   }
632
633   assert(OW->getStream().tell() - Start == FragmentSize &&
634          "The stream should advance by fragment size");
635 }
636
637 void MCAssembler::writeSectionData(const MCSectionData *SD,
638                                    const MCAsmLayout &Layout) const {
639   // Ignore virtual sections.
640   if (SD->getSection().isVirtualSection()) {
641     assert(Layout.getSectionFileSize(SD) == 0 && "Invalid size for section!");
642
643     // Check that contents are only things legal inside a virtual section.
644     for (MCSectionData::const_iterator it = SD->begin(),
645            ie = SD->end(); it != ie; ++it) {
646       switch (it->getKind()) {
647       default: llvm_unreachable("Invalid fragment in virtual section!");
648       case MCFragment::FT_Data: {
649         // Check that we aren't trying to write a non-zero contents (or fixups)
650         // into a virtual section. This is to support clients which use standard
651         // directives to fill the contents of virtual sections.
652         MCDataFragment &DF = cast<MCDataFragment>(*it);
653         assert(DF.fixup_begin() == DF.fixup_end() &&
654                "Cannot have fixups in virtual section!");
655         for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
656           assert(DF.getContents()[i] == 0 &&
657                  "Invalid data value for virtual section!");
658         break;
659       }
660       case MCFragment::FT_Align:
661         // Check that we aren't trying to write a non-zero value into a virtual
662         // section.
663         assert((!cast<MCAlignFragment>(it)->getValueSize() ||
664                 !cast<MCAlignFragment>(it)->getValue()) &&
665                "Invalid align in virtual section!");
666         break;
667       case MCFragment::FT_Fill:
668         assert(!cast<MCFillFragment>(it)->getValueSize() &&
669                "Invalid fill in virtual section!");
670         break;
671       }
672     }
673
674     return;
675   }
676
677   uint64_t Start = getWriter().getStream().tell();
678   (void)Start;
679
680   for (MCSectionData::const_iterator it = SD->begin(), ie = SD->end();
681        it != ie; ++it)
682     writeFragment(*this, Layout, *it);
683
684   assert(getWriter().getStream().tell() - Start ==
685          Layout.getSectionAddressSize(SD));
686 }
687
688
689 uint64_t MCAssembler::handleFixup(const MCAsmLayout &Layout,
690                                   MCFragment &F,
691                                   const MCFixup &Fixup) {
692    // Evaluate the fixup.
693    MCValue Target;
694    uint64_t FixedValue;
695    if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
696      // The fixup was unresolved, we need a relocation. Inform the object
697      // writer of the relocation, and give it an opportunity to adjust the
698      // fixup value if need be.
699      getWriter().RecordRelocation(*this, Layout, &F, Fixup, Target, FixedValue);
700    }
701    return FixedValue;
702  }
703
704 void MCAssembler::Finish() {
705   DEBUG_WITH_TYPE("mc-dump", {
706       llvm::errs() << "assembler backend - pre-layout\n--\n";
707       dump(); });
708
709   // Create the layout object.
710   MCAsmLayout Layout(*this);
711
712   // Create dummy fragments and assign section ordinals.
713   unsigned SectionIndex = 0;
714   for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
715     // Create dummy fragments to eliminate any empty sections, this simplifies
716     // layout.
717     if (it->getFragmentList().empty())
718       new MCDataFragment(it);
719
720     it->setOrdinal(SectionIndex++);
721   }
722
723   // Assign layout order indices to sections and fragments.
724   for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
725     MCSectionData *SD = Layout.getSectionOrder()[i];
726     SD->setLayoutOrder(i);
727
728     unsigned FragmentIndex = 0;
729     for (MCSectionData::iterator iFrag = SD->begin(), iFragEnd = SD->end();
730          iFrag != iFragEnd; ++iFrag)
731       iFrag->setLayoutOrder(FragmentIndex++);
732   }
733
734   // Layout until everything fits.
735   while (layoutOnce(Layout))
736     continue;
737
738   DEBUG_WITH_TYPE("mc-dump", {
739       llvm::errs() << "assembler backend - post-relaxation\n--\n";
740       dump(); });
741
742   // Finalize the layout, including fragment lowering.
743   finishLayout(Layout);
744
745   DEBUG_WITH_TYPE("mc-dump", {
746       llvm::errs() << "assembler backend - final-layout\n--\n";
747       dump(); });
748
749   uint64_t StartOffset = OS.tell();
750
751   // Allow the object writer a chance to perform post-layout binding (for
752   // example, to set the index fields in the symbol data).
753   getWriter().ExecutePostLayoutBinding(*this, Layout);
754
755   // Evaluate and apply the fixups, generating relocation entries as necessary.
756   for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
757     for (MCSectionData::iterator it2 = it->begin(),
758            ie2 = it->end(); it2 != ie2; ++it2) {
759       MCEncodedFragmentWithFixups *F =
760         dyn_cast<MCEncodedFragmentWithFixups>(it2);
761       if (F) {
762         for (MCEncodedFragmentWithFixups::fixup_iterator it3 = F->fixup_begin(),
763              ie3 = F->fixup_end(); it3 != ie3; ++it3) {
764           MCFixup &Fixup = *it3;
765           uint64_t FixedValue = handleFixup(Layout, *F, Fixup);
766           getBackend().applyFixup(Fixup, F->getContents().data(),
767                                   F->getContents().size(), FixedValue);
768         }
769       }
770     }
771   }
772
773   // Write the object file.
774   getWriter().WriteObject(*this, Layout);
775
776   stats::ObjectBytes += OS.tell() - StartOffset;
777 }
778
779 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
780                                        const MCRelaxableFragment *DF,
781                                        const MCAsmLayout &Layout) const {
782   // If we cannot resolve the fixup value, it requires relaxation.
783   MCValue Target;
784   uint64_t Value;
785   if (!evaluateFixup(Layout, Fixup, DF, Target, Value))
786     return true;
787
788   return getBackend().fixupNeedsRelaxation(Fixup, Value, DF, Layout);
789 }
790
791 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
792                                           const MCAsmLayout &Layout) const {
793   // If this inst doesn't ever need relaxation, ignore it. This occurs when we
794   // are intentionally pushing out inst fragments, or because we relaxed a
795   // previous instruction to one that doesn't need relaxation.
796   if (!getBackend().mayNeedRelaxation(F->getInst()))
797     return false;
798
799   for (MCRelaxableFragment::const_fixup_iterator it = F->fixup_begin(),
800        ie = F->fixup_end(); it != ie; ++it)
801     if (fixupNeedsRelaxation(*it, F, Layout))
802       return true;
803
804   return false;
805 }
806
807 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
808                                    MCRelaxableFragment &F) {
809   if (!fragmentNeedsRelaxation(&F, Layout))
810     return false;
811
812   ++stats::RelaxedInstructions;
813
814   // FIXME-PERF: We could immediately lower out instructions if we can tell
815   // they are fully resolved, to avoid retesting on later passes.
816
817   // Relax the fragment.
818
819   MCInst Relaxed;
820   getBackend().relaxInstruction(F.getInst(), Relaxed);
821
822   // Encode the new instruction.
823   //
824   // FIXME-PERF: If it matters, we could let the target do this. It can
825   // probably do so more efficiently in many cases.
826   SmallVector<MCFixup, 4> Fixups;
827   SmallString<256> Code;
828   raw_svector_ostream VecOS(Code);
829   getEmitter().EncodeInstruction(Relaxed, VecOS, Fixups);
830   VecOS.flush();
831
832   // Update the fragment.
833   F.setInst(Relaxed);
834   F.getContents() = Code;
835   F.getFixups() = Fixups;
836
837   return true;
838 }
839
840 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
841   int64_t Value = 0;
842   uint64_t OldSize = LF.getContents().size();
843   bool IsAbs = LF.getValue().EvaluateAsAbsolute(Value, Layout);
844   (void)IsAbs;
845   assert(IsAbs);
846   SmallString<8> &Data = LF.getContents();
847   Data.clear();
848   raw_svector_ostream OSE(Data);
849   if (LF.isSigned())
850     encodeSLEB128(Value, OSE);
851   else
852     encodeULEB128(Value, OSE);
853   OSE.flush();
854   return OldSize != LF.getContents().size();
855 }
856
857 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
858                                      MCDwarfLineAddrFragment &DF) {
859   int64_t AddrDelta = 0;
860   uint64_t OldSize = DF.getContents().size();
861   bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
862   (void)IsAbs;
863   assert(IsAbs);
864   int64_t LineDelta;
865   LineDelta = DF.getLineDelta();
866   SmallString<8> &Data = DF.getContents();
867   Data.clear();
868   raw_svector_ostream OSE(Data);
869   MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OSE);
870   OSE.flush();
871   return OldSize != Data.size();
872 }
873
874 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
875                                               MCDwarfCallFrameFragment &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   SmallString<8> &Data = DF.getContents();
882   Data.clear();
883   raw_svector_ostream OSE(Data);
884   MCDwarfFrameEmitter::EncodeAdvanceLoc(AddrDelta, OSE);
885   OSE.flush();
886   return OldSize != Data.size();
887 }
888
889 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSectionData &SD) {
890   // Holds the first fragment which needed relaxing during this layout. It will
891   // remain NULL if none were relaxed.
892   // When a fragment is relaxed, all the fragments following it should get
893   // invalidated because their offset is going to change.
894   MCFragment *FirstRelaxedFragment = NULL;
895
896   // Attempt to relax all the fragments in the section.
897   for (MCSectionData::iterator I = SD.begin(), IE = SD.end(); I != IE; ++I) {
898     // Check if this is a fragment that needs relaxation.
899     bool RelaxedFrag = false;
900     switch(I->getKind()) {
901     default:
902       break;
903     case MCFragment::FT_Relaxable:
904       assert(!getRelaxAll() &&
905              "Did not expect a MCRelaxableFragment in RelaxAll mode");
906       RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
907       break;
908     case MCFragment::FT_Dwarf:
909       RelaxedFrag = relaxDwarfLineAddr(Layout,
910                                        *cast<MCDwarfLineAddrFragment>(I));
911       break;
912     case MCFragment::FT_DwarfFrame:
913       RelaxedFrag =
914         relaxDwarfCallFrameFragment(Layout,
915                                     *cast<MCDwarfCallFrameFragment>(I));
916       break;
917     case MCFragment::FT_LEB:
918       RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
919       break;
920     }
921     if (RelaxedFrag && !FirstRelaxedFragment)
922       FirstRelaxedFragment = I;
923   }
924   if (FirstRelaxedFragment) {
925     Layout.invalidateFragmentsAfter(FirstRelaxedFragment);
926     return true;
927   }
928   return false;
929 }
930
931 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
932   ++stats::RelaxationSteps;
933
934   bool WasRelaxed = false;
935   for (iterator it = begin(), ie = end(); it != ie; ++it) {
936     MCSectionData &SD = *it;
937     while (layoutSectionOnce(Layout, SD))
938       WasRelaxed = true;
939   }
940
941   return WasRelaxed;
942 }
943
944 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
945   // The layout is done. Mark every fragment as valid.
946   for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
947     Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
948   }
949 }
950
951 // Debugging methods
952
953 namespace llvm {
954
955 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
956   OS << "<MCFixup" << " Offset:" << AF.getOffset()
957      << " Value:" << *AF.getValue()
958      << " Kind:" << AF.getKind() << ">";
959   return OS;
960 }
961
962 }
963
964 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
965 void MCFragment::dump() {
966   raw_ostream &OS = llvm::errs();
967
968   OS << "<";
969   switch (getKind()) {
970   case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
971   case MCFragment::FT_Data:  OS << "MCDataFragment"; break;
972   case MCFragment::FT_CompactEncodedInst:
973     OS << "MCCompactEncodedInstFragment"; break;
974   case MCFragment::FT_Fill:  OS << "MCFillFragment"; break;
975   case MCFragment::FT_Relaxable:  OS << "MCRelaxableFragment"; break;
976   case MCFragment::FT_Org:   OS << "MCOrgFragment"; break;
977   case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
978   case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
979   case MCFragment::FT_LEB:   OS << "MCLEBFragment"; break;
980   }
981
982   OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
983      << " Offset:" << Offset
984      << " HasInstructions:" << hasInstructions() 
985      << " BundlePadding:" << getBundlePadding() << ">";
986
987   switch (getKind()) {
988   case MCFragment::FT_Align: {
989     const MCAlignFragment *AF = cast<MCAlignFragment>(this);
990     if (AF->hasEmitNops())
991       OS << " (emit nops)";
992     OS << "\n       ";
993     OS << " Alignment:" << AF->getAlignment()
994        << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
995        << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
996     break;
997   }
998   case MCFragment::FT_Data:  {
999     const MCDataFragment *DF = cast<MCDataFragment>(this);
1000     OS << "\n       ";
1001     OS << " Contents:[";
1002     const SmallVectorImpl<char> &Contents = DF->getContents();
1003     for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1004       if (i) OS << ",";
1005       OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1006     }
1007     OS << "] (" << Contents.size() << " bytes)";
1008
1009     if (DF->fixup_begin() != DF->fixup_end()) {
1010       OS << ",\n       ";
1011       OS << " Fixups:[";
1012       for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
1013              ie = DF->fixup_end(); it != ie; ++it) {
1014         if (it != DF->fixup_begin()) OS << ",\n                ";
1015         OS << *it;
1016       }
1017       OS << "]";
1018     }
1019     break;
1020   }
1021   case MCFragment::FT_CompactEncodedInst: {
1022     const MCCompactEncodedInstFragment *CEIF =
1023       cast<MCCompactEncodedInstFragment>(this);
1024     OS << "\n       ";
1025     OS << " Contents:[";
1026     const SmallVectorImpl<char> &Contents = CEIF->getContents();
1027     for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1028       if (i) OS << ",";
1029       OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1030     }
1031     OS << "] (" << Contents.size() << " bytes)";
1032     break;
1033   }
1034   case MCFragment::FT_Fill:  {
1035     const MCFillFragment *FF = cast<MCFillFragment>(this);
1036     OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
1037        << " Size:" << FF->getSize();
1038     break;
1039   }
1040   case MCFragment::FT_Relaxable:  {
1041     const MCRelaxableFragment *F = cast<MCRelaxableFragment>(this);
1042     OS << "\n       ";
1043     OS << " Inst:";
1044     F->getInst().dump_pretty(OS);
1045     break;
1046   }
1047   case MCFragment::FT_Org:  {
1048     const MCOrgFragment *OF = cast<MCOrgFragment>(this);
1049     OS << "\n       ";
1050     OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
1051     break;
1052   }
1053   case MCFragment::FT_Dwarf:  {
1054     const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
1055     OS << "\n       ";
1056     OS << " AddrDelta:" << OF->getAddrDelta()
1057        << " LineDelta:" << OF->getLineDelta();
1058     break;
1059   }
1060   case MCFragment::FT_DwarfFrame:  {
1061     const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
1062     OS << "\n       ";
1063     OS << " AddrDelta:" << CF->getAddrDelta();
1064     break;
1065   }
1066   case MCFragment::FT_LEB: {
1067     const MCLEBFragment *LF = cast<MCLEBFragment>(this);
1068     OS << "\n       ";
1069     OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
1070     break;
1071   }
1072   }
1073   OS << ">";
1074 }
1075
1076 void MCSectionData::dump() {
1077   raw_ostream &OS = llvm::errs();
1078
1079   OS << "<MCSectionData";
1080   OS << " Alignment:" << getAlignment()
1081      << " Fragments:[\n      ";
1082   for (iterator it = begin(), ie = end(); it != ie; ++it) {
1083     if (it != begin()) OS << ",\n      ";
1084     it->dump();
1085   }
1086   OS << "]>";
1087 }
1088
1089 void MCSymbolData::dump() {
1090   raw_ostream &OS = llvm::errs();
1091
1092   OS << "<MCSymbolData Symbol:" << getSymbol()
1093      << " Fragment:" << getFragment() << " Offset:" << getOffset()
1094      << " Flags:" << getFlags() << " Index:" << getIndex();
1095   if (isCommon())
1096     OS << " (common, size:" << getCommonSize()
1097        << " align: " << getCommonAlignment() << ")";
1098   if (isExternal())
1099     OS << " (external)";
1100   if (isPrivateExtern())
1101     OS << " (private extern)";
1102   OS << ">";
1103 }
1104
1105 void MCAssembler::dump() {
1106   raw_ostream &OS = llvm::errs();
1107
1108   OS << "<MCAssembler\n";
1109   OS << "  Sections:[\n    ";
1110   for (iterator it = begin(), ie = end(); it != ie; ++it) {
1111     if (it != begin()) OS << ",\n    ";
1112     it->dump();
1113   }
1114   OS << "],\n";
1115   OS << "  Symbols:[";
1116
1117   for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1118     if (it != symbol_begin()) OS << ",\n           ";
1119     it->dump();
1120   }
1121   OS << "]>\n";
1122 }
1123 #endif
1124
1125 // anchors for MC*Fragment vtables
1126 void MCEncodedFragment::anchor() { }
1127 void MCEncodedFragmentWithFixups::anchor() { }
1128 void MCDataFragment::anchor() { }
1129 void MCCompactEncodedInstFragment::anchor() { }
1130 void MCRelaxableFragment::anchor() { }
1131 void MCAlignFragment::anchor() { }
1132 void MCFillFragment::anchor() { }
1133 void MCOrgFragment::anchor() { }
1134 void MCLEBFragment::anchor() { }
1135 void MCDwarfLineAddrFragment::anchor() { }
1136 void MCDwarfCallFrameFragment::anchor() { }
1137