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