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