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