blob: 4d8cc6a763cb79e704e72e24cfc5eb6897fbca89 [file] [log] [blame]
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +00001//===- 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
Daniel Dunbar0adcd352009-08-25 21:10:45 +000010#define DEBUG_TYPE "assembler"
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000011#include "llvm/MC/MCAssembler.h"
Daniel Dunbar18ff2cc2010-03-11 05:53:33 +000012#include "llvm/MC/MCAsmLayout.h"
Daniel Dunbar1253a6f2009-10-16 01:58:03 +000013#include "llvm/MC/MCExpr.h"
Daniel Dunbar53b23382010-03-19 09:28:59 +000014#include "llvm/MC/MCObjectWriter.h"
Daniel Dunbar1253a6f2009-10-16 01:58:03 +000015#include "llvm/MC/MCSymbol.h"
16#include "llvm/MC/MCValue.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000017#include "llvm/MC/MachObjectWriter.h"
Daniel Dunbar0adcd352009-08-25 21:10:45 +000018#include "llvm/ADT/Statistic.h"
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +000019#include "llvm/ADT/StringExtras.h"
Daniel Dunbard6f761e2009-08-21 23:07:38 +000020#include "llvm/ADT/Twine.h"
Daniel Dunbar0705fbf2009-08-21 18:29:01 +000021#include "llvm/Support/ErrorHandling.h"
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000022#include "llvm/Support/raw_ostream.h"
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +000023#include "llvm/Support/Debug.h"
Daniel Dunbaree0d8922010-03-13 22:10:17 +000024#include "llvm/Target/TargetRegistry.h"
Daniel Dunbardf3c8f22010-03-12 21:00:49 +000025#include "llvm/Target/TargetAsmBackend.h"
Daniel Dunbarf6346762010-02-13 09:29:02 +000026
27// FIXME: Gross.
28#include "../Target/X86/X86FixupKinds.h"
29
Chris Lattner23132b12009-08-24 03:52:50 +000030#include <vector>
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000031using namespace llvm;
32
Daniel Dunbar0adcd352009-08-25 21:10:45 +000033STATISTIC(EmittedFragments, "Number of emitted assembler fragments");
34
Daniel Dunbar8f4d1462009-08-28 07:08:35 +000035// 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
Duncan Sands9a7795c2010-02-17 14:52:22 +000040static bool isFixupKindPCRel(unsigned Kind) {
Daniel Dunbar591047f2010-02-13 09:45:59 +000041 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
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000051/* *** */
52
Daniel Dunbar0705fbf2009-08-21 18:29:01 +000053MCFragment::MCFragment() : Kind(FragmentType(~0)) {
54}
55
Daniel Dunbar5e835962009-08-26 02:48:04 +000056MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
Daniel Dunbar0705fbf2009-08-21 18:29:01 +000057 : Kind(_Kind),
Daniel Dunbar5e835962009-08-26 02:48:04 +000058 Parent(_Parent),
Daniel Dunbar0705fbf2009-08-21 18:29:01 +000059 FileSize(~UINT64_C(0))
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000060{
Daniel Dunbar5e835962009-08-26 02:48:04 +000061 if (Parent)
62 Parent->getFragmentList().push_back(this);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000063}
64
Daniel Dunbar0705fbf2009-08-21 18:29:01 +000065MCFragment::~MCFragment() {
66}
67
Daniel Dunbar5e835962009-08-26 02:48:04 +000068uint64_t MCFragment::getAddress() const {
69 assert(getParent() && "Missing Section!");
70 return getParent()->getAddress() + Offset;
71}
72
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000073/* *** */
74
Daniel Dunbar81e40002009-08-27 00:38:04 +000075MCSectionData::MCSectionData() : Section(0) {}
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000076
77MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
Daniel Dunbar81e40002009-08-27 00:38:04 +000078 : Section(&_Section),
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000079 Alignment(1),
Daniel Dunbar5e835962009-08-26 02:48:04 +000080 Address(~UINT64_C(0)),
Daniel Dunbar6742e342009-08-26 04:13:32 +000081 Size(~UINT64_C(0)),
Daniel Dunbar3f6a9602009-08-26 13:58:10 +000082 FileSize(~UINT64_C(0)),
Daniel Dunbare1ec6172010-02-02 21:44:01 +000083 HasInstructions(false)
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000084{
85 if (A)
86 A->getSectionList().push_back(this);
87}
88
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000089/* *** */
90
Daniel Dunbarefbb5332009-09-01 04:09:03 +000091MCSymbolData::MCSymbolData() : Symbol(0) {}
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000092
Daniel Dunbarcb579b32009-08-31 08:08:06 +000093MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000094 uint64_t _Offset, MCAssembler *A)
Daniel Dunbarefbb5332009-09-01 04:09:03 +000095 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
Daniel Dunbar8f4d1462009-08-28 07:08:35 +000096 IsExternal(false), IsPrivateExtern(false),
97 CommonSize(0), CommonAlign(0), Flags(0), Index(0)
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000098{
99 if (A)
100 A->getSymbolList().push_back(this);
101}
102
103/* *** */
104
Daniel Dunbar1f3e4452010-03-11 01:34:27 +0000105MCAssembler::MCAssembler(MCContext &_Context, TargetAsmBackend &_Backend,
Daniel Dunbarcf871e52010-03-19 10:43:18 +0000106 MCCodeEmitter &_Emitter, raw_ostream &_OS)
107 : Context(_Context), Backend(_Backend), Emitter(_Emitter),
108 OS(_OS), SubsectionsViaSymbols(false)
Daniel Dunbar6009db42009-08-26 21:22:22 +0000109{
110}
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000111
112MCAssembler::~MCAssembler() {
113}
114
Daniel Dunbar939f8d72010-03-19 03:18:12 +0000115static 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
Daniel Dunbar034843a2010-03-19 03:18:18 +0000153static 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
Daniel Dunbar23869852010-03-19 03:18:09 +0000199bool 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
Daniel Dunbar8ad0dcc2010-03-19 03:18:15 +0000213const 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
236const 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
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000249bool 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
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000261 bool IsResolved = true, IsPCRel = isFixupKindPCRel(Fixup.Kind);
Daniel Dunbar9a1d2002010-03-18 00:59:10 +0000262 if (const MCSymbolRefExpr *A = Target.getSymA()) {
263 if (A->getSymbol().isDefined())
264 Value += getSymbolData(A->getSymbol()).getAddress();
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000265 else
266 IsResolved = false;
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000267 }
Daniel Dunbar9a1d2002010-03-18 00:59:10 +0000268 if (const MCSymbolRefExpr *B = Target.getSymB()) {
269 if (B->getSymbol().isDefined())
270 Value -= getSymbolData(B->getSymbol()).getAddress();
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000271 else
272 IsResolved = false;
Daniel Dunbar939f8d72010-03-19 03:18:12 +0000273 }
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000274
Daniel Dunbar939f8d72010-03-19 03:18:12 +0000275 // 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()) {
Daniel Dunbar034843a2010-03-19 03:18:18 +0000279 // 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);
Daniel Dunbar939f8d72010-03-19 03:18:12 +0000292 } 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 }
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000300 }
301
302 if (IsPCRel)
Daniel Dunbarda3e9f72010-03-13 02:38:00 +0000303 Value -= DF->getAddress() + Fixup.Offset;
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000304
305 return IsResolved;
306}
307
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000308void MCAssembler::LayoutSection(MCSectionData &SD) {
Daniel Dunbar18ff2cc2010-03-11 05:53:33 +0000309 MCAsmLayout Layout(*this);
Daniel Dunbar6742e342009-08-26 04:13:32 +0000310 uint64_t Address = SD.getAddress();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000311
312 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
313 MCFragment &F = *it;
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000314
Daniel Dunbar6742e342009-08-26 04:13:32 +0000315 F.setOffset(Address - SD.getAddress());
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000316
317 // Evaluate fragment size.
318 switch (F.getKind()) {
319 case MCFragment::FT_Align: {
320 MCAlignFragment &AF = cast<MCAlignFragment>(F);
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000321
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000322 uint64_t Size = OffsetToAlignment(Address, AF.getAlignment());
Daniel Dunbar6742e342009-08-26 04:13:32 +0000323 if (Size > AF.getMaxBytesToEmit())
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000324 AF.setFileSize(0);
325 else
Daniel Dunbar6742e342009-08-26 04:13:32 +0000326 AF.setFileSize(Size);
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000327 break;
328 }
329
330 case MCFragment::FT_Data:
Daniel Dunbara4766d72010-02-13 09:28:32 +0000331 case MCFragment::FT_Fill:
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000332 F.setFileSize(F.getMaxFileSize());
333 break;
334
335 case MCFragment::FT_Org: {
336 MCOrgFragment &OF = cast<MCOrgFragment>(F);
337
Daniel Dunbar18ff2cc2010-03-11 05:53:33 +0000338 int64_t TargetLocation;
339 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, &Layout))
340 llvm_report_error("expected assembly-time absolute expression");
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000341
342 // FIXME: We need a way to communicate this error.
Daniel Dunbar18ff2cc2010-03-11 05:53:33 +0000343 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()) + "'");
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000347
Daniel Dunbar18ff2cc2010-03-11 05:53:33 +0000348 F.setFileSize(Offset);
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000349 break;
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000350 }
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000351
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.
Daniel Dunbar37fad5c2010-03-08 21:10:42 +0000357 Address = RoundUpToAlignment(Address, ZFF.getAlignment());
358 F.setOffset(Address - SD.getAddress());
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000359
360 // FIXME: This is misnamed.
361 F.setFileSize(ZFF.getSize());
362 break;
363 }
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000364 }
365
Daniel Dunbar6742e342009-08-26 04:13:32 +0000366 Address += F.getFileSize();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000367 }
368
Daniel Dunbar6742e342009-08-26 04:13:32 +0000369 // Set the section sizes.
370 SD.setSize(Address - SD.getAddress());
Daniel Dunbarcc5b84c2010-03-19 09:29:03 +0000371 if (getBackend().isVirtualSection(SD.getSection()))
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000372 SD.setFileSize(0);
373 else
374 SD.setFileSize(Address - SD.getAddress());
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000375}
376
Kevin Enderby6e720482010-02-23 18:26:34 +0000377/// 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.
Daniel Dunbarbdd92812010-03-19 09:28:55 +0000382static uint64_t WriteNopData(uint64_t Count, MCObjectWriter *OW) {
Kevin Enderby76687082010-02-23 21:41:24 +0000383 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
Kevin Enderby6e720482010-02-23 18:26:34 +0000429 for (uint64_t i = 0; i < Count; i++)
Daniel Dunbarbdd92812010-03-19 09:28:55 +0000430 OW->Write8(uint8_t(Nops[Count - 1][i]));
Kevin Enderby6e720482010-02-23 18:26:34 +0000431
432 return Count;
433}
434
Daniel Dunbar53b23382010-03-19 09:28:59 +0000435/// WriteFragmentData - Write the \arg F data to the output file.
436static void WriteFragmentData(const MCFragment &F, MCObjectWriter *OW) {
437 uint64_t Start = OW->getStream().tell();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000438 (void) Start;
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000439
Daniel Dunbar0adcd352009-08-25 21:10:45 +0000440 ++EmittedFragments;
441
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000442 // FIXME: Embed in fragments instead?
443 switch (F.getKind()) {
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000444 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())
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000452 llvm_report_error("undefined .align directive, value size '" +
453 Twine(AF.getValueSize()) +
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000454 "' is not a divisor of padding size '" +
455 Twine(AF.getFileSize()) + "'");
456
Kevin Enderby6e720482010-02-23 18:26:34 +0000457 // 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()) {
Daniel Dunbarbdd92812010-03-19 09:28:55 +0000461 uint64_t NopByteCount = WriteNopData(Count, OW);
Kevin Enderby6e720482010-02-23 18:26:34 +0000462 Count -= NopByteCount;
463 }
464
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000465 for (uint64_t i = 0; i != Count; ++i) {
466 switch (AF.getValueSize()) {
467 default:
468 assert(0 && "Invalid size!");
Daniel Dunbarbdd92812010-03-19 09:28:55 +0000469 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;
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000473 }
474 }
475 break;
476 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000477
Daniel Dunbar3a30b822010-02-13 09:28:15 +0000478 case MCFragment::FT_Data: {
Daniel Dunbar53b23382010-03-19 09:28:59 +0000479 OW->WriteBytes(cast<MCDataFragment>(F).getContents().str());
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000480 break;
Daniel Dunbar3a30b822010-02-13 09:28:15 +0000481 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000482
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000483 case MCFragment::FT_Fill: {
484 MCFillFragment &FF = cast<MCFillFragment>(F);
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000485 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
486 switch (FF.getValueSize()) {
487 default:
488 assert(0 && "Invalid size!");
Daniel Dunbarbdd92812010-03-19 09:28:55 +0000489 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;
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000493 }
494 }
495 break;
496 }
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000497
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000498 case MCFragment::FT_Org: {
499 MCOrgFragment &OF = cast<MCOrgFragment>(F);
500
501 for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
Daniel Dunbarbdd92812010-03-19 09:28:55 +0000502 OW->Write8(uint8_t(OF.getValue()));
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000503
504 break;
505 }
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000506
507 case MCFragment::FT_ZeroFill: {
508 assert(0 && "Invalid zero fill fragment in concrete section!");
509 break;
510 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000511 }
512
Daniel Dunbar53b23382010-03-19 09:28:59 +0000513 assert(OW->getStream().tell() - Start == F.getFileSize());
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000514}
515
Daniel Dunbar53b23382010-03-19 09:28:59 +0000516void MCAssembler::WriteSectionData(const MCSectionData *SD,
517 MCObjectWriter *OW) const {
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000518 // Ignore virtual sections.
Daniel Dunbarcc5b84c2010-03-19 09:29:03 +0000519 if (getBackend().isVirtualSection(SD->getSection())) {
Daniel Dunbar53b23382010-03-19 09:28:59 +0000520 assert(SD->getFileSize() == 0);
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000521 return;
522 }
523
Daniel Dunbar53b23382010-03-19 09:28:59 +0000524 uint64_t Start = OW->getStream().tell();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000525 (void) Start;
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000526
Daniel Dunbar53b23382010-03-19 09:28:59 +0000527 for (MCSectionData::const_iterator it = SD->begin(),
528 ie = SD->end(); it != ie; ++it)
529 WriteFragmentData(*it, OW);
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000530
Daniel Dunbar6742e342009-08-26 04:13:32 +0000531 // Add section padding.
Daniel Dunbar53b23382010-03-19 09:28:59 +0000532 assert(SD->getFileSize() >= SD->getSize() && "Invalid section sizes!");
533 OW->WriteZeros(SD->getFileSize() - SD->getSize());
Daniel Dunbar6742e342009-08-26 04:13:32 +0000534
Daniel Dunbar53b23382010-03-19 09:28:59 +0000535 assert(OW->getStream().tell() - Start == SD->getFileSize());
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000536}
537
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000538void MCAssembler::Finish() {
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000539 DEBUG_WITH_TYPE("mc-dump", {
540 llvm::errs() << "assembler backend - pre-layout\n--\n";
541 dump(); });
542
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000543 // 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
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000551 // FIXME: Factor out MCObjectWriter.
552 bool Is64Bit = StringRef(getBackend().getTarget().getName()) == "x86-64";
553 MachObjectWriter MOW(OS, Is64Bit);
Daniel Dunbarbacba992010-03-19 07:09:33 +0000554
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
Daniel Dunbarb1e98942010-03-19 07:09:47 +0000559 // Evaluate and apply the fixups, generating relocation entries as necessary.
Daniel Dunbarbdd92812010-03-19 09:28:55 +0000560 //
561 // FIXME: Share layout object.
Daniel Dunbarb1e98942010-03-19 07:09:47 +0000562 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
Daniel Dunbar87190c42010-03-19 09:28:12 +0000584 getBackend().ApplyFixup(Fixup, *DF, FixedValue);
Daniel Dunbarb1e98942010-03-19 07:09:47 +0000585 }
586 }
587 }
588
Daniel Dunbarbacba992010-03-19 07:09:33 +0000589 // Write the object file.
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000590 MOW.WriteObject(*this);
591
592 OS.flush();
593}
594
595bool 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
613bool MCAssembler::LayoutOnce() {
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000614 // Layout the concrete sections and fragments.
Daniel Dunbar5e835962009-08-26 02:48:04 +0000615 uint64_t Address = 0;
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000616 MCSectionData *Prev = 0;
617 for (iterator it = begin(), ie = end(); it != ie; ++it) {
Daniel Dunbar6742e342009-08-26 04:13:32 +0000618 MCSectionData &SD = *it;
619
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000620 // Skip virtual sections.
Daniel Dunbarcc5b84c2010-03-19 09:29:03 +0000621 if (getBackend().isVirtualSection(SD.getSection()))
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000622 continue;
623
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000624 // 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 }
Daniel Dunbar6742e342009-08-26 04:13:32 +0000631
632 // Layout the section fragments and its size.
633 SD.setAddress(Address);
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000634 LayoutSection(SD);
Daniel Dunbar6742e342009-08-26 04:13:32 +0000635 Address += SD.getFileSize();
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000636
637 Prev = &SD;
Daniel Dunbar5e835962009-08-26 02:48:04 +0000638 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000639
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000640 // Layout the virtual sections.
641 for (iterator it = begin(), ie = end(); it != ie; ++it) {
642 MCSectionData &SD = *it;
643
Daniel Dunbarcc5b84c2010-03-19 09:29:03 +0000644 if (!getBackend().isVirtualSection(SD.getSection()))
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000645 continue;
646
Daniel Dunbarb2b4acd2010-03-08 22:03:42 +0000647 // Align this section if necessary by adding padding bytes to the previous
648 // section.
Daniel Dunbarf8b8ad72010-03-09 01:12:20 +0000649 if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment()))
Daniel Dunbarb2b4acd2010-03-08 22:03:42 +0000650 Address += Pad;
Daniel Dunbarb2b4acd2010-03-08 22:03:42 +0000651
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000652 SD.setAddress(Address);
653 LayoutSection(SD);
654 Address += SD.getSize();
655 }
656
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000657 // 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;
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000660
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000661 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;
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000666
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000667 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;
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000742}
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000743
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000744// Debugging methods
745
746namespace llvm {
747
748raw_ostream &operator<<(raw_ostream &OS, const MCAsmFixup &AF) {
Daniel Dunbar2be2fd02010-02-13 09:28:54 +0000749 OS << "<MCAsmFixup" << " Offset:" << AF.Offset << " Value:" << *AF.Value
750 << " Kind:" << AF.Kind << ">";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000751 return OS;
752}
753
754}
755
756void MCFragment::dump() {
757 raw_ostream &OS = llvm::errs();
758
759 OS << "<MCFragment " << (void*) this << " Offset:" << Offset
760 << " FileSize:" << FileSize;
761
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000762 OS << ">";
763}
764
765void 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
776void 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 }
Daniel Dunbar2be2fd02010-02-13 09:28:54 +0000787 OS << "] (" << getContents().size() << " bytes)";
Daniel Dunbar0bcf0742010-02-13 09:28:43 +0000788
789 if (!getFixups().empty()) {
790 OS << ",\n ";
791 OS << " Fixups:[";
792 for (fixup_iterator it = fixup_begin(), ie = fixup_end(); it != ie; ++it) {
Daniel Dunbar45aefff2010-03-09 01:12:23 +0000793 if (it != fixup_begin()) OS << ",\n ";
Daniel Dunbar0bcf0742010-02-13 09:28:43 +0000794 OS << *it;
795 }
796 OS << "]";
797 }
798
799 OS << ">";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000800}
801
802void 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
812void 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
821void 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
830void MCSectionData::dump() {
831 raw_ostream &OS = llvm::errs();
832
833 OS << "<MCSectionData";
834 OS << " Alignment:" << getAlignment() << " Address:" << Address
835 << " Size:" << Size << " FileSize:" << FileSize
Daniel Dunbar45aefff2010-03-09 01:12:23 +0000836 << " Fragments:[\n ";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000837 for (iterator it = begin(), ie = end(); it != ie; ++it) {
838 if (it != begin()) OS << ",\n ";
839 it->dump();
840 }
841 OS << "]>";
842}
843
844void 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
860void MCAssembler::dump() {
861 raw_ostream &OS = llvm::errs();
862
863 OS << "<MCAssembler\n";
Daniel Dunbar45aefff2010-03-09 01:12:23 +0000864 OS << " Sections:[\n ";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000865 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) {
Daniel Dunbar45aefff2010-03-09 01:12:23 +0000873 if (it != symbol_begin()) OS << ",\n ";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000874 it->dump();
875 }
876 OS << "]>\n";
877}