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