MC: Fix a few more cases we were passing an MCDataFragment when a MCFragment would...
[oota-llvm.git] / lib / MC / MCAssembler.cpp
1 //===- lib/MC/MCAssembler.cpp - Assembler Backend Implementation ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #define DEBUG_TYPE "assembler"
11 #include "llvm/MC/MCAssembler.h"
12 #include "llvm/MC/MCAsmLayout.h"
13 #include "llvm/MC/MCCodeEmitter.h"
14 #include "llvm/MC/MCExpr.h"
15 #include "llvm/MC/MCObjectWriter.h"
16 #include "llvm/MC/MCSymbol.h"
17 #include "llvm/MC/MCValue.h"
18 #include "llvm/ADT/OwningPtr.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Target/TargetRegistry.h"
26 #include "llvm/Target/TargetAsmBackend.h"
27
28 // FIXME: Gross.
29 #include "../Target/X86/X86FixupKinds.h"
30
31 #include <vector>
32 using namespace llvm;
33
34 STATISTIC(EmittedFragments, "Number of emitted assembler fragments");
35
36 // FIXME FIXME FIXME: There are number of places in this file where we convert
37 // what is a 64-bit assembler value used for computation into a value in the
38 // object file, which may truncate it. We should detect that truncation where
39 // invalid and report errors back.
40
41 /* *** */
42
43 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
44 }
45
46 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
47   : Kind(_Kind),
48     Parent(_Parent),
49     FileSize(~UINT64_C(0))
50 {
51   if (Parent)
52     Parent->getFragmentList().push_back(this);
53 }
54
55 MCFragment::~MCFragment() {
56 }
57
58 uint64_t MCFragment::getAddress() const {
59   assert(getParent() && "Missing Section!");
60   return getParent()->getAddress() + Offset;
61 }
62
63 /* *** */
64
65 MCSectionData::MCSectionData() : Section(0) {}
66
67 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
68   : Section(&_Section),
69     Alignment(1),
70     Address(~UINT64_C(0)),
71     Size(~UINT64_C(0)),
72     FileSize(~UINT64_C(0)),
73     HasInstructions(false)
74 {
75   if (A)
76     A->getSectionList().push_back(this);
77 }
78
79 /* *** */
80
81 MCSymbolData::MCSymbolData() : Symbol(0) {}
82
83 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
84                            uint64_t _Offset, MCAssembler *A)
85   : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
86     IsExternal(false), IsPrivateExtern(false),
87     CommonSize(0), CommonAlign(0), Flags(0), Index(0)
88 {
89   if (A)
90     A->getSymbolList().push_back(this);
91 }
92
93 /* *** */
94
95 MCAssembler::MCAssembler(MCContext &_Context, TargetAsmBackend &_Backend,
96                          MCCodeEmitter &_Emitter, raw_ostream &_OS)
97   : Context(_Context), Backend(_Backend), Emitter(_Emitter),
98     OS(_OS), SubsectionsViaSymbols(false)
99 {
100 }
101
102 MCAssembler::~MCAssembler() {
103 }
104
105 static bool isScatteredFixupFullyResolvedSimple(const MCAssembler &Asm,
106                                                 const MCAsmFixup &Fixup,
107                                                 const MCValue Target,
108                                                 const MCSection *BaseSection) {
109   // The effective fixup address is
110   //     addr(atom(A)) + offset(A)
111   //   - addr(atom(B)) - offset(B)
112   //   - addr(<base symbol>) + <fixup offset from base symbol>
113   // and the offsets are not relocatable, so the fixup is fully resolved when
114   //  addr(atom(A)) - addr(atom(B)) - addr(<base symbol>)) == 0.
115   //
116   // The simple (Darwin, except on x86_64) way of dealing with this was to
117   // assume that any reference to a temporary symbol *must* be a temporary
118   // symbol in the same atom, unless the sections differ. Therefore, any PCrel
119   // relocation to a temporary symbol (in the same section) is fully
120   // resolved. This also works in conjunction with absolutized .set, which
121   // requires the compiler to use .set to absolutize the differences between
122   // symbols which the compiler knows to be assembly time constants, so we don't
123   // need to worry about consider symbol differences fully resolved.
124
125   // Non-relative fixups are only resolved if constant.
126   if (!BaseSection)
127     return Target.isAbsolute();
128
129   // Otherwise, relative fixups are only resolved if not a difference and the
130   // target is a temporary in the same section.
131   if (Target.isAbsolute() || Target.getSymB())
132     return false;
133
134   const MCSymbol *A = &Target.getSymA()->getSymbol();
135   if (!A->isTemporary() || !A->isInSection() ||
136       &A->getSection() != BaseSection)
137     return false;
138
139   return true;
140 }
141
142 static bool isScatteredFixupFullyResolved(const MCAssembler &Asm,
143                                           const MCAsmFixup &Fixup,
144                                           const MCValue Target,
145                                           const MCSymbolData *BaseSymbol) {
146   // The effective fixup address is
147   //     addr(atom(A)) + offset(A)
148   //   - addr(atom(B)) - offset(B)
149   //   - addr(BaseSymbol) + <fixup offset from base symbol>
150   // and the offsets are not relocatable, so the fixup is fully resolved when
151   //  addr(atom(A)) - addr(atom(B)) - addr(BaseSymbol) == 0.
152   //
153   // Note that "false" is almost always conservatively correct (it means we emit
154   // a relocation which is unnecessary), except when it would force us to emit a
155   // relocation which the target cannot encode.
156
157   const MCSymbolData *A_Base = 0, *B_Base = 0;
158   if (const MCSymbolRefExpr *A = Target.getSymA()) {
159     // Modified symbol references cannot be resolved.
160     if (A->getKind() != MCSymbolRefExpr::VK_None)
161       return false;
162
163     A_Base = Asm.getAtom(&Asm.getSymbolData(A->getSymbol()));
164     if (!A_Base)
165       return false;
166   }
167
168   if (const MCSymbolRefExpr *B = Target.getSymB()) {
169     // Modified symbol references cannot be resolved.
170     if (B->getKind() != MCSymbolRefExpr::VK_None)
171       return false;
172
173     B_Base = Asm.getAtom(&Asm.getSymbolData(B->getSymbol()));
174     if (!B_Base)
175       return false;
176   }
177
178   // If there is no base, A and B have to be the same atom for this fixup to be
179   // fully resolved.
180   if (!BaseSymbol)
181     return A_Base == B_Base;
182
183   // Otherwise, B must be missing and A must be the base.
184   return !B_Base && BaseSymbol == A_Base;
185 }
186
187 bool MCAssembler::isSymbolLinkerVisible(const MCSymbolData *SD) const {
188   // Non-temporary labels should always be visible to the linker.
189   if (!SD->getSymbol().isTemporary())
190     return true;
191
192   // Absolute temporary labels are never visible.
193   if (!SD->getFragment())
194     return false;
195
196   // Otherwise, check if the section requires symbols even for temporary labels.
197   return getBackend().doesSectionRequireSymbols(
198     SD->getFragment()->getParent()->getSection());
199 }
200
201 const MCSymbolData *MCAssembler::getAtomForAddress(const MCSectionData *Section,
202                                                    uint64_t Address) const {
203   const MCSymbolData *Best = 0;
204   for (MCAssembler::const_symbol_iterator it = symbol_begin(),
205          ie = symbol_end(); it != ie; ++it) {
206     // Ignore non-linker visible symbols.
207     if (!isSymbolLinkerVisible(it))
208       continue;
209
210     // Ignore symbols not in the same section.
211     if (!it->getFragment() || it->getFragment()->getParent() != Section)
212       continue;
213
214     // Otherwise, find the closest symbol preceding this address (ties are
215     // resolved in favor of the last defined symbol).
216     if (it->getAddress() <= Address &&
217         (!Best || it->getAddress() >= Best->getAddress()))
218       Best = it;
219   }
220
221   return Best;
222 }
223
224 const MCSymbolData *MCAssembler::getAtom(const MCSymbolData *SD) const {
225   // Linker visible symbols define atoms.
226   if (isSymbolLinkerVisible(SD))
227     return SD;
228
229   // Absolute and undefined symbols have no defining atom.
230   if (!SD->getFragment())
231     return 0;
232
233   // Otherwise, search by address.
234   return getAtomForAddress(SD->getFragment()->getParent(), SD->getAddress());
235 }
236
237 bool MCAssembler::EvaluateFixup(const MCAsmLayout &Layout,
238                                 const MCAsmFixup &Fixup, const MCFragment *DF,
239                                 MCValue &Target, uint64_t &Value) const {
240   if (!Fixup.Value->EvaluateAsRelocatable(Target, &Layout))
241     llvm_report_error("expected relocatable expression");
242
243   // FIXME: How do non-scattered symbols work in ELF? I presume the linker
244   // doesn't support small relocations, but then under what criteria does the
245   // assembler allow symbol differences?
246
247   Value = Target.getConstant();
248
249   bool IsPCRel =
250     Emitter.getFixupKindInfo(Fixup.Kind).Flags & MCFixupKindInfo::FKF_IsPCRel;
251   bool IsResolved = true;
252   if (const MCSymbolRefExpr *A = Target.getSymA()) {
253     if (A->getSymbol().isDefined())
254       Value += getSymbolData(A->getSymbol()).getAddress();
255     else
256       IsResolved = false;
257   }
258   if (const MCSymbolRefExpr *B = Target.getSymB()) {
259     if (B->getSymbol().isDefined())
260       Value -= getSymbolData(B->getSymbol()).getAddress();
261     else
262       IsResolved = false;
263   }
264
265   // If we are using scattered symbols, determine whether this value is actually
266   // resolved; scattering may cause atoms to move.
267   if (IsResolved && getBackend().hasScatteredSymbols()) {
268     if (getBackend().hasReliableSymbolDifference()) {
269       // If this is a PCrel relocation, find the base atom (identified by its
270       // symbol) that the fixup value is relative to.
271       const MCSymbolData *BaseSymbol = 0;
272       if (IsPCRel) {
273         BaseSymbol = getAtomForAddress(
274           DF->getParent(), DF->getAddress() + Fixup.Offset);
275         if (!BaseSymbol)
276           IsResolved = false;
277       }
278
279       if (IsResolved)
280         IsResolved = isScatteredFixupFullyResolved(*this, Fixup, Target,
281                                                    BaseSymbol);
282     } else {
283       const MCSection *BaseSection = 0;
284       if (IsPCRel)
285         BaseSection = &DF->getParent()->getSection();
286
287       IsResolved = isScatteredFixupFullyResolvedSimple(*this, Fixup, Target,
288                                                        BaseSection);
289     }
290   }
291
292   if (IsPCRel)
293     Value -= DF->getAddress() + Fixup.Offset;
294
295   return IsResolved;
296 }
297
298 void MCAssembler::LayoutSection(MCSectionData &SD,
299                                 MCAsmLayout &Layout) {
300   uint64_t Address = SD.getAddress();
301
302   for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
303     MCFragment &F = *it;
304
305     F.setOffset(Address - SD.getAddress());
306
307     // Evaluate fragment size.
308     switch (F.getKind()) {
309     case MCFragment::FT_Align: {
310       MCAlignFragment &AF = cast<MCAlignFragment>(F);
311
312       uint64_t Size = OffsetToAlignment(Address, AF.getAlignment());
313       if (Size > AF.getMaxBytesToEmit())
314         AF.setFileSize(0);
315       else
316         AF.setFileSize(Size);
317       break;
318     }
319
320     case MCFragment::FT_Data:
321       F.setFileSize(cast<MCDataFragment>(F).getContents().size());
322       break;
323
324     case MCFragment::FT_Fill: {
325       MCFillFragment &FF = cast<MCFillFragment>(F);
326       F.setFileSize(FF.getValueSize() * FF.getCount());
327       break;
328     }
329
330     case MCFragment::FT_Org: {
331       MCOrgFragment &OF = cast<MCOrgFragment>(F);
332
333       int64_t TargetLocation;
334       if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, &Layout))
335         llvm_report_error("expected assembly-time absolute expression");
336
337       // FIXME: We need a way to communicate this error.
338       int64_t Offset = TargetLocation - F.getOffset();
339       if (Offset < 0)
340         llvm_report_error("invalid .org offset '" + Twine(TargetLocation) +
341                           "' (at offset '" + Twine(F.getOffset()) + "'");
342
343       F.setFileSize(Offset);
344       break;
345     }
346
347     case MCFragment::FT_ZeroFill: {
348       MCZeroFillFragment &ZFF = cast<MCZeroFillFragment>(F);
349
350       // Align the fragment offset; it is safe to adjust the offset freely since
351       // this is only in virtual sections.
352       Address = RoundUpToAlignment(Address, ZFF.getAlignment());
353       F.setOffset(Address - SD.getAddress());
354
355       // FIXME: This is misnamed.
356       F.setFileSize(ZFF.getSize());
357       break;
358     }
359     }
360
361     Address += F.getFileSize();
362   }
363
364   // Set the section sizes.
365   SD.setSize(Address - SD.getAddress());
366   if (getBackend().isVirtualSection(SD.getSection()))
367     SD.setFileSize(0);
368   else
369     SD.setFileSize(Address - SD.getAddress());
370 }
371
372 /// WriteNopData - Write optimal nops to the output file for the \arg Count
373 /// bytes.  This returns the number of bytes written.  It may return 0 if
374 /// the \arg Count is more than the maximum optimal nops.
375 ///
376 /// FIXME this is X86 32-bit specific and should move to a better place.
377 static uint64_t WriteNopData(uint64_t Count, MCObjectWriter *OW) {
378   static const uint8_t Nops[16][16] = {
379     // nop
380     {0x90},
381     // xchg %ax,%ax
382     {0x66, 0x90},
383     // nopl (%[re]ax)
384     {0x0f, 0x1f, 0x00},
385     // nopl 0(%[re]ax)
386     {0x0f, 0x1f, 0x40, 0x00},
387     // nopl 0(%[re]ax,%[re]ax,1)
388     {0x0f, 0x1f, 0x44, 0x00, 0x00},
389     // nopw 0(%[re]ax,%[re]ax,1)
390     {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
391     // nopl 0L(%[re]ax)
392     {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
393     // nopl 0L(%[re]ax,%[re]ax,1)
394     {0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
395     // nopw 0L(%[re]ax,%[re]ax,1)
396     {0x66, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
397     // nopw %cs:0L(%[re]ax,%[re]ax,1)
398     {0x66, 0x2e, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
399     // nopl 0(%[re]ax,%[re]ax,1)
400     // nopw 0(%[re]ax,%[re]ax,1)
401     {0x0f, 0x1f, 0x44, 0x00, 0x00,
402      0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
403     // nopw 0(%[re]ax,%[re]ax,1)
404     // nopw 0(%[re]ax,%[re]ax,1)
405     {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00,
406      0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
407     // nopw 0(%[re]ax,%[re]ax,1)
408     // nopl 0L(%[re]ax) */
409     {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00,
410      0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
411     // nopl 0L(%[re]ax)
412     // nopl 0L(%[re]ax)
413     {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00,
414      0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
415     // nopl 0L(%[re]ax)
416     // nopl 0L(%[re]ax,%[re]ax,1)
417     {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00,
418      0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00}
419   };
420
421   if (Count > 15)
422     return 0;
423
424   for (uint64_t i = 0; i < Count; i++)
425     OW->Write8(uint8_t(Nops[Count - 1][i]));
426
427   return Count;
428 }
429
430 /// WriteFragmentData - Write the \arg F data to the output file.
431 static void WriteFragmentData(const MCFragment &F, MCObjectWriter *OW) {
432   uint64_t Start = OW->getStream().tell();
433   (void) Start;
434
435   ++EmittedFragments;
436
437   // FIXME: Embed in fragments instead?
438   switch (F.getKind()) {
439   case MCFragment::FT_Align: {
440     MCAlignFragment &AF = cast<MCAlignFragment>(F);
441     uint64_t Count = AF.getFileSize() / AF.getValueSize();
442
443     // FIXME: This error shouldn't actually occur (the front end should emit
444     // multiple .align directives to enforce the semantics it wants), but is
445     // severe enough that we want to report it. How to handle this?
446     if (Count * AF.getValueSize() != AF.getFileSize())
447       llvm_report_error("undefined .align directive, value size '" +
448                         Twine(AF.getValueSize()) +
449                         "' is not a divisor of padding size '" +
450                         Twine(AF.getFileSize()) + "'");
451
452     // See if we are aligning with nops, and if so do that first to try to fill
453     // the Count bytes.  Then if that did not fill any bytes or there are any
454     // bytes left to fill use the the Value and ValueSize to fill the rest.
455     if (AF.getEmitNops()) {
456       uint64_t NopByteCount = WriteNopData(Count, OW);
457       Count -= NopByteCount;
458     }
459
460     for (uint64_t i = 0; i != Count; ++i) {
461       switch (AF.getValueSize()) {
462       default:
463         assert(0 && "Invalid size!");
464       case 1: OW->Write8 (uint8_t (AF.getValue())); break;
465       case 2: OW->Write16(uint16_t(AF.getValue())); break;
466       case 4: OW->Write32(uint32_t(AF.getValue())); break;
467       case 8: OW->Write64(uint64_t(AF.getValue())); break;
468       }
469     }
470     break;
471   }
472
473   case MCFragment::FT_Data: {
474     OW->WriteBytes(cast<MCDataFragment>(F).getContents().str());
475     break;
476   }
477
478   case MCFragment::FT_Fill: {
479     MCFillFragment &FF = cast<MCFillFragment>(F);
480     for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
481       switch (FF.getValueSize()) {
482       default:
483         assert(0 && "Invalid size!");
484       case 1: OW->Write8 (uint8_t (FF.getValue())); break;
485       case 2: OW->Write16(uint16_t(FF.getValue())); break;
486       case 4: OW->Write32(uint32_t(FF.getValue())); break;
487       case 8: OW->Write64(uint64_t(FF.getValue())); break;
488       }
489     }
490     break;
491   }
492
493   case MCFragment::FT_Org: {
494     MCOrgFragment &OF = cast<MCOrgFragment>(F);
495
496     for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
497       OW->Write8(uint8_t(OF.getValue()));
498
499     break;
500   }
501
502   case MCFragment::FT_ZeroFill: {
503     assert(0 && "Invalid zero fill fragment in concrete section!");
504     break;
505   }
506   }
507
508   assert(OW->getStream().tell() - Start == F.getFileSize());
509 }
510
511 void MCAssembler::WriteSectionData(const MCSectionData *SD,
512                                    MCObjectWriter *OW) const {
513   // Ignore virtual sections.
514   if (getBackend().isVirtualSection(SD->getSection())) {
515     assert(SD->getFileSize() == 0);
516     return;
517   }
518
519   uint64_t Start = OW->getStream().tell();
520   (void) Start;
521
522   for (MCSectionData::const_iterator it = SD->begin(),
523          ie = SD->end(); it != ie; ++it)
524     WriteFragmentData(*it, OW);
525
526   // Add section padding.
527   assert(SD->getFileSize() >= SD->getSize() && "Invalid section sizes!");
528   OW->WriteZeros(SD->getFileSize() - SD->getSize());
529
530   assert(OW->getStream().tell() - Start == SD->getFileSize());
531 }
532
533 void MCAssembler::Finish() {
534   DEBUG_WITH_TYPE("mc-dump", {
535       llvm::errs() << "assembler backend - pre-layout\n--\n";
536       dump(); });
537
538   // Layout until everything fits.
539   MCAsmLayout Layout(*this);
540   while (LayoutOnce(Layout))
541     continue;
542
543   DEBUG_WITH_TYPE("mc-dump", {
544       llvm::errs() << "assembler backend - post-layout\n--\n";
545       dump(); });
546
547   llvm::OwningPtr<MCObjectWriter> Writer(getBackend().createObjectWriter(OS));
548   if (!Writer)
549     llvm_report_error("unable to create object writer!");
550
551   // Allow the object writer a chance to perform post-layout binding (for
552   // example, to set the index fields in the symbol data).
553   Writer->ExecutePostLayoutBinding(*this);
554
555   // Evaluate and apply the fixups, generating relocation entries as necessary.
556   for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
557     for (MCSectionData::iterator it2 = it->begin(),
558            ie2 = it->end(); it2 != ie2; ++it2) {
559       MCDataFragment *DF = dyn_cast<MCDataFragment>(it2);
560       if (!DF)
561         continue;
562
563       for (MCDataFragment::fixup_iterator it3 = DF->fixup_begin(),
564              ie3 = DF->fixup_end(); it3 != ie3; ++it3) {
565         MCAsmFixup &Fixup = *it3;
566
567         // Evaluate the fixup.
568         MCValue Target;
569         uint64_t FixedValue;
570         if (!EvaluateFixup(Layout, Fixup, DF, Target, FixedValue)) {
571           // The fixup was unresolved, we need a relocation. Inform the object
572           // writer of the relocation, and give it an opportunity to adjust the
573           // fixup value if need be.
574           Writer->RecordRelocation(*this, DF, Fixup, Target, FixedValue);
575         }
576
577         getBackend().ApplyFixup(Fixup, *DF, FixedValue);
578       }
579     }
580   }
581
582   // Write the object file.
583   Writer->WriteObject(*this);
584   OS.flush();
585 }
586
587 bool MCAssembler::FixupNeedsRelaxation(const MCAsmFixup &Fixup,
588                                        const MCFragment *DF,
589                                        const MCAsmLayout &Layout) const {
590   // Currently we only need to relax X86::reloc_pcrel_1byte.
591   if (unsigned(Fixup.Kind) != X86::reloc_pcrel_1byte)
592     return false;
593
594   // If we cannot resolve the fixup value, it requires relaxation.
595   MCValue Target;
596   uint64_t Value;
597   if (!EvaluateFixup(Layout, Fixup, DF, Target, Value))
598     return true;
599
600   // Otherwise, relax if the value is too big for a (signed) i8.
601   return int64_t(Value) != int64_t(int8_t(Value));
602 }
603
604 bool MCAssembler::LayoutOnce(MCAsmLayout &Layout) {
605   // Layout the concrete sections and fragments.
606   uint64_t Address = 0;
607   MCSectionData *Prev = 0;
608   for (iterator it = begin(), ie = end(); it != ie; ++it) {
609     MCSectionData &SD = *it;
610
611     // Skip virtual sections.
612     if (getBackend().isVirtualSection(SD.getSection()))
613       continue;
614
615     // Align this section if necessary by adding padding bytes to the previous
616     // section.
617     if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment())) {
618       assert(Prev && "Missing prev section!");
619       Prev->setFileSize(Prev->getFileSize() + Pad);
620       Address += Pad;
621     }
622
623     // Layout the section fragments and its size.
624     SD.setAddress(Address);
625     LayoutSection(SD, Layout);
626     Address += SD.getFileSize();
627
628     Prev = &SD;
629   }
630
631   // Layout the virtual sections.
632   for (iterator it = begin(), ie = end(); it != ie; ++it) {
633     MCSectionData &SD = *it;
634
635     if (!getBackend().isVirtualSection(SD.getSection()))
636       continue;
637
638     // Align this section if necessary by adding padding bytes to the previous
639     // section.
640     if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment()))
641       Address += Pad;
642
643     SD.setAddress(Address);
644     LayoutSection(SD, Layout);
645     Address += SD.getSize();
646   }
647
648   // Scan the fixups in order and relax any that don't fit.
649   for (iterator it = begin(), ie = end(); it != ie; ++it) {
650     MCSectionData &SD = *it;
651
652     for (MCSectionData::iterator it2 = SD.begin(),
653            ie2 = SD.end(); it2 != ie2; ++it2) {
654       MCDataFragment *DF = dyn_cast<MCDataFragment>(it2);
655       if (!DF)
656         continue;
657
658       for (MCDataFragment::fixup_iterator it3 = DF->fixup_begin(),
659              ie3 = DF->fixup_end(); it3 != ie3; ++it3) {
660         MCAsmFixup &Fixup = *it3;
661
662         // Check whether we need to relax this fixup.
663         if (!FixupNeedsRelaxation(Fixup, DF, Layout))
664           continue;
665
666         // Relax the instruction.
667         //
668         // FIXME: This is a huge temporary hack which just looks for x86
669         // branches; the only thing we need to relax on x86 is
670         // 'X86::reloc_pcrel_1byte'. Once we have MCInst fragments, this will be
671         // replaced by a TargetAsmBackend hook (most likely tblgen'd) to relax
672         // an individual MCInst.
673         SmallVectorImpl<char> &C = DF->getContents();
674         uint64_t PrevOffset = Fixup.Offset;
675         unsigned Amt = 0;
676
677           // jcc instructions
678         if (unsigned(C[Fixup.Offset-1]) >= 0x70 &&
679             unsigned(C[Fixup.Offset-1]) <= 0x7f) {
680           C[Fixup.Offset] = C[Fixup.Offset-1] + 0x10;
681           C[Fixup.Offset-1] = char(0x0f);
682           ++Fixup.Offset;
683           Amt = 4;
684
685           // jmp rel8
686         } else if (C[Fixup.Offset-1] == char(0xeb)) {
687           C[Fixup.Offset-1] = char(0xe9);
688           Amt = 3;
689
690         } else
691           llvm_unreachable("unknown 1 byte pcrel instruction!");
692
693         Fixup.Value = MCBinaryExpr::Create(
694           MCBinaryExpr::Sub, Fixup.Value,
695           MCConstantExpr::Create(3, getContext()),
696           getContext());
697         C.insert(C.begin() + Fixup.Offset, Amt, char(0));
698         Fixup.Kind = MCFixupKind(X86::reloc_pcrel_4byte);
699
700         // Update the remaining fixups, which have slid.
701         //
702         // FIXME: This is bad for performance, but will be eliminated by the
703         // move to MCInst specific fragments.
704         ++it3;
705         for (; it3 != ie3; ++it3)
706           it3->Offset += Amt;
707
708         // Update all the symbols for this fragment, which may have slid.
709         //
710         // FIXME: This is really really bad for performance, but will be
711         // eliminated by the move to MCInst specific fragments.
712         for (MCAssembler::symbol_iterator it = symbol_begin(),
713                ie = symbol_end(); it != ie; ++it) {
714           MCSymbolData &SD = *it;
715
716           if (it->getFragment() != DF)
717             continue;
718
719           if (SD.getOffset() > PrevOffset)
720             SD.setOffset(SD.getOffset() + Amt);
721         }
722
723         // Restart layout.
724         //
725         // FIXME: This is O(N^2), but will be eliminated once we have a smart
726         // MCAsmLayout object.
727         return true;
728       }
729     }
730   }
731
732   return false;
733 }
734
735 // Debugging methods
736
737 namespace llvm {
738
739 raw_ostream &operator<<(raw_ostream &OS, const MCAsmFixup &AF) {
740   OS << "<MCAsmFixup" << " Offset:" << AF.Offset << " Value:" << *AF.Value
741      << " Kind:" << AF.Kind << ">";
742   return OS;
743 }
744
745 }
746
747 void MCFragment::dump() {
748   raw_ostream &OS = llvm::errs();
749
750   OS << "<MCFragment " << (void*) this << " Offset:" << Offset
751      << " FileSize:" << FileSize;
752
753   OS << ">";
754 }
755
756 void MCAlignFragment::dump() {
757   raw_ostream &OS = llvm::errs();
758
759   OS << "<MCAlignFragment ";
760   this->MCFragment::dump();
761   OS << "\n       ";
762   OS << " Alignment:" << getAlignment()
763      << " Value:" << getValue() << " ValueSize:" << getValueSize()
764      << " MaxBytesToEmit:" << getMaxBytesToEmit() << ">";
765 }
766
767 void MCDataFragment::dump() {
768   raw_ostream &OS = llvm::errs();
769
770   OS << "<MCDataFragment ";
771   this->MCFragment::dump();
772   OS << "\n       ";
773   OS << " Contents:[";
774   for (unsigned i = 0, e = getContents().size(); i != e; ++i) {
775     if (i) OS << ",";
776     OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
777   }
778   OS << "] (" << getContents().size() << " bytes)";
779
780   if (!getFixups().empty()) {
781     OS << ",\n       ";
782     OS << " Fixups:[";
783     for (fixup_iterator it = fixup_begin(), ie = fixup_end(); it != ie; ++it) {
784       if (it != fixup_begin()) OS << ",\n                ";
785       OS << *it;
786     }
787     OS << "]";
788   }
789
790   OS << ">";
791 }
792
793 void MCFillFragment::dump() {
794   raw_ostream &OS = llvm::errs();
795
796   OS << "<MCFillFragment ";
797   this->MCFragment::dump();
798   OS << "\n       ";
799   OS << " Value:" << getValue() << " ValueSize:" << getValueSize()
800      << " Count:" << getCount() << ">";
801 }
802
803 void MCOrgFragment::dump() {
804   raw_ostream &OS = llvm::errs();
805
806   OS << "<MCOrgFragment ";
807   this->MCFragment::dump();
808   OS << "\n       ";
809   OS << " Offset:" << getOffset() << " Value:" << getValue() << ">";
810 }
811
812 void MCZeroFillFragment::dump() {
813   raw_ostream &OS = llvm::errs();
814
815   OS << "<MCZeroFillFragment ";
816   this->MCFragment::dump();
817   OS << "\n       ";
818   OS << " Size:" << getSize() << " Alignment:" << getAlignment() << ">";
819 }
820
821 void MCSectionData::dump() {
822   raw_ostream &OS = llvm::errs();
823
824   OS << "<MCSectionData";
825   OS << " Alignment:" << getAlignment() << " Address:" << Address
826      << " Size:" << Size << " FileSize:" << FileSize
827      << " Fragments:[\n      ";
828   for (iterator it = begin(), ie = end(); it != ie; ++it) {
829     if (it != begin()) OS << ",\n      ";
830     it->dump();
831   }
832   OS << "]>";
833 }
834
835 void MCSymbolData::dump() {
836   raw_ostream &OS = llvm::errs();
837
838   OS << "<MCSymbolData Symbol:" << getSymbol()
839      << " Fragment:" << getFragment() << " Offset:" << getOffset()
840      << " Flags:" << getFlags() << " Index:" << getIndex();
841   if (isCommon())
842     OS << " (common, size:" << getCommonSize()
843        << " align: " << getCommonAlignment() << ")";
844   if (isExternal())
845     OS << " (external)";
846   if (isPrivateExtern())
847     OS << " (private extern)";
848   OS << ">";
849 }
850
851 void MCAssembler::dump() {
852   raw_ostream &OS = llvm::errs();
853
854   OS << "<MCAssembler\n";
855   OS << "  Sections:[\n    ";
856   for (iterator it = begin(), ie = end(); it != ie; ++it) {
857     if (it != begin()) OS << ",\n    ";
858     it->dump();
859   }
860   OS << "],\n";
861   OS << "  Symbols:[";
862
863   for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
864     if (it != symbol_begin()) OS << ",\n           ";
865     it->dump();
866   }
867   OS << "]>\n";
868 }