No relocation produces a SLEB or ULEB, make sure they are handled in MC.
[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   bool IsAbs = LF.getValue().EvaluateAsAbsolute(Value, Layout);
695   (void)IsAbs;
696   assert(IsAbs);
697   SmallString<8> &Data = LF.getContents();
698   Data.clear();
699   raw_svector_ostream OSE(Data);
700   if (LF.isSigned())
701     MCObjectWriter::EncodeSLEB128(Value, OSE);
702   else
703     MCObjectWriter::EncodeULEB128(Value, OSE);
704   OSE.flush();
705   return OldSize != LF.getContents().size();
706 }
707
708 bool MCAssembler::RelaxDwarfLineAddr(MCAsmLayout &Layout,
709                                      MCDwarfLineAddrFragment &DF) {
710   int64_t AddrDelta = 0;
711   uint64_t OldSize = DF.getContents().size();
712   bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
713   (void)IsAbs;
714   assert(IsAbs);
715   int64_t LineDelta;
716   LineDelta = DF.getLineDelta();
717   SmallString<8> &Data = DF.getContents();
718   Data.clear();
719   raw_svector_ostream OSE(Data);
720   MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OSE);
721   OSE.flush();
722   return OldSize != Data.size();
723 }
724
725 bool MCAssembler::RelaxDwarfCallFrameFragment(MCAsmLayout &Layout,
726                                               MCDwarfCallFrameFragment &DF) {
727   int64_t AddrDelta = 0;
728   uint64_t OldSize = DF.getContents().size();
729   bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
730   (void)IsAbs;
731   assert(IsAbs);
732   SmallString<8> &Data = DF.getContents();
733   Data.clear();
734   raw_svector_ostream OSE(Data);
735   MCDwarfFrameEmitter::EncodeAdvanceLoc(AddrDelta, OSE);
736   OSE.flush();
737   return OldSize != Data.size();
738 }
739
740 bool MCAssembler::LayoutSectionOnce(MCAsmLayout &Layout,
741                                     MCSectionData &SD) {
742   MCFragment *FirstInvalidFragment = NULL;
743   // Scan for fragments that need relaxation.
744   for (MCSectionData::iterator it2 = SD.begin(),
745          ie2 = SD.end(); it2 != ie2; ++it2) {
746     // Check if this is an fragment that needs relaxation.
747     bool relaxedFrag = false;
748     switch(it2->getKind()) {
749     default:
750           break;
751     case MCFragment::FT_Inst:
752       relaxedFrag = RelaxInstruction(Layout, *cast<MCInstFragment>(it2));
753       break;
754     case MCFragment::FT_Dwarf:
755       relaxedFrag = RelaxDwarfLineAddr(Layout,
756                                        *cast<MCDwarfLineAddrFragment>(it2));
757       break;
758     case MCFragment::FT_DwarfFrame:
759       relaxedFrag =
760         RelaxDwarfCallFrameFragment(Layout,
761                                     *cast<MCDwarfCallFrameFragment>(it2));
762       break;
763     case MCFragment::FT_LEB:
764       relaxedFrag = RelaxLEB(Layout, *cast<MCLEBFragment>(it2));
765       break;
766     }
767     // Update the layout, and remember that we relaxed.
768     if (relaxedFrag && !FirstInvalidFragment)
769       FirstInvalidFragment = it2;
770   }
771   if (FirstInvalidFragment) {
772     Layout.Invalidate(FirstInvalidFragment);
773     return true;
774   }
775   return false;
776 }
777
778 bool MCAssembler::LayoutOnce(MCAsmLayout &Layout) {
779   ++stats::RelaxationSteps;
780
781   bool WasRelaxed = false;
782   for (iterator it = begin(), ie = end(); it != ie; ++it) {
783     MCSectionData &SD = *it;
784     while(LayoutSectionOnce(Layout, SD))
785       WasRelaxed = true;
786   }
787
788   return WasRelaxed;
789 }
790
791 void MCAssembler::FinishLayout(MCAsmLayout &Layout) {
792   // The layout is done. Mark every fragment as valid.
793   for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
794     Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
795   }
796 }
797
798 // Debugging methods
799
800 namespace llvm {
801
802 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
803   OS << "<MCFixup" << " Offset:" << AF.getOffset()
804      << " Value:" << *AF.getValue()
805      << " Kind:" << AF.getKind() << ">";
806   return OS;
807 }
808
809 }
810
811 void MCFragment::dump() {
812   raw_ostream &OS = llvm::errs();
813
814   OS << "<";
815   switch (getKind()) {
816   case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
817   case MCFragment::FT_Data:  OS << "MCDataFragment"; break;
818   case MCFragment::FT_Fill:  OS << "MCFillFragment"; break;
819   case MCFragment::FT_Inst:  OS << "MCInstFragment"; break;
820   case MCFragment::FT_Org:   OS << "MCOrgFragment"; break;
821   case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
822   case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
823   case MCFragment::FT_LEB:   OS << "MCLEBFragment"; break;
824   }
825
826   OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
827      << " Offset:" << Offset << ">";
828
829   switch (getKind()) {
830   case MCFragment::FT_Align: {
831     const MCAlignFragment *AF = cast<MCAlignFragment>(this);
832     if (AF->hasEmitNops())
833       OS << " (emit nops)";
834     OS << "\n       ";
835     OS << " Alignment:" << AF->getAlignment()
836        << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
837        << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
838     break;
839   }
840   case MCFragment::FT_Data:  {
841     const MCDataFragment *DF = cast<MCDataFragment>(this);
842     OS << "\n       ";
843     OS << " Contents:[";
844     const SmallVectorImpl<char> &Contents = DF->getContents();
845     for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
846       if (i) OS << ",";
847       OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
848     }
849     OS << "] (" << Contents.size() << " bytes)";
850
851     if (!DF->getFixups().empty()) {
852       OS << ",\n       ";
853       OS << " Fixups:[";
854       for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
855              ie = DF->fixup_end(); it != ie; ++it) {
856         if (it != DF->fixup_begin()) OS << ",\n                ";
857         OS << *it;
858       }
859       OS << "]";
860     }
861     break;
862   }
863   case MCFragment::FT_Fill:  {
864     const MCFillFragment *FF = cast<MCFillFragment>(this);
865     OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
866        << " Size:" << FF->getSize();
867     break;
868   }
869   case MCFragment::FT_Inst:  {
870     const MCInstFragment *IF = cast<MCInstFragment>(this);
871     OS << "\n       ";
872     OS << " Inst:";
873     IF->getInst().dump_pretty(OS);
874     break;
875   }
876   case MCFragment::FT_Org:  {
877     const MCOrgFragment *OF = cast<MCOrgFragment>(this);
878     OS << "\n       ";
879     OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
880     break;
881   }
882   case MCFragment::FT_Dwarf:  {
883     const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
884     OS << "\n       ";
885     OS << " AddrDelta:" << OF->getAddrDelta()
886        << " LineDelta:" << OF->getLineDelta();
887     break;
888   }
889   case MCFragment::FT_DwarfFrame:  {
890     const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
891     OS << "\n       ";
892     OS << " AddrDelta:" << CF->getAddrDelta();
893     break;
894   }
895   case MCFragment::FT_LEB: {
896     const MCLEBFragment *LF = cast<MCLEBFragment>(this);
897     OS << "\n       ";
898     OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
899     break;
900   }
901   }
902   OS << ">";
903 }
904
905 void MCSectionData::dump() {
906   raw_ostream &OS = llvm::errs();
907
908   OS << "<MCSectionData";
909   OS << " Alignment:" << getAlignment() << " Fragments:[\n      ";
910   for (iterator it = begin(), ie = end(); it != ie; ++it) {
911     if (it != begin()) OS << ",\n      ";
912     it->dump();
913   }
914   OS << "]>";
915 }
916
917 void MCSymbolData::dump() {
918   raw_ostream &OS = llvm::errs();
919
920   OS << "<MCSymbolData Symbol:" << getSymbol()
921      << " Fragment:" << getFragment() << " Offset:" << getOffset()
922      << " Flags:" << getFlags() << " Index:" << getIndex();
923   if (isCommon())
924     OS << " (common, size:" << getCommonSize()
925        << " align: " << getCommonAlignment() << ")";
926   if (isExternal())
927     OS << " (external)";
928   if (isPrivateExtern())
929     OS << " (private extern)";
930   OS << ">";
931 }
932
933 void MCAssembler::dump() {
934   raw_ostream &OS = llvm::errs();
935
936   OS << "<MCAssembler\n";
937   OS << "  Sections:[\n    ";
938   for (iterator it = begin(), ie = end(); it != ie; ++it) {
939     if (it != begin()) OS << ",\n    ";
940     it->dump();
941   }
942   OS << "],\n";
943   OS << "  Symbols:[";
944
945   for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
946     if (it != symbol_begin()) OS << ",\n           ";
947     it->dump();
948   }
949   OS << "]>\n";
950 }