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