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