blob: 6e5f73ff44cf55f63df6eac9ccd8b458253f4b3a [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,
106 raw_ostream &_OS)
107 : Context(_Context), Backend(_Backend), OS(_OS), SubsectionsViaSymbols(false)
Daniel Dunbar6009db42009-08-26 21:22:22 +0000108{
109}
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000110
111MCAssembler::~MCAssembler() {
112}
113
Daniel Dunbar939f8d72010-03-19 03:18:12 +0000114static bool isScatteredFixupFullyResolvedSimple(const MCAssembler &Asm,
115 const MCAsmFixup &Fixup,
116 const MCDataFragment *DF,
117 const MCValue Target,
118 const MCSection *BaseSection) {
119 // The effective fixup address is
120 // addr(atom(A)) + offset(A)
121 // - addr(atom(B)) - offset(B)
122 // - addr(<base symbol>) + <fixup offset from base symbol>
123 // and the offsets are not relocatable, so the fixup is fully resolved when
124 // addr(atom(A)) - addr(atom(B)) - addr(<base symbol>)) == 0.
125 //
126 // The simple (Darwin, except on x86_64) way of dealing with this was to
127 // assume that any reference to a temporary symbol *must* be a temporary
128 // symbol in the same atom, unless the sections differ. Therefore, any PCrel
129 // relocation to a temporary symbol (in the same section) is fully
130 // resolved. This also works in conjunction with absolutized .set, which
131 // requires the compiler to use .set to absolutize the differences between
132 // symbols which the compiler knows to be assembly time constants, so we don't
133 // need to worry about consider symbol differences fully resolved.
134
135 // Non-relative fixups are only resolved if constant.
136 if (!BaseSection)
137 return Target.isAbsolute();
138
139 // Otherwise, relative fixups are only resolved if not a difference and the
140 // target is a temporary in the same section.
141 if (Target.isAbsolute() || Target.getSymB())
142 return false;
143
144 const MCSymbol *A = &Target.getSymA()->getSymbol();
145 if (!A->isTemporary() || !A->isInSection() ||
146 &A->getSection() != BaseSection)
147 return false;
148
149 return true;
150}
151
Daniel Dunbar034843a2010-03-19 03:18:18 +0000152static bool isScatteredFixupFullyResolved(const MCAssembler &Asm,
153 const MCAsmFixup &Fixup,
154 const MCDataFragment *DF,
155 const MCValue Target,
156 const MCSymbolData *BaseSymbol) {
157 // The effective fixup address is
158 // addr(atom(A)) + offset(A)
159 // - addr(atom(B)) - offset(B)
160 // - addr(BaseSymbol) + <fixup offset from base symbol>
161 // and the offsets are not relocatable, so the fixup is fully resolved when
162 // addr(atom(A)) - addr(atom(B)) - addr(BaseSymbol) == 0.
163 //
164 // Note that "false" is almost always conservatively correct (it means we emit
165 // a relocation which is unnecessary), except when it would force us to emit a
166 // relocation which the target cannot encode.
167
168 const MCSymbolData *A_Base = 0, *B_Base = 0;
169 if (const MCSymbolRefExpr *A = Target.getSymA()) {
170 // Modified symbol references cannot be resolved.
171 if (A->getKind() != MCSymbolRefExpr::VK_None)
172 return false;
173
174 A_Base = Asm.getAtom(&Asm.getSymbolData(A->getSymbol()));
175 if (!A_Base)
176 return false;
177 }
178
179 if (const MCSymbolRefExpr *B = Target.getSymB()) {
180 // Modified symbol references cannot be resolved.
181 if (B->getKind() != MCSymbolRefExpr::VK_None)
182 return false;
183
184 B_Base = Asm.getAtom(&Asm.getSymbolData(B->getSymbol()));
185 if (!B_Base)
186 return false;
187 }
188
189 // If there is no base, A and B have to be the same atom for this fixup to be
190 // fully resolved.
191 if (!BaseSymbol)
192 return A_Base == B_Base;
193
194 // Otherwise, B must be missing and A must be the base.
195 return !B_Base && BaseSymbol == A_Base;
196}
197
Daniel Dunbar23869852010-03-19 03:18:09 +0000198bool MCAssembler::isSymbolLinkerVisible(const MCSymbolData *SD) const {
199 // Non-temporary labels should always be visible to the linker.
200 if (!SD->getSymbol().isTemporary())
201 return true;
202
203 // Absolute temporary labels are never visible.
204 if (!SD->getFragment())
205 return false;
206
207 // Otherwise, check if the section requires symbols even for temporary labels.
208 return getBackend().doesSectionRequireSymbols(
209 SD->getFragment()->getParent()->getSection());
210}
211
Daniel Dunbar8ad0dcc2010-03-19 03:18:15 +0000212const MCSymbolData *MCAssembler::getAtomForAddress(const MCSectionData *Section,
213 uint64_t Address) const {
214 const MCSymbolData *Best = 0;
215 for (MCAssembler::const_symbol_iterator it = symbol_begin(),
216 ie = symbol_end(); it != ie; ++it) {
217 // Ignore non-linker visible symbols.
218 if (!isSymbolLinkerVisible(it))
219 continue;
220
221 // Ignore symbols not in the same section.
222 if (!it->getFragment() || it->getFragment()->getParent() != Section)
223 continue;
224
225 // Otherwise, find the closest symbol preceding this address (ties are
226 // resolved in favor of the last defined symbol).
227 if (it->getAddress() <= Address &&
228 (!Best || it->getAddress() >= Best->getAddress()))
229 Best = it;
230 }
231
232 return Best;
233}
234
235const MCSymbolData *MCAssembler::getAtom(const MCSymbolData *SD) const {
236 // Linker visible symbols define atoms.
237 if (isSymbolLinkerVisible(SD))
238 return SD;
239
240 // Absolute and undefined symbols have no defining atom.
241 if (!SD->getFragment())
242 return 0;
243
244 // Otherwise, search by address.
245 return getAtomForAddress(SD->getFragment()->getParent(), SD->getAddress());
246}
247
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000248bool MCAssembler::EvaluateFixup(const MCAsmLayout &Layout, MCAsmFixup &Fixup,
249 MCDataFragment *DF,
250 MCValue &Target, uint64_t &Value) const {
251 if (!Fixup.Value->EvaluateAsRelocatable(Target, &Layout))
252 llvm_report_error("expected relocatable expression");
253
254 // FIXME: How do non-scattered symbols work in ELF? I presume the linker
255 // doesn't support small relocations, but then under what criteria does the
256 // assembler allow symbol differences?
257
258 Value = Target.getConstant();
259
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000260 bool IsResolved = true, IsPCRel = isFixupKindPCRel(Fixup.Kind);
Daniel Dunbar9a1d2002010-03-18 00:59:10 +0000261 if (const MCSymbolRefExpr *A = Target.getSymA()) {
262 if (A->getSymbol().isDefined())
263 Value += getSymbolData(A->getSymbol()).getAddress();
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000264 else
265 IsResolved = false;
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000266 }
Daniel Dunbar9a1d2002010-03-18 00:59:10 +0000267 if (const MCSymbolRefExpr *B = Target.getSymB()) {
268 if (B->getSymbol().isDefined())
269 Value -= getSymbolData(B->getSymbol()).getAddress();
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000270 else
271 IsResolved = false;
Daniel Dunbar939f8d72010-03-19 03:18:12 +0000272 }
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000273
Daniel Dunbar939f8d72010-03-19 03:18:12 +0000274 // If we are using scattered symbols, determine whether this value is actually
275 // resolved; scattering may cause atoms to move.
276 if (IsResolved && getBackend().hasScatteredSymbols()) {
277 if (getBackend().hasReliableSymbolDifference()) {
Daniel Dunbar034843a2010-03-19 03:18:18 +0000278 // If this is a PCrel relocation, find the base atom (identified by its
279 // symbol) that the fixup value is relative to.
280 const MCSymbolData *BaseSymbol = 0;
281 if (IsPCRel) {
282 BaseSymbol = getAtomForAddress(
283 DF->getParent(), DF->getAddress() + Fixup.Offset);
284 if (!BaseSymbol)
285 IsResolved = false;
286 }
287
288 if (IsResolved)
289 IsResolved = isScatteredFixupFullyResolved(*this, Fixup, DF, Target,
290 BaseSymbol);
Daniel Dunbar939f8d72010-03-19 03:18:12 +0000291 } else {
292 const MCSection *BaseSection = 0;
293 if (IsPCRel)
294 BaseSection = &DF->getParent()->getSection();
295
296 IsResolved = isScatteredFixupFullyResolvedSimple(*this, Fixup, DF, Target,
297 BaseSection);
298 }
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000299 }
300
301 if (IsPCRel)
Daniel Dunbarda3e9f72010-03-13 02:38:00 +0000302 Value -= DF->getAddress() + Fixup.Offset;
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000303
304 return IsResolved;
305}
306
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000307void MCAssembler::LayoutSection(MCSectionData &SD) {
Daniel Dunbar18ff2cc2010-03-11 05:53:33 +0000308 MCAsmLayout Layout(*this);
Daniel Dunbar6742e342009-08-26 04:13:32 +0000309 uint64_t Address = SD.getAddress();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000310
311 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
312 MCFragment &F = *it;
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000313
Daniel Dunbar6742e342009-08-26 04:13:32 +0000314 F.setOffset(Address - SD.getAddress());
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000315
316 // Evaluate fragment size.
317 switch (F.getKind()) {
318 case MCFragment::FT_Align: {
319 MCAlignFragment &AF = cast<MCAlignFragment>(F);
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000320
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000321 uint64_t Size = OffsetToAlignment(Address, AF.getAlignment());
Daniel Dunbar6742e342009-08-26 04:13:32 +0000322 if (Size > AF.getMaxBytesToEmit())
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000323 AF.setFileSize(0);
324 else
Daniel Dunbar6742e342009-08-26 04:13:32 +0000325 AF.setFileSize(Size);
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000326 break;
327 }
328
329 case MCFragment::FT_Data:
Daniel Dunbara4766d72010-02-13 09:28:32 +0000330 case MCFragment::FT_Fill:
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000331 F.setFileSize(F.getMaxFileSize());
332 break;
333
334 case MCFragment::FT_Org: {
335 MCOrgFragment &OF = cast<MCOrgFragment>(F);
336
Daniel Dunbar18ff2cc2010-03-11 05:53:33 +0000337 int64_t TargetLocation;
338 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, &Layout))
339 llvm_report_error("expected assembly-time absolute expression");
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000340
341 // FIXME: We need a way to communicate this error.
Daniel Dunbar18ff2cc2010-03-11 05:53:33 +0000342 int64_t Offset = TargetLocation - F.getOffset();
343 if (Offset < 0)
344 llvm_report_error("invalid .org offset '" + Twine(TargetLocation) +
345 "' (at offset '" + Twine(F.getOffset()) + "'");
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000346
Daniel Dunbar18ff2cc2010-03-11 05:53:33 +0000347 F.setFileSize(Offset);
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000348 break;
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000349 }
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000350
351 case MCFragment::FT_ZeroFill: {
352 MCZeroFillFragment &ZFF = cast<MCZeroFillFragment>(F);
353
354 // Align the fragment offset; it is safe to adjust the offset freely since
355 // this is only in virtual sections.
Daniel Dunbar37fad5c2010-03-08 21:10:42 +0000356 Address = RoundUpToAlignment(Address, ZFF.getAlignment());
357 F.setOffset(Address - SD.getAddress());
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000358
359 // FIXME: This is misnamed.
360 F.setFileSize(ZFF.getSize());
361 break;
362 }
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000363 }
364
Daniel Dunbar6742e342009-08-26 04:13:32 +0000365 Address += F.getFileSize();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000366 }
367
Daniel Dunbar6742e342009-08-26 04:13:32 +0000368 // Set the section sizes.
369 SD.setSize(Address - SD.getAddress());
Daniel Dunbarcc5b84c2010-03-19 09:29:03 +0000370 if (getBackend().isVirtualSection(SD.getSection()))
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000371 SD.setFileSize(0);
372 else
373 SD.setFileSize(Address - SD.getAddress());
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000374}
375
Kevin Enderby6e720482010-02-23 18:26:34 +0000376/// WriteNopData - Write optimal nops to the output file for the \arg Count
377/// bytes. This returns the number of bytes written. It may return 0 if
378/// the \arg Count is more than the maximum optimal nops.
379///
380/// FIXME this is X86 32-bit specific and should move to a better place.
Daniel Dunbarbdd92812010-03-19 09:28:55 +0000381static uint64_t WriteNopData(uint64_t Count, MCObjectWriter *OW) {
Kevin Enderby76687082010-02-23 21:41:24 +0000382 static const uint8_t Nops[16][16] = {
383 // nop
384 {0x90},
385 // xchg %ax,%ax
386 {0x66, 0x90},
387 // nopl (%[re]ax)
388 {0x0f, 0x1f, 0x00},
389 // nopl 0(%[re]ax)
390 {0x0f, 0x1f, 0x40, 0x00},
391 // nopl 0(%[re]ax,%[re]ax,1)
392 {0x0f, 0x1f, 0x44, 0x00, 0x00},
393 // nopw 0(%[re]ax,%[re]ax,1)
394 {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
395 // nopl 0L(%[re]ax)
396 {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
397 // nopl 0L(%[re]ax,%[re]ax,1)
398 {0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
399 // nopw 0L(%[re]ax,%[re]ax,1)
400 {0x66, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
401 // nopw %cs:0L(%[re]ax,%[re]ax,1)
402 {0x66, 0x2e, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
403 // nopl 0(%[re]ax,%[re]ax,1)
404 // nopw 0(%[re]ax,%[re]ax,1)
405 {0x0f, 0x1f, 0x44, 0x00, 0x00,
406 0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
407 // nopw 0(%[re]ax,%[re]ax,1)
408 // nopw 0(%[re]ax,%[re]ax,1)
409 {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00,
410 0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
411 // nopw 0(%[re]ax,%[re]ax,1)
412 // nopl 0L(%[re]ax) */
413 {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00,
414 0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
415 // nopl 0L(%[re]ax)
416 // nopl 0L(%[re]ax)
417 {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00,
418 0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
419 // nopl 0L(%[re]ax)
420 // nopl 0L(%[re]ax,%[re]ax,1)
421 {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00,
422 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00}
423 };
424
425 if (Count > 15)
426 return 0;
427
Kevin Enderby6e720482010-02-23 18:26:34 +0000428 for (uint64_t i = 0; i < Count; i++)
Daniel Dunbarbdd92812010-03-19 09:28:55 +0000429 OW->Write8(uint8_t(Nops[Count - 1][i]));
Kevin Enderby6e720482010-02-23 18:26:34 +0000430
431 return Count;
432}
433
Daniel Dunbar53b23382010-03-19 09:28:59 +0000434/// WriteFragmentData - Write the \arg F data to the output file.
435static void WriteFragmentData(const MCFragment &F, MCObjectWriter *OW) {
436 uint64_t Start = OW->getStream().tell();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000437 (void) Start;
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000438
Daniel Dunbar0adcd352009-08-25 21:10:45 +0000439 ++EmittedFragments;
440
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000441 // FIXME: Embed in fragments instead?
442 switch (F.getKind()) {
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000443 case MCFragment::FT_Align: {
444 MCAlignFragment &AF = cast<MCAlignFragment>(F);
445 uint64_t Count = AF.getFileSize() / AF.getValueSize();
446
447 // FIXME: This error shouldn't actually occur (the front end should emit
448 // multiple .align directives to enforce the semantics it wants), but is
449 // severe enough that we want to report it. How to handle this?
450 if (Count * AF.getValueSize() != AF.getFileSize())
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000451 llvm_report_error("undefined .align directive, value size '" +
452 Twine(AF.getValueSize()) +
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000453 "' is not a divisor of padding size '" +
454 Twine(AF.getFileSize()) + "'");
455
Kevin Enderby6e720482010-02-23 18:26:34 +0000456 // See if we are aligning with nops, and if so do that first to try to fill
457 // the Count bytes. Then if that did not fill any bytes or there are any
458 // bytes left to fill use the the Value and ValueSize to fill the rest.
459 if (AF.getEmitNops()) {
Daniel Dunbarbdd92812010-03-19 09:28:55 +0000460 uint64_t NopByteCount = WriteNopData(Count, OW);
Kevin Enderby6e720482010-02-23 18:26:34 +0000461 Count -= NopByteCount;
462 }
463
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000464 for (uint64_t i = 0; i != Count; ++i) {
465 switch (AF.getValueSize()) {
466 default:
467 assert(0 && "Invalid size!");
Daniel Dunbarbdd92812010-03-19 09:28:55 +0000468 case 1: OW->Write8 (uint8_t (AF.getValue())); break;
469 case 2: OW->Write16(uint16_t(AF.getValue())); break;
470 case 4: OW->Write32(uint32_t(AF.getValue())); break;
471 case 8: OW->Write64(uint64_t(AF.getValue())); break;
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000472 }
473 }
474 break;
475 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000476
Daniel Dunbar3a30b822010-02-13 09:28:15 +0000477 case MCFragment::FT_Data: {
Daniel Dunbar53b23382010-03-19 09:28:59 +0000478 OW->WriteBytes(cast<MCDataFragment>(F).getContents().str());
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000479 break;
Daniel Dunbar3a30b822010-02-13 09:28:15 +0000480 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000481
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000482 case MCFragment::FT_Fill: {
483 MCFillFragment &FF = cast<MCFillFragment>(F);
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000484 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
485 switch (FF.getValueSize()) {
486 default:
487 assert(0 && "Invalid size!");
Daniel Dunbarbdd92812010-03-19 09:28:55 +0000488 case 1: OW->Write8 (uint8_t (FF.getValue())); break;
489 case 2: OW->Write16(uint16_t(FF.getValue())); break;
490 case 4: OW->Write32(uint32_t(FF.getValue())); break;
491 case 8: OW->Write64(uint64_t(FF.getValue())); break;
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000492 }
493 }
494 break;
495 }
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000496
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000497 case MCFragment::FT_Org: {
498 MCOrgFragment &OF = cast<MCOrgFragment>(F);
499
500 for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
Daniel Dunbarbdd92812010-03-19 09:28:55 +0000501 OW->Write8(uint8_t(OF.getValue()));
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000502
503 break;
504 }
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000505
506 case MCFragment::FT_ZeroFill: {
507 assert(0 && "Invalid zero fill fragment in concrete section!");
508 break;
509 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000510 }
511
Daniel Dunbar53b23382010-03-19 09:28:59 +0000512 assert(OW->getStream().tell() - Start == F.getFileSize());
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000513}
514
Daniel Dunbar53b23382010-03-19 09:28:59 +0000515void MCAssembler::WriteSectionData(const MCSectionData *SD,
516 MCObjectWriter *OW) const {
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000517 // Ignore virtual sections.
Daniel Dunbarcc5b84c2010-03-19 09:29:03 +0000518 if (getBackend().isVirtualSection(SD->getSection())) {
Daniel Dunbar53b23382010-03-19 09:28:59 +0000519 assert(SD->getFileSize() == 0);
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000520 return;
521 }
522
Daniel Dunbar53b23382010-03-19 09:28:59 +0000523 uint64_t Start = OW->getStream().tell();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000524 (void) Start;
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000525
Daniel Dunbar53b23382010-03-19 09:28:59 +0000526 for (MCSectionData::const_iterator it = SD->begin(),
527 ie = SD->end(); it != ie; ++it)
528 WriteFragmentData(*it, OW);
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000529
Daniel Dunbar6742e342009-08-26 04:13:32 +0000530 // Add section padding.
Daniel Dunbar53b23382010-03-19 09:28:59 +0000531 assert(SD->getFileSize() >= SD->getSize() && "Invalid section sizes!");
532 OW->WriteZeros(SD->getFileSize() - SD->getSize());
Daniel Dunbar6742e342009-08-26 04:13:32 +0000533
Daniel Dunbar53b23382010-03-19 09:28:59 +0000534 assert(OW->getStream().tell() - Start == SD->getFileSize());
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000535}
536
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000537void MCAssembler::Finish() {
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000538 DEBUG_WITH_TYPE("mc-dump", {
539 llvm::errs() << "assembler backend - pre-layout\n--\n";
540 dump(); });
541
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000542 // Layout until everything fits.
543 while (LayoutOnce())
544 continue;
545
546 DEBUG_WITH_TYPE("mc-dump", {
547 llvm::errs() << "assembler backend - post-layout\n--\n";
548 dump(); });
549
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000550 // FIXME: Factor out MCObjectWriter.
551 bool Is64Bit = StringRef(getBackend().getTarget().getName()) == "x86-64";
552 MachObjectWriter MOW(OS, Is64Bit);
Daniel Dunbarbacba992010-03-19 07:09:33 +0000553
554 // Allow the object writer a chance to perform post-layout binding (for
555 // example, to set the index fields in the symbol data).
556 MOW.ExecutePostLayoutBinding(*this);
557
Daniel Dunbarb1e98942010-03-19 07:09:47 +0000558 // Evaluate and apply the fixups, generating relocation entries as necessary.
Daniel Dunbarbdd92812010-03-19 09:28:55 +0000559 //
560 // FIXME: Share layout object.
Daniel Dunbarb1e98942010-03-19 07:09:47 +0000561 MCAsmLayout Layout(*this);
562 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
563 for (MCSectionData::iterator it2 = it->begin(),
564 ie2 = it->end(); it2 != ie2; ++it2) {
565 MCDataFragment *DF = dyn_cast<MCDataFragment>(it2);
566 if (!DF)
567 continue;
568
569 for (MCDataFragment::fixup_iterator it3 = DF->fixup_begin(),
570 ie3 = DF->fixup_end(); it3 != ie3; ++it3) {
571 MCAsmFixup &Fixup = *it3;
572
573 // Evaluate the fixup.
574 MCValue Target;
575 uint64_t FixedValue;
576 if (!EvaluateFixup(Layout, Fixup, DF, Target, FixedValue)) {
577 // The fixup was unresolved, we need a relocation. Inform the object
578 // writer of the relocation, and give it an opportunity to adjust the
579 // fixup value if need be.
580 MOW.RecordRelocation(*this, *DF, Fixup, Target, FixedValue);
581 }
582
Daniel Dunbar87190c42010-03-19 09:28:12 +0000583 getBackend().ApplyFixup(Fixup, *DF, FixedValue);
Daniel Dunbarb1e98942010-03-19 07:09:47 +0000584 }
585 }
586 }
587
Daniel Dunbarbacba992010-03-19 07:09:33 +0000588 // Write the object file.
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000589 MOW.WriteObject(*this);
590
591 OS.flush();
592}
593
594bool MCAssembler::FixupNeedsRelaxation(MCAsmFixup &Fixup, MCDataFragment *DF) {
595 // FIXME: Share layout object.
596 MCAsmLayout Layout(*this);
597
598 // Currently we only need to relax X86::reloc_pcrel_1byte.
599 if (unsigned(Fixup.Kind) != X86::reloc_pcrel_1byte)
600 return false;
601
602 // If we cannot resolve the fixup value, it requires relaxation.
603 MCValue Target;
604 uint64_t Value;
605 if (!EvaluateFixup(Layout, Fixup, DF, Target, Value))
606 return true;
607
608 // Otherwise, relax if the value is too big for a (signed) i8.
609 return int64_t(Value) != int64_t(int8_t(Value));
610}
611
612bool MCAssembler::LayoutOnce() {
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000613 // Layout the concrete sections and fragments.
Daniel Dunbar5e835962009-08-26 02:48:04 +0000614 uint64_t Address = 0;
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000615 MCSectionData *Prev = 0;
616 for (iterator it = begin(), ie = end(); it != ie; ++it) {
Daniel Dunbar6742e342009-08-26 04:13:32 +0000617 MCSectionData &SD = *it;
618
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000619 // Skip virtual sections.
Daniel Dunbarcc5b84c2010-03-19 09:29:03 +0000620 if (getBackend().isVirtualSection(SD.getSection()))
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000621 continue;
622
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000623 // Align this section if necessary by adding padding bytes to the previous
624 // section.
625 if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment())) {
626 assert(Prev && "Missing prev section!");
627 Prev->setFileSize(Prev->getFileSize() + Pad);
628 Address += Pad;
629 }
Daniel Dunbar6742e342009-08-26 04:13:32 +0000630
631 // Layout the section fragments and its size.
632 SD.setAddress(Address);
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000633 LayoutSection(SD);
Daniel Dunbar6742e342009-08-26 04:13:32 +0000634 Address += SD.getFileSize();
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000635
636 Prev = &SD;
Daniel Dunbar5e835962009-08-26 02:48:04 +0000637 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000638
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000639 // Layout the virtual sections.
640 for (iterator it = begin(), ie = end(); it != ie; ++it) {
641 MCSectionData &SD = *it;
642
Daniel Dunbarcc5b84c2010-03-19 09:29:03 +0000643 if (!getBackend().isVirtualSection(SD.getSection()))
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000644 continue;
645
Daniel Dunbarb2b4acd2010-03-08 22:03:42 +0000646 // Align this section if necessary by adding padding bytes to the previous
647 // section.
Daniel Dunbarf8b8ad72010-03-09 01:12:20 +0000648 if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment()))
Daniel Dunbarb2b4acd2010-03-08 22:03:42 +0000649 Address += Pad;
Daniel Dunbarb2b4acd2010-03-08 22:03:42 +0000650
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000651 SD.setAddress(Address);
652 LayoutSection(SD);
653 Address += SD.getSize();
654 }
655
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000656 // Scan the fixups in order and relax any that don't fit.
657 for (iterator it = begin(), ie = end(); it != ie; ++it) {
658 MCSectionData &SD = *it;
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000659
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000660 for (MCSectionData::iterator it2 = SD.begin(),
661 ie2 = SD.end(); it2 != ie2; ++it2) {
662 MCDataFragment *DF = dyn_cast<MCDataFragment>(it2);
663 if (!DF)
664 continue;
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000665
Daniel Dunbarf08fde42010-03-12 22:07:14 +0000666 for (MCDataFragment::fixup_iterator it3 = DF->fixup_begin(),
667 ie3 = DF->fixup_end(); it3 != ie3; ++it3) {
668 MCAsmFixup &Fixup = *it3;
669
670 // Check whether we need to relax this fixup.
671 if (!FixupNeedsRelaxation(Fixup, DF))
672 continue;
673
674 // Relax the instruction.
675 //
676 // FIXME: This is a huge temporary hack which just looks for x86
677 // branches; the only thing we need to relax on x86 is
678 // 'X86::reloc_pcrel_1byte'. Once we have MCInst fragments, this will be
679 // replaced by a TargetAsmBackend hook (most likely tblgen'd) to relax
680 // an individual MCInst.
681 SmallVectorImpl<char> &C = DF->getContents();
682 uint64_t PrevOffset = Fixup.Offset;
683 unsigned Amt = 0;
684
685 // jcc instructions
686 if (unsigned(C[Fixup.Offset-1]) >= 0x70 &&
687 unsigned(C[Fixup.Offset-1]) <= 0x7f) {
688 C[Fixup.Offset] = C[Fixup.Offset-1] + 0x10;
689 C[Fixup.Offset-1] = char(0x0f);
690 ++Fixup.Offset;
691 Amt = 4;
692
693 // jmp rel8
694 } else if (C[Fixup.Offset-1] == char(0xeb)) {
695 C[Fixup.Offset-1] = char(0xe9);
696 Amt = 3;
697
698 } else
699 llvm_unreachable("unknown 1 byte pcrel instruction!");
700
701 Fixup.Value = MCBinaryExpr::Create(
702 MCBinaryExpr::Sub, Fixup.Value,
703 MCConstantExpr::Create(3, getContext()),
704 getContext());
705 C.insert(C.begin() + Fixup.Offset, Amt, char(0));
706 Fixup.Kind = MCFixupKind(X86::reloc_pcrel_4byte);
707
708 // Update the remaining fixups, which have slid.
709 //
710 // FIXME: This is bad for performance, but will be eliminated by the
711 // move to MCInst specific fragments.
712 ++it3;
713 for (; it3 != ie3; ++it3)
714 it3->Offset += Amt;
715
716 // Update all the symbols for this fragment, which may have slid.
717 //
718 // FIXME: This is really really bad for performance, but will be
719 // eliminated by the move to MCInst specific fragments.
720 for (MCAssembler::symbol_iterator it = symbol_begin(),
721 ie = symbol_end(); it != ie; ++it) {
722 MCSymbolData &SD = *it;
723
724 if (it->getFragment() != DF)
725 continue;
726
727 if (SD.getOffset() > PrevOffset)
728 SD.setOffset(SD.getOffset() + Amt);
729 }
730
731 // Restart layout.
732 //
733 // FIXME: This is O(N^2), but will be eliminated once we have a smart
734 // MCAsmLayout object.
735 return true;
736 }
737 }
738 }
739
740 return false;
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000741}
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000742
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000743// Debugging methods
744
745namespace llvm {
746
747raw_ostream &operator<<(raw_ostream &OS, const MCAsmFixup &AF) {
Daniel Dunbar2be2fd02010-02-13 09:28:54 +0000748 OS << "<MCAsmFixup" << " Offset:" << AF.Offset << " Value:" << *AF.Value
749 << " Kind:" << AF.Kind << ">";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000750 return OS;
751}
752
753}
754
755void MCFragment::dump() {
756 raw_ostream &OS = llvm::errs();
757
758 OS << "<MCFragment " << (void*) this << " Offset:" << Offset
759 << " FileSize:" << FileSize;
760
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000761 OS << ">";
762}
763
764void MCAlignFragment::dump() {
765 raw_ostream &OS = llvm::errs();
766
767 OS << "<MCAlignFragment ";
768 this->MCFragment::dump();
769 OS << "\n ";
770 OS << " Alignment:" << getAlignment()
771 << " Value:" << getValue() << " ValueSize:" << getValueSize()
772 << " MaxBytesToEmit:" << getMaxBytesToEmit() << ">";
773}
774
775void MCDataFragment::dump() {
776 raw_ostream &OS = llvm::errs();
777
778 OS << "<MCDataFragment ";
779 this->MCFragment::dump();
780 OS << "\n ";
781 OS << " Contents:[";
782 for (unsigned i = 0, e = getContents().size(); i != e; ++i) {
783 if (i) OS << ",";
784 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
785 }
Daniel Dunbar2be2fd02010-02-13 09:28:54 +0000786 OS << "] (" << getContents().size() << " bytes)";
Daniel Dunbar0bcf0742010-02-13 09:28:43 +0000787
788 if (!getFixups().empty()) {
789 OS << ",\n ";
790 OS << " Fixups:[";
791 for (fixup_iterator it = fixup_begin(), ie = fixup_end(); it != ie; ++it) {
Daniel Dunbar45aefff2010-03-09 01:12:23 +0000792 if (it != fixup_begin()) OS << ",\n ";
Daniel Dunbar0bcf0742010-02-13 09:28:43 +0000793 OS << *it;
794 }
795 OS << "]";
796 }
797
798 OS << ">";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000799}
800
801void MCFillFragment::dump() {
802 raw_ostream &OS = llvm::errs();
803
804 OS << "<MCFillFragment ";
805 this->MCFragment::dump();
806 OS << "\n ";
807 OS << " Value:" << getValue() << " ValueSize:" << getValueSize()
808 << " Count:" << getCount() << ">";
809}
810
811void MCOrgFragment::dump() {
812 raw_ostream &OS = llvm::errs();
813
814 OS << "<MCOrgFragment ";
815 this->MCFragment::dump();
816 OS << "\n ";
817 OS << " Offset:" << getOffset() << " Value:" << getValue() << ">";
818}
819
820void MCZeroFillFragment::dump() {
821 raw_ostream &OS = llvm::errs();
822
823 OS << "<MCZeroFillFragment ";
824 this->MCFragment::dump();
825 OS << "\n ";
826 OS << " Size:" << getSize() << " Alignment:" << getAlignment() << ">";
827}
828
829void MCSectionData::dump() {
830 raw_ostream &OS = llvm::errs();
831
832 OS << "<MCSectionData";
833 OS << " Alignment:" << getAlignment() << " Address:" << Address
834 << " Size:" << Size << " FileSize:" << FileSize
Daniel Dunbar45aefff2010-03-09 01:12:23 +0000835 << " Fragments:[\n ";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000836 for (iterator it = begin(), ie = end(); it != ie; ++it) {
837 if (it != begin()) OS << ",\n ";
838 it->dump();
839 }
840 OS << "]>";
841}
842
843void MCSymbolData::dump() {
844 raw_ostream &OS = llvm::errs();
845
846 OS << "<MCSymbolData Symbol:" << getSymbol()
847 << " Fragment:" << getFragment() << " Offset:" << getOffset()
848 << " Flags:" << getFlags() << " Index:" << getIndex();
849 if (isCommon())
850 OS << " (common, size:" << getCommonSize()
851 << " align: " << getCommonAlignment() << ")";
852 if (isExternal())
853 OS << " (external)";
854 if (isPrivateExtern())
855 OS << " (private extern)";
856 OS << ">";
857}
858
859void MCAssembler::dump() {
860 raw_ostream &OS = llvm::errs();
861
862 OS << "<MCAssembler\n";
Daniel Dunbar45aefff2010-03-09 01:12:23 +0000863 OS << " Sections:[\n ";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000864 for (iterator it = begin(), ie = end(); it != ie; ++it) {
865 if (it != begin()) OS << ",\n ";
866 it->dump();
867 }
868 OS << "],\n";
869 OS << " Symbols:[";
870
871 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
Daniel Dunbar45aefff2010-03-09 01:12:23 +0000872 if (it != symbol_begin()) OS << ",\n ";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +0000873 it->dump();
874 }
875 OS << "]>\n";
876}