blob: dae2d9336cbb5f99f9e9b6d5198aecad6158257b [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"
Chris Lattnerbea2c952009-08-22 19:19:12 +000014#include "llvm/MC/MCSectionMachO.h"
Daniel Dunbar1253a6f2009-10-16 01:58:03 +000015#include "llvm/MC/MCSymbol.h"
16#include "llvm/MC/MCValue.h"
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +000017#include "llvm/ADT/DenseMap.h"
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000018#include "llvm/ADT/SmallString.h"
Daniel Dunbar0adcd352009-08-25 21:10:45 +000019#include "llvm/ADT/Statistic.h"
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +000020#include "llvm/ADT/StringExtras.h"
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000021#include "llvm/ADT/StringMap.h"
Daniel Dunbard6f761e2009-08-21 23:07:38 +000022#include "llvm/ADT/Twine.h"
Daniel Dunbar0705fbf2009-08-21 18:29:01 +000023#include "llvm/Support/ErrorHandling.h"
Chris Lattner45f8c092010-02-02 19:38:14 +000024#include "llvm/Support/MachO.h"
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000025#include "llvm/Support/raw_ostream.h"
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +000026#include "llvm/Support/Debug.h"
Daniel Dunbaree0d8922010-03-13 22:10:17 +000027#include "llvm/Target/TargetRegistry.h"
Daniel Dunbardf3c8f22010-03-12 21:00:49 +000028#include "llvm/Target/TargetAsmBackend.h"
Daniel Dunbarf6346762010-02-13 09:29:02 +000029
30// FIXME: Gross.
31#include "../Target/X86/X86FixupKinds.h"
32
Chris Lattner23132b12009-08-24 03:52:50 +000033#include <vector>
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000034using namespace llvm;
35
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000036class MachObjectWriter;
37
Daniel Dunbar0adcd352009-08-25 21:10:45 +000038STATISTIC(EmittedFragments, "Number of emitted assembler fragments");
39
Daniel Dunbar8f4d1462009-08-28 07:08:35 +000040// FIXME FIXME FIXME: There are number of places in this file where we convert
41// what is a 64-bit assembler value used for computation into a value in the
42// object file, which may truncate it. We should detect that truncation where
43// invalid and report errors back.
44
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000045static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
46 MachObjectWriter &MOW);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000047
Kevin Enderby6e720482010-02-23 18:26:34 +000048static uint64_t WriteNopData(uint64_t Count, MachObjectWriter &MOW);
49
Daniel Dunbard5a8e982009-08-28 05:49:21 +000050/// isVirtualSection - Check if this is a section which does not actually exist
51/// in the object file.
52static bool isVirtualSection(const MCSection &Section) {
53 // FIXME: Lame.
54 const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
55 unsigned Type = SMO.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
56 return (Type == MCSectionMachO::S_ZEROFILL);
57}
58
Duncan Sands9a7795c2010-02-17 14:52:22 +000059static unsigned getFixupKindLog2Size(unsigned Kind) {
Daniel Dunbar2be2fd02010-02-13 09:28:54 +000060 switch (Kind) {
61 default: llvm_unreachable("invalid fixup kind!");
Daniel Dunbarf6346762010-02-13 09:29:02 +000062 case X86::reloc_pcrel_1byte:
Daniel Dunbar2be2fd02010-02-13 09:28:54 +000063 case FK_Data_1: return 0;
64 case FK_Data_2: return 1;
Daniel Dunbarf6346762010-02-13 09:29:02 +000065 case X86::reloc_pcrel_4byte:
66 case X86::reloc_riprel_4byte:
Daniel Dunbar2be2fd02010-02-13 09:28:54 +000067 case FK_Data_4: return 2;
68 case FK_Data_8: return 3;
69 }
70}
71
Duncan Sands9a7795c2010-02-17 14:52:22 +000072static bool isFixupKindPCRel(unsigned Kind) {
Daniel Dunbar591047f2010-02-13 09:45:59 +000073 switch (Kind) {
74 default:
75 return false;
76 case X86::reloc_pcrel_1byte:
77 case X86::reloc_pcrel_4byte:
78 case X86::reloc_riprel_4byte:
79 return true;
80 }
81}
82
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000083class MachObjectWriter {
84 // See <mach-o/loader.h>.
85 enum {
86 Header_Magic32 = 0xFEEDFACE,
87 Header_Magic64 = 0xFEEDFACF
88 };
Daniel Dunbar7eb85192009-10-16 01:58:15 +000089
Daniel Dunbaree0d8922010-03-13 22:10:17 +000090 enum {
91 Header32Size = 28,
92 Header64Size = 32,
93 SegmentLoadCommand32Size = 56,
94 SegmentLoadCommand64Size = 72,
95 Section32Size = 68,
96 Section64Size = 80,
97 SymtabLoadCommandSize = 24,
98 DysymtabLoadCommandSize = 80,
99 Nlist32Size = 12,
100 Nlist64Size = 16,
101 RelocationInfoSize = 8
102 };
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000103
104 enum HeaderFileType {
105 HFT_Object = 0x1
106 };
107
Daniel Dunbar6009db42009-08-26 21:22:22 +0000108 enum HeaderFlags {
109 HF_SubsectionsViaSymbols = 0x2000
110 };
111
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000112 enum LoadCommandType {
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000113 LCT_Segment = 0x1,
114 LCT_Symtab = 0x2,
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000115 LCT_Dysymtab = 0xb,
116 LCT_Segment64 = 0x19
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000117 };
118
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000119 // See <mach-o/nlist.h>.
120 enum SymbolTypeType {
121 STT_Undefined = 0x00,
122 STT_Absolute = 0x02,
123 STT_Section = 0x0e
124 };
125
126 enum SymbolTypeFlags {
127 // If any of these bits are set, then the entry is a stab entry number (see
128 // <mach-o/stab.h>. Otherwise the other masks apply.
129 STF_StabsEntryMask = 0xe0,
130
131 STF_TypeMask = 0x0e,
132 STF_External = 0x01,
133 STF_PrivateExtern = 0x10
134 };
135
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000136 /// IndirectSymbolFlags - Flags for encoding special values in the indirect
137 /// symbol entry.
138 enum IndirectSymbolFlags {
139 ISF_Local = 0x80000000,
140 ISF_Absolute = 0x40000000
141 };
142
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000143 /// RelocationFlags - Special flags for addresses.
144 enum RelocationFlags {
145 RF_Scattered = 0x80000000
146 };
147
148 enum RelocationInfoType {
149 RIT_Vanilla = 0,
150 RIT_Pair = 1,
151 RIT_Difference = 2,
152 RIT_PreboundLazyPointer = 3,
153 RIT_LocalDifference = 4
154 };
155
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000156 /// MachSymbolData - Helper struct for containing some precomputed information
157 /// on symbols.
158 struct MachSymbolData {
159 MCSymbolData *SymbolData;
160 uint64_t StringIndex;
161 uint8_t SectionIndex;
162
163 // Support lexicographic sorting.
164 bool operator<(const MachSymbolData &RHS) const {
165 const std::string &Name = SymbolData->getSymbol().getName();
166 return Name < RHS.SymbolData->getSymbol().getName();
167 }
168 };
169
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000170 raw_ostream &OS;
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000171 unsigned Is64Bit : 1;
172 unsigned IsLSB : 1;
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000173
174public:
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000175 MachObjectWriter(raw_ostream &_OS, bool _Is64Bit, bool _IsLSB = true)
176 : OS(_OS), Is64Bit(_Is64Bit), IsLSB(_IsLSB) {
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000177 }
178
179 /// @name Helper Methods
180 /// @{
181
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000182 void Write8(uint8_t Value) {
183 OS << char(Value);
184 }
185
186 void Write16(uint16_t Value) {
187 if (IsLSB) {
188 Write8(uint8_t(Value >> 0));
189 Write8(uint8_t(Value >> 8));
190 } else {
191 Write8(uint8_t(Value >> 8));
192 Write8(uint8_t(Value >> 0));
193 }
194 }
195
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000196 void Write32(uint32_t Value) {
197 if (IsLSB) {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000198 Write16(uint16_t(Value >> 0));
199 Write16(uint16_t(Value >> 16));
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000200 } else {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000201 Write16(uint16_t(Value >> 16));
202 Write16(uint16_t(Value >> 0));
203 }
204 }
205
206 void Write64(uint64_t Value) {
207 if (IsLSB) {
208 Write32(uint32_t(Value >> 0));
209 Write32(uint32_t(Value >> 32));
210 } else {
211 Write32(uint32_t(Value >> 32));
212 Write32(uint32_t(Value >> 0));
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000213 }
214 }
215
216 void WriteZeros(unsigned N) {
217 const char Zeros[16] = { 0 };
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000218
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000219 for (unsigned i = 0, e = N / 16; i != e; ++i)
220 OS << StringRef(Zeros, 16);
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000221
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000222 OS << StringRef(Zeros, N % 16);
223 }
224
Daniel Dunbar2928c832009-11-06 10:58:06 +0000225 void WriteString(StringRef Str, unsigned ZeroFillSize = 0) {
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000226 OS << Str;
227 if (ZeroFillSize)
228 WriteZeros(ZeroFillSize - Str.size());
229 }
230
231 /// @}
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000232
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000233 void WriteHeader(unsigned NumLoadCommands, unsigned LoadCommandsSize,
234 bool SubsectionsViaSymbols) {
Daniel Dunbar6009db42009-08-26 21:22:22 +0000235 uint32_t Flags = 0;
236
237 if (SubsectionsViaSymbols)
238 Flags |= HF_SubsectionsViaSymbols;
239
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000240 // struct mach_header (28 bytes) or
241 // struct mach_header_64 (32 bytes)
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000242
243 uint64_t Start = OS.tell();
244 (void) Start;
245
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000246 Write32(Is64Bit ? Header_Magic64 : Header_Magic32);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000247
248 // FIXME: Support cputype.
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000249 Write32(Is64Bit ? MachO::CPUTypeX86_64 : MachO::CPUTypeI386);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000250 // FIXME: Support cpusubtype.
Chris Lattner45f8c092010-02-02 19:38:14 +0000251 Write32(MachO::CPUSubType_I386_ALL);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000252 Write32(HFT_Object);
Daniel Dunbar6009db42009-08-26 21:22:22 +0000253 Write32(NumLoadCommands); // Object files have a single load command, the
254 // segment.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000255 Write32(LoadCommandsSize);
Daniel Dunbar6009db42009-08-26 21:22:22 +0000256 Write32(Flags);
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000257 if (Is64Bit)
258 Write32(0); // reserved
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000259
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000260 assert(OS.tell() - Start == Is64Bit ? Header64Size : Header32Size);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000261 }
262
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000263 /// WriteSegmentLoadCommand - Write a segment load command.
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000264 ///
265 /// \arg NumSections - The number of sections in this segment.
266 /// \arg SectionDataSize - The total size of the sections.
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000267 void WriteSegmentLoadCommand(unsigned NumSections,
268 uint64_t VMSize,
269 uint64_t SectionDataStartOffset,
270 uint64_t SectionDataSize) {
271 // struct segment_command (56 bytes) or
272 // struct segment_command_64 (72 bytes)
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000273
274 uint64_t Start = OS.tell();
275 (void) Start;
276
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000277 unsigned SegmentLoadCommandSize = Is64Bit ? SegmentLoadCommand64Size :
278 SegmentLoadCommand32Size;
279 Write32(Is64Bit ? LCT_Segment64 : LCT_Segment);
280 Write32(SegmentLoadCommandSize +
281 NumSections * (Is64Bit ? Section64Size : Section32Size));
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000282
283 WriteString("", 16);
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000284 if (Is64Bit) {
285 Write64(0); // vmaddr
286 Write64(VMSize); // vmsize
287 Write64(SectionDataStartOffset); // file offset
288 Write64(SectionDataSize); // file size
289 } else {
290 Write32(0); // vmaddr
291 Write32(VMSize); // vmsize
292 Write32(SectionDataStartOffset); // file offset
293 Write32(SectionDataSize); // file size
294 }
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000295 Write32(0x7); // maxprot
296 Write32(0x7); // initprot
297 Write32(NumSections);
298 Write32(0); // flags
299
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000300 assert(OS.tell() - Start == SegmentLoadCommandSize);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000301 }
302
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000303 void WriteSection(const MCSectionData &SD, uint64_t FileOffset,
304 uint64_t RelocationsStart, unsigned NumRelocations) {
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000305 // The offset is unused for virtual sections.
306 if (isVirtualSection(SD.getSection())) {
307 assert(SD.getFileSize() == 0 && "Invalid file size!");
308 FileOffset = 0;
309 }
310
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000311 // struct section (68 bytes) or
312 // struct section_64 (80 bytes)
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000313
314 uint64_t Start = OS.tell();
315 (void) Start;
316
317 // FIXME: cast<> support!
318 const MCSectionMachO &Section =
319 static_cast<const MCSectionMachO&>(SD.getSection());
320 WriteString(Section.getSectionName(), 16);
321 WriteString(Section.getSegmentName(), 16);
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000322 if (Is64Bit) {
323 Write64(SD.getAddress()); // address
324 Write64(SD.getSize()); // size
325 } else {
326 Write32(SD.getAddress()); // address
327 Write32(SD.getSize()); // size
328 }
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000329 Write32(FileOffset);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000330
Daniel Dunbare1ec6172010-02-02 21:44:01 +0000331 unsigned Flags = Section.getTypeAndAttributes();
332 if (SD.hasInstructions())
333 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
334
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000335 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
336 Write32(Log2_32(SD.getAlignment()));
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000337 Write32(NumRelocations ? RelocationsStart : 0);
338 Write32(NumRelocations);
Daniel Dunbare1ec6172010-02-02 21:44:01 +0000339 Write32(Flags);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000340 Write32(0); // reserved1
341 Write32(Section.getStubSize()); // reserved2
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000342 if (Is64Bit)
343 Write32(0); // reserved3
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000344
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000345 assert(OS.tell() - Start == Is64Bit ? Section64Size : Section32Size);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000346 }
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000347
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000348 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
349 uint32_t StringTableOffset,
350 uint32_t StringTableSize) {
351 // struct symtab_command (24 bytes)
352
353 uint64_t Start = OS.tell();
354 (void) Start;
355
356 Write32(LCT_Symtab);
357 Write32(SymtabLoadCommandSize);
358 Write32(SymbolOffset);
359 Write32(NumSymbols);
360 Write32(StringTableOffset);
361 Write32(StringTableSize);
362
363 assert(OS.tell() - Start == SymtabLoadCommandSize);
364 }
365
366 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
367 uint32_t NumLocalSymbols,
368 uint32_t FirstExternalSymbol,
369 uint32_t NumExternalSymbols,
370 uint32_t FirstUndefinedSymbol,
371 uint32_t NumUndefinedSymbols,
372 uint32_t IndirectSymbolOffset,
373 uint32_t NumIndirectSymbols) {
374 // struct dysymtab_command (80 bytes)
375
376 uint64_t Start = OS.tell();
377 (void) Start;
378
379 Write32(LCT_Dysymtab);
380 Write32(DysymtabLoadCommandSize);
381 Write32(FirstLocalSymbol);
382 Write32(NumLocalSymbols);
383 Write32(FirstExternalSymbol);
384 Write32(NumExternalSymbols);
385 Write32(FirstUndefinedSymbol);
386 Write32(NumUndefinedSymbols);
387 Write32(0); // tocoff
388 Write32(0); // ntoc
389 Write32(0); // modtaboff
390 Write32(0); // nmodtab
391 Write32(0); // extrefsymoff
392 Write32(0); // nextrefsyms
393 Write32(IndirectSymbolOffset);
394 Write32(NumIndirectSymbols);
395 Write32(0); // extreloff
396 Write32(0); // nextrel
397 Write32(0); // locreloff
398 Write32(0); // nlocrel
399
400 assert(OS.tell() - Start == DysymtabLoadCommandSize);
401 }
402
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000403 void WriteNlist32(MachSymbolData &MSD) {
Daniel Dunbar5e835962009-08-26 02:48:04 +0000404 MCSymbolData &Data = *MSD.SymbolData;
Daniel Dunbarcb579b32009-08-31 08:08:06 +0000405 const MCSymbol &Symbol = Data.getSymbol();
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000406 uint8_t Type = 0;
Daniel Dunbar8f4d1462009-08-28 07:08:35 +0000407 uint16_t Flags = Data.getFlags();
408 uint32_t Address = 0;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000409
410 // Set the N_TYPE bits. See <mach-o/nlist.h>.
411 //
412 // FIXME: Are the prebound or indirect fields possible here?
413 if (Symbol.isUndefined())
414 Type = STT_Undefined;
415 else if (Symbol.isAbsolute())
416 Type = STT_Absolute;
417 else
418 Type = STT_Section;
419
420 // FIXME: Set STAB bits.
421
Daniel Dunbar5e835962009-08-26 02:48:04 +0000422 if (Data.isPrivateExtern())
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000423 Type |= STF_PrivateExtern;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000424
425 // Set external bit.
Daniel Dunbar5e835962009-08-26 02:48:04 +0000426 if (Data.isExternal() || Symbol.isUndefined())
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000427 Type |= STF_External;
428
Daniel Dunbar8f4d1462009-08-28 07:08:35 +0000429 // Compute the symbol address.
430 if (Symbol.isDefined()) {
431 if (Symbol.isAbsolute()) {
432 llvm_unreachable("FIXME: Not yet implemented!");
433 } else {
Daniel Dunbar8f0448c2010-03-11 18:22:51 +0000434 Address = Data.getAddress();
Daniel Dunbar8f4d1462009-08-28 07:08:35 +0000435 }
436 } else if (Data.isCommon()) {
437 // Common symbols are encoded with the size in the address
438 // field, and their alignment in the flags.
439 Address = Data.getCommonSize();
440
441 // Common alignment is packed into the 'desc' bits.
442 if (unsigned Align = Data.getCommonAlignment()) {
443 unsigned Log2Size = Log2_32(Align);
444 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
445 if (Log2Size > 15)
446 llvm_report_error("invalid 'common' alignment '" +
447 Twine(Align) + "'");
448 // FIXME: Keep this mask with the SymbolFlags enumeration.
449 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
450 }
451 }
452
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000453 // struct nlist (12 bytes)
454
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000455 Write32(MSD.StringIndex);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000456 Write8(Type);
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000457 Write8(MSD.SectionIndex);
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000458
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000459 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
460 // value.
Daniel Dunbar8f4d1462009-08-28 07:08:35 +0000461 Write16(Flags);
Daniel Dunbar5e835962009-08-26 02:48:04 +0000462 Write32(Address);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000463 }
464
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000465 struct MachRelocationEntry {
466 uint32_t Word0;
467 uint32_t Word1;
468 };
Daniel Dunbarcb7d7432010-02-11 21:29:46 +0000469 void ComputeScatteredRelocationInfo(MCAssembler &Asm, MCFragment &Fragment,
Daniel Dunbar27ade182010-02-11 21:29:29 +0000470 MCAsmFixup &Fixup,
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000471 const MCValue &Target,
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000472 std::vector<MachRelocationEntry> &Relocs) {
Daniel Dunbarcb7d7432010-02-11 21:29:46 +0000473 uint32_t Address = Fragment.getOffset() + Fixup.Offset;
Daniel Dunbare180fa92010-03-09 21:27:30 +0000474 unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
Daniel Dunbareb3804e2010-02-17 23:45:16 +0000475 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000476 unsigned Type = RIT_Vanilla;
477
478 // See <reloc.h>.
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000479 const MCSymbol *A = Target.getSymA();
Daniel Dunbar2101d9c2010-03-10 20:58:31 +0000480 MCSymbolData *A_SD = &Asm.getSymbolData(*A);
Daniel Dunbar0ce6bd52010-03-08 21:10:39 +0000481
Daniel Dunbara015c1c2010-03-10 00:58:25 +0000482 if (!A_SD->getFragment())
Daniel Dunbar0ce6bd52010-03-08 21:10:39 +0000483 llvm_report_error("symbol '" + A->getName() +
484 "' can not be undefined in a subtraction expression");
485
Daniel Dunbar8f0448c2010-03-11 18:22:51 +0000486 uint32_t Value = A_SD->getAddress();
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000487 uint32_t Value2 = 0;
488
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000489 if (const MCSymbol *B = Target.getSymB()) {
Daniel Dunbar2101d9c2010-03-10 20:58:31 +0000490 MCSymbolData *B_SD = &Asm.getSymbolData(*B);
Daniel Dunbar0ce6bd52010-03-08 21:10:39 +0000491
Daniel Dunbara015c1c2010-03-10 00:58:25 +0000492 if (!B_SD->getFragment())
Daniel Dunbar0ce6bd52010-03-08 21:10:39 +0000493 llvm_report_error("symbol '" + B->getName() +
494 "' can not be undefined in a subtraction expression");
495
Daniel Dunbar07a96412010-03-10 02:10:29 +0000496 // Select the appropriate difference relocation type.
497 //
498 // Note that there is no longer any semantic difference between these two
499 // relocation types from the linkers point of view, this is done solely
500 // for pedantic compatibility with 'as'.
Daniel Dunbara015c1c2010-03-10 00:58:25 +0000501 Type = A_SD->isExternal() ? RIT_Difference : RIT_LocalDifference;
Daniel Dunbar8f0448c2010-03-11 18:22:51 +0000502 Value2 = B_SD->getAddress();
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000503 }
504
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000505 MachRelocationEntry MRE;
506 MRE.Word0 = ((Address << 0) |
507 (Type << 24) |
508 (Log2Size << 28) |
509 (IsPCRel << 30) |
510 RF_Scattered);
511 MRE.Word1 = Value;
512 Relocs.push_back(MRE);
513
Daniel Dunbara015c1c2010-03-10 00:58:25 +0000514 if (Type == RIT_Difference || Type == RIT_LocalDifference) {
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000515 MachRelocationEntry MRE;
516 MRE.Word0 = ((0 << 0) |
Daniel Dunbaraef9d7a2010-03-09 21:27:47 +0000517 (RIT_Pair << 24) |
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000518 (Log2Size << 28) |
Daniel Dunbaraef9d7a2010-03-09 21:27:47 +0000519 (IsPCRel << 30) |
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000520 RF_Scattered);
521 MRE.Word1 = Value2;
522 Relocs.push_back(MRE);
523 }
524 }
525
Daniel Dunbar0bcf0742010-02-13 09:28:43 +0000526 void ComputeRelocationInfo(MCAssembler &Asm, MCDataFragment &Fragment,
Daniel Dunbar27ade182010-02-11 21:29:29 +0000527 MCAsmFixup &Fixup,
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000528 std::vector<MachRelocationEntry> &Relocs) {
Daniel Dunbarf3a066f2010-03-09 21:27:58 +0000529 unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
530 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
531
Daniel Dunbar18ff2cc2010-03-11 05:53:33 +0000532 // FIXME: Share layout object.
533 MCAsmLayout Layout(Asm);
534
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000535 // Evaluate the fixup; if the value was resolved, no relocation is needed.
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000536 MCValue Target;
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000537 if (Asm.EvaluateFixup(Layout, Fixup, &Fragment, Target, Fixup.FixedValue))
538 return;
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000539
Daniel Dunbarf3a066f2010-03-09 21:27:58 +0000540 // If this is a difference or a defined symbol plus an offset, then we need
541 // a scattered relocation entry.
542 uint32_t Offset = Target.getConstant();
543 if (IsPCRel)
544 Offset += 1 << Log2Size;
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000545 if (Target.getSymB() ||
546 (Target.getSymA() && !Target.getSymA()->isUndefined() &&
Daniel Dunbarf3a066f2010-03-09 21:27:58 +0000547 Offset))
Daniel Dunbarcb7d7432010-02-11 21:29:46 +0000548 return ComputeScatteredRelocationInfo(Asm, Fragment, Fixup, Target,
Daniel Dunbar2101d9c2010-03-10 20:58:31 +0000549 Relocs);
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000550
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000551 // See <reloc.h>.
Daniel Dunbarcb7d7432010-02-11 21:29:46 +0000552 uint32_t Address = Fragment.getOffset() + Fixup.Offset;
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000553 uint32_t Value = 0;
554 unsigned Index = 0;
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000555 unsigned IsExtern = 0;
556 unsigned Type = 0;
557
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000558 if (Target.isAbsolute()) { // constant
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000559 // SymbolNum of 0 indicates the absolute section.
Daniel Dunbar3a30b822010-02-13 09:28:15 +0000560 //
Daniel Dunbar979ba5b2010-03-11 05:53:37 +0000561 // FIXME: Currently, these are never generated (see code below). I cannot
562 // find a case where they are actually emitted.
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000563 Type = RIT_Vanilla;
564 Value = 0;
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000565 } else {
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000566 const MCSymbol *Symbol = Target.getSymA();
Daniel Dunbar2101d9c2010-03-10 20:58:31 +0000567 MCSymbolData *SD = &Asm.getSymbolData(*Symbol);
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000568
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000569 if (Symbol->isUndefined()) {
570 IsExtern = 1;
571 Index = SD->getIndex();
572 Value = 0;
573 } else {
574 // The index is the section ordinal.
575 //
576 // FIXME: O(N)
577 Index = 1;
Daniel Dunbar591047f2010-02-13 09:45:59 +0000578 MCAssembler::iterator it = Asm.begin(), ie = Asm.end();
579 for (; it != ie; ++it, ++Index)
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000580 if (&*it == SD->getFragment()->getParent())
581 break;
Daniel Dunbar591047f2010-02-13 09:45:59 +0000582 assert(it != ie && "Unable to find section index!");
Daniel Dunbar8f0448c2010-03-11 18:22:51 +0000583 Value = SD->getAddress();
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000584 }
585
586 Type = RIT_Vanilla;
587 }
588
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000589 // struct relocation_info (8 bytes)
590 MachRelocationEntry MRE;
591 MRE.Word0 = Address;
592 MRE.Word1 = ((Index << 0) |
593 (IsPCRel << 24) |
594 (Log2Size << 25) |
595 (IsExtern << 27) |
596 (Type << 28));
597 Relocs.push_back(MRE);
598 }
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000599
Daniel Dunbar2101d9c2010-03-10 20:58:31 +0000600 void BindIndirectSymbols(MCAssembler &Asm) {
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000601 // This is the point where 'as' creates actual symbols for indirect symbols
602 // (in the following two passes). It would be easier for us to do this
603 // sooner when we see the attribute, but that makes getting the order in the
604 // symbol table much more complicated than it is worth.
605 //
606 // FIXME: Revisit this when the dust settles.
607
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000608 // Bind non lazy symbol pointers first.
609 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
610 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
611 // FIXME: cast<> support!
612 const MCSectionMachO &Section =
613 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
614
615 unsigned Type =
616 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
617 if (Type != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
618 continue;
619
Daniel Dunbar2101d9c2010-03-10 20:58:31 +0000620 Asm.getOrCreateSymbolData(*it->Symbol);
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000621 }
622
623 // Then lazy symbol pointers and symbol stubs.
624 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
625 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
626 // FIXME: cast<> support!
627 const MCSectionMachO &Section =
628 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
629
630 unsigned Type =
631 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
632 if (Type != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
633 Type != MCSectionMachO::S_SYMBOL_STUBS)
634 continue;
635
Daniel Dunbar2101d9c2010-03-10 20:58:31 +0000636 // Set the symbol type to undefined lazy, but only on construction.
637 //
638 // FIXME: Do not hardcode.
639 bool Created;
640 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
641 if (Created)
642 Entry.setFlags(Entry.getFlags() | 0x0001);
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000643 }
644 }
645
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000646 /// ComputeSymbolTable - Compute the symbol table data
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000647 ///
648 /// \param StringTable [out] - The string table data.
649 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
650 /// string table.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000651 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
652 std::vector<MachSymbolData> &LocalSymbolData,
653 std::vector<MachSymbolData> &ExternalSymbolData,
654 std::vector<MachSymbolData> &UndefinedSymbolData) {
655 // Build section lookup table.
656 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
657 unsigned Index = 1;
658 for (MCAssembler::iterator it = Asm.begin(),
659 ie = Asm.end(); it != ie; ++it, ++Index)
660 SectionIndexMap[&it->getSection()] = Index;
661 assert(Index <= 256 && "Too many sections!");
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000662
663 // Index 0 is always the empty string.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000664 StringMap<uint64_t> StringIndexMap;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000665 StringTable += '\x00';
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000666
667 // Build the symbol arrays and the string table, but only for non-local
668 // symbols.
669 //
670 // The particular order that we collect the symbols and create the string
671 // table, then sort the symbols is chosen to match 'as'. Even though it
672 // doesn't matter for correctness, this is important for letting us diff .o
673 // files.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000674 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
675 ie = Asm.symbol_end(); it != ie; ++it) {
Daniel Dunbarcb579b32009-08-31 08:08:06 +0000676 const MCSymbol &Symbol = it->getSymbol();
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000677
Daniel Dunbar959fd882009-08-26 22:13:22 +0000678 // Ignore assembler temporaries.
679 if (it->getSymbol().isTemporary())
680 continue;
681
Daniel Dunbar50e48b32009-08-24 08:39:57 +0000682 if (!it->isExternal() && !Symbol.isUndefined())
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000683 continue;
684
685 uint64_t &Entry = StringIndexMap[Symbol.getName()];
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000686 if (!Entry) {
687 Entry = StringTable.size();
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000688 StringTable += Symbol.getName();
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000689 StringTable += '\x00';
690 }
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000691
692 MachSymbolData MSD;
693 MSD.SymbolData = it;
694 MSD.StringIndex = Entry;
695
696 if (Symbol.isUndefined()) {
697 MSD.SectionIndex = 0;
698 UndefinedSymbolData.push_back(MSD);
699 } else if (Symbol.isAbsolute()) {
700 MSD.SectionIndex = 0;
701 ExternalSymbolData.push_back(MSD);
702 } else {
703 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
704 assert(MSD.SectionIndex && "Invalid section index!");
705 ExternalSymbolData.push_back(MSD);
706 }
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000707 }
708
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000709 // Now add the data for local symbols.
710 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
711 ie = Asm.symbol_end(); it != ie; ++it) {
Daniel Dunbarcb579b32009-08-31 08:08:06 +0000712 const MCSymbol &Symbol = it->getSymbol();
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000713
Daniel Dunbar959fd882009-08-26 22:13:22 +0000714 // Ignore assembler temporaries.
715 if (it->getSymbol().isTemporary())
716 continue;
717
Daniel Dunbar50e48b32009-08-24 08:39:57 +0000718 if (it->isExternal() || Symbol.isUndefined())
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000719 continue;
720
721 uint64_t &Entry = StringIndexMap[Symbol.getName()];
722 if (!Entry) {
723 Entry = StringTable.size();
724 StringTable += Symbol.getName();
725 StringTable += '\x00';
726 }
727
728 MachSymbolData MSD;
729 MSD.SymbolData = it;
730 MSD.StringIndex = Entry;
731
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000732 if (Symbol.isAbsolute()) {
733 MSD.SectionIndex = 0;
734 LocalSymbolData.push_back(MSD);
735 } else {
736 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
737 assert(MSD.SectionIndex && "Invalid section index!");
738 LocalSymbolData.push_back(MSD);
739 }
740 }
741
742 // External and undefined symbols are required to be in lexicographic order.
743 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
744 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
745
Daniel Dunbarbe963552009-08-26 13:57:54 +0000746 // Set the symbol indices.
747 Index = 0;
748 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
749 LocalSymbolData[i].SymbolData->setIndex(Index++);
750 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
751 ExternalSymbolData[i].SymbolData->setIndex(Index++);
752 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
753 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
754
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000755 // The string table is padded to a multiple of 4.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000756 while (StringTable.size() % 4)
757 StringTable += '\x00';
758 }
759
760 void WriteObject(MCAssembler &Asm) {
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000761 unsigned NumSections = Asm.size();
762
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000763 // Create symbol data for any indirect symbols.
Daniel Dunbar2101d9c2010-03-10 20:58:31 +0000764 BindIndirectSymbols(Asm);
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000765
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000766 // Compute symbol table information.
767 SmallString<256> StringTable;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000768 std::vector<MachSymbolData> LocalSymbolData;
769 std::vector<MachSymbolData> ExternalSymbolData;
770 std::vector<MachSymbolData> UndefinedSymbolData;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000771 unsigned NumSymbols = Asm.symbol_size();
772
773 // No symbol table command is written if there are no symbols.
774 if (NumSymbols)
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000775 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
776 UndefinedSymbolData);
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000777
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000778 // The section data starts after the header, the segment load command (and
779 // section headers) and the symbol table.
780 unsigned NumLoadCommands = 1;
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000781 uint64_t LoadCommandsSize = Is64Bit ?
782 SegmentLoadCommand64Size + NumSections * Section64Size :
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000783 SegmentLoadCommand32Size + NumSections * Section32Size;
784
785 // Add the symbol table load command sizes, if used.
786 if (NumSymbols) {
787 NumLoadCommands += 2;
788 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
789 }
790
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000791 // Compute the total size of the section data, as well as its file size and
792 // vm size.
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000793 uint64_t SectionDataStart = (Is64Bit ? Header64Size : Header32Size)
794 + LoadCommandsSize;
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000795 uint64_t SectionDataSize = 0;
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000796 uint64_t SectionDataFileSize = 0;
797 uint64_t VMSize = 0;
798 for (MCAssembler::iterator it = Asm.begin(),
799 ie = Asm.end(); it != ie; ++it) {
800 MCSectionData &SD = *it;
801
802 VMSize = std::max(VMSize, SD.getAddress() + SD.getSize());
803
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000804 if (isVirtualSection(SD.getSection()))
805 continue;
806
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000807 SectionDataSize = std::max(SectionDataSize,
808 SD.getAddress() + SD.getSize());
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000809 SectionDataFileSize = std::max(SectionDataFileSize,
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000810 SD.getAddress() + SD.getFileSize());
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000811 }
812
Daniel Dunbar6b716532010-02-09 23:00:14 +0000813 // The section data is padded to 4 bytes.
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000814 //
815 // FIXME: Is this machine dependent?
816 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
817 SectionDataFileSize += SectionDataPadding;
818
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000819 // Write the prolog, starting with the header and load command...
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000820 WriteHeader(NumLoadCommands, LoadCommandsSize,
821 Asm.getSubsectionsViaSymbols());
822 WriteSegmentLoadCommand(NumSections, VMSize,
823 SectionDataStart, SectionDataSize);
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000824
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000825 // ... and then the section headers.
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000826 //
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000827 // We also compute the section relocations while we do this. Note that
Daniel Dunbar6b716532010-02-09 23:00:14 +0000828 // computing relocation info will also update the fixup to have the correct
829 // value; this will overwrite the appropriate data in the fragment when it
830 // is written.
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000831 std::vector<MachRelocationEntry> RelocInfos;
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000832 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
Daniel Dunbarcb7d7432010-02-11 21:29:46 +0000833 for (MCAssembler::iterator it = Asm.begin(),
834 ie = Asm.end(); it != ie; ++it) {
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000835 MCSectionData &SD = *it;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000836
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000837 // The assembler writes relocations in the reverse order they were seen.
838 //
839 // FIXME: It is probably more complicated than this.
840 unsigned NumRelocsStart = RelocInfos.size();
Daniel Dunbarcb7d7432010-02-11 21:29:46 +0000841 for (MCSectionData::reverse_iterator it2 = SD.rbegin(),
842 ie2 = SD.rend(); it2 != ie2; ++it2)
Daniel Dunbar0bcf0742010-02-13 09:28:43 +0000843 if (MCDataFragment *DF = dyn_cast<MCDataFragment>(&*it2))
844 for (unsigned i = 0, e = DF->fixup_size(); i != e; ++i)
845 ComputeRelocationInfo(Asm, *DF, DF->getFixups()[e - i - 1],
Daniel Dunbar2101d9c2010-03-10 20:58:31 +0000846 RelocInfos);
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000847
848 unsigned NumRelocs = RelocInfos.size() - NumRelocsStart;
849 uint64_t SectionStart = SectionDataStart + SD.getAddress();
Daniel Dunbaree0d8922010-03-13 22:10:17 +0000850 WriteSection(SD, SectionStart, RelocTableEnd, NumRelocs);
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000851 RelocTableEnd += NumRelocs * RelocationInfoSize;
852 }
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000853
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000854 // Write the symbol table load command, if used.
855 if (NumSymbols) {
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000856 unsigned FirstLocalSymbol = 0;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000857 unsigned NumLocalSymbols = LocalSymbolData.size();
858 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
859 unsigned NumExternalSymbols = ExternalSymbolData.size();
860 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
861 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000862 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
863 unsigned NumSymTabSymbols =
864 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
865 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
866 uint64_t IndirectSymbolOffset = 0;
867
868 // If used, the indirect symbols are written after the section data.
869 if (NumIndirectSymbols)
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000870 IndirectSymbolOffset = RelocTableEnd;
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000871
872 // The symbol table is written after the indirect symbol data.
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000873 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000874
875 // The string table is written after symbol table.
876 uint64_t StringTableOffset =
877 SymbolTableOffset + NumSymTabSymbols * Nlist32Size;
878 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
879 StringTableOffset, StringTable.size());
880
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000881 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
882 FirstExternalSymbol, NumExternalSymbols,
883 FirstUndefinedSymbol, NumUndefinedSymbols,
884 IndirectSymbolOffset, NumIndirectSymbols);
885 }
886
887 // Write the actual section data.
888 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
889 WriteFileData(OS, *it, *this);
890
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000891 // Write the extra padding.
892 WriteZeros(SectionDataPadding);
893
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000894 // Write the relocation entries.
895 for (unsigned i = 0, e = RelocInfos.size(); i != e; ++i) {
896 Write32(RelocInfos[i].Word0);
897 Write32(RelocInfos[i].Word1);
898 }
899
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000900 // Write the symbol table data, if used.
901 if (NumSymbols) {
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000902 // Write the indirect symbol entries.
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000903 for (MCAssembler::indirect_symbol_iterator
904 it = Asm.indirect_symbol_begin(),
905 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
906 // Indirect symbols in the non lazy symbol pointer section have some
907 // special handling.
908 const MCSectionMachO &Section =
909 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
910 unsigned Type =
911 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
912 if (Type == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
913 // If this symbol is defined and internal, mark it as such.
914 if (it->Symbol->isDefined() &&
Daniel Dunbar2101d9c2010-03-10 20:58:31 +0000915 !Asm.getSymbolData(*it->Symbol).isExternal()) {
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000916 uint32_t Flags = ISF_Local;
917 if (it->Symbol->isAbsolute())
918 Flags |= ISF_Absolute;
919 Write32(Flags);
920 continue;
921 }
922 }
923
Daniel Dunbar2101d9c2010-03-10 20:58:31 +0000924 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000925 }
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000926
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000927 // FIXME: Check that offsets match computed ones.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000928
929 // Write the symbol table entries.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000930 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
931 WriteNlist32(LocalSymbolData[i]);
932 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
933 WriteNlist32(ExternalSymbolData[i]);
934 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
935 WriteNlist32(UndefinedSymbolData[i]);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000936
937 // Write the string table.
938 OS << StringTable.str();
939 }
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000940 }
Daniel Dunbar3a30b822010-02-13 09:28:15 +0000941
942 void ApplyFixup(const MCAsmFixup &Fixup, MCDataFragment &DF) {
Daniel Dunbar2be2fd02010-02-13 09:28:54 +0000943 unsigned Size = 1 << getFixupKindLog2Size(Fixup.Kind);
944
Daniel Dunbar3a30b822010-02-13 09:28:15 +0000945 // FIXME: Endianness assumption.
Daniel Dunbar2be2fd02010-02-13 09:28:54 +0000946 assert(Fixup.Offset + Size <= DF.getContents().size() &&
947 "Invalid fixup offset!");
948 for (unsigned i = 0; i != Size; ++i)
Daniel Dunbar3a30b822010-02-13 09:28:15 +0000949 DF.getContents()[Fixup.Offset + i] = uint8_t(Fixup.FixedValue >> (i * 8));
950 }
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000951};
952
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000953/* *** */
954
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000955MCFragment::MCFragment() : Kind(FragmentType(~0)) {
956}
957
Daniel Dunbar5e835962009-08-26 02:48:04 +0000958MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000959 : Kind(_Kind),
Daniel Dunbar5e835962009-08-26 02:48:04 +0000960 Parent(_Parent),
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000961 FileSize(~UINT64_C(0))
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000962{
Daniel Dunbar5e835962009-08-26 02:48:04 +0000963 if (Parent)
964 Parent->getFragmentList().push_back(this);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000965}
966
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000967MCFragment::~MCFragment() {
968}
969
Daniel Dunbar5e835962009-08-26 02:48:04 +0000970uint64_t MCFragment::getAddress() const {
971 assert(getParent() && "Missing Section!");
972 return getParent()->getAddress() + Offset;
973}
974
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000975/* *** */
976
Daniel Dunbar81e40002009-08-27 00:38:04 +0000977MCSectionData::MCSectionData() : Section(0) {}
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000978
979MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
Daniel Dunbar81e40002009-08-27 00:38:04 +0000980 : Section(&_Section),
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000981 Alignment(1),
Daniel Dunbar5e835962009-08-26 02:48:04 +0000982 Address(~UINT64_C(0)),
Daniel Dunbar6742e342009-08-26 04:13:32 +0000983 Size(~UINT64_C(0)),
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000984 FileSize(~UINT64_C(0)),
Daniel Dunbare1ec6172010-02-02 21:44:01 +0000985 HasInstructions(false)
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000986{
987 if (A)
988 A->getSectionList().push_back(this);
989}
990
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000991/* *** */
992
Daniel Dunbarefbb5332009-09-01 04:09:03 +0000993MCSymbolData::MCSymbolData() : Symbol(0) {}
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000994
Daniel Dunbarcb579b32009-08-31 08:08:06 +0000995MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000996 uint64_t _Offset, MCAssembler *A)
Daniel Dunbarefbb5332009-09-01 04:09:03 +0000997 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
Daniel Dunbar8f4d1462009-08-28 07:08:35 +0000998 IsExternal(false), IsPrivateExtern(false),
999 CommonSize(0), CommonAlign(0), Flags(0), Index(0)
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +00001000{
1001 if (A)
1002 A->getSymbolList().push_back(this);
1003}
1004
1005/* *** */
1006
Daniel Dunbar1f3e4452010-03-11 01:34:27 +00001007MCAssembler::MCAssembler(MCContext &_Context, TargetAsmBackend &_Backend,
1008 raw_ostream &_OS)
1009 : Context(_Context), Backend(_Backend), OS(_OS), SubsectionsViaSymbols(false)
Daniel Dunbar6009db42009-08-26 21:22:22 +00001010{
1011}
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +00001012
1013MCAssembler::~MCAssembler() {
1014}
1015
Daniel Dunbardf3c8f22010-03-12 21:00:49 +00001016bool MCAssembler::EvaluateFixup(const MCAsmLayout &Layout, MCAsmFixup &Fixup,
1017 MCDataFragment *DF,
1018 MCValue &Target, uint64_t &Value) const {
1019 if (!Fixup.Value->EvaluateAsRelocatable(Target, &Layout))
1020 llvm_report_error("expected relocatable expression");
1021
1022 // FIXME: How do non-scattered symbols work in ELF? I presume the linker
1023 // doesn't support small relocations, but then under what criteria does the
1024 // assembler allow symbol differences?
1025
1026 Value = Target.getConstant();
1027
1028 // FIXME: This "resolved" check isn't quite right. The assumption is that if
1029 // we have a PCrel access to a temporary, then that temporary is in the same
1030 // atom, and so the value is resolved. We need explicit atom's to implement
1031 // this more precisely.
1032 bool IsResolved = true, IsPCRel = isFixupKindPCRel(Fixup.Kind);
1033 if (const MCSymbol *Symbol = Target.getSymA()) {
1034 if (Symbol->isDefined())
1035 Value += getSymbolData(*Symbol).getAddress();
1036 else
1037 IsResolved = false;
1038
1039 // With scattered symbols, we assume anything that isn't a PCrel temporary
1040 // access can have an arbitrary value.
1041 if (getBackend().hasScatteredSymbols() &&
1042 (!IsPCRel || !Symbol->isTemporary()))
1043 IsResolved = false;
1044 }
1045 if (const MCSymbol *Symbol = Target.getSymB()) {
1046 if (Symbol->isDefined())
1047 Value -= getSymbolData(*Symbol).getAddress();
1048 else
1049 IsResolved = false;
1050
1051 // With scattered symbols, we assume anything that isn't a PCrel temporary
1052 // access can have an arbitrary value.
1053 if (getBackend().hasScatteredSymbols() &&
1054 (!IsPCRel || !Symbol->isTemporary()))
1055 IsResolved = false;
1056 }
1057
1058 if (IsPCRel)
Daniel Dunbarda3e9f72010-03-13 02:38:00 +00001059 Value -= DF->getAddress() + Fixup.Offset;
Daniel Dunbardf3c8f22010-03-12 21:00:49 +00001060
1061 return IsResolved;
1062}
1063
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001064void MCAssembler::LayoutSection(MCSectionData &SD) {
Daniel Dunbar18ff2cc2010-03-11 05:53:33 +00001065 MCAsmLayout Layout(*this);
Daniel Dunbar6742e342009-08-26 04:13:32 +00001066 uint64_t Address = SD.getAddress();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001067
1068 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
1069 MCFragment &F = *it;
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001070
Daniel Dunbar6742e342009-08-26 04:13:32 +00001071 F.setOffset(Address - SD.getAddress());
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001072
1073 // Evaluate fragment size.
1074 switch (F.getKind()) {
1075 case MCFragment::FT_Align: {
1076 MCAlignFragment &AF = cast<MCAlignFragment>(F);
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001077
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001078 uint64_t Size = OffsetToAlignment(Address, AF.getAlignment());
Daniel Dunbar6742e342009-08-26 04:13:32 +00001079 if (Size > AF.getMaxBytesToEmit())
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001080 AF.setFileSize(0);
1081 else
Daniel Dunbar6742e342009-08-26 04:13:32 +00001082 AF.setFileSize(Size);
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001083 break;
1084 }
1085
1086 case MCFragment::FT_Data:
Daniel Dunbara4766d72010-02-13 09:28:32 +00001087 case MCFragment::FT_Fill:
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001088 F.setFileSize(F.getMaxFileSize());
1089 break;
1090
1091 case MCFragment::FT_Org: {
1092 MCOrgFragment &OF = cast<MCOrgFragment>(F);
1093
Daniel Dunbar18ff2cc2010-03-11 05:53:33 +00001094 int64_t TargetLocation;
1095 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, &Layout))
1096 llvm_report_error("expected assembly-time absolute expression");
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001097
1098 // FIXME: We need a way to communicate this error.
Daniel Dunbar18ff2cc2010-03-11 05:53:33 +00001099 int64_t Offset = TargetLocation - F.getOffset();
1100 if (Offset < 0)
1101 llvm_report_error("invalid .org offset '" + Twine(TargetLocation) +
1102 "' (at offset '" + Twine(F.getOffset()) + "'");
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001103
Daniel Dunbar18ff2cc2010-03-11 05:53:33 +00001104 F.setFileSize(Offset);
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001105 break;
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001106 }
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001107
1108 case MCFragment::FT_ZeroFill: {
1109 MCZeroFillFragment &ZFF = cast<MCZeroFillFragment>(F);
1110
1111 // Align the fragment offset; it is safe to adjust the offset freely since
1112 // this is only in virtual sections.
Daniel Dunbar37fad5c2010-03-08 21:10:42 +00001113 Address = RoundUpToAlignment(Address, ZFF.getAlignment());
1114 F.setOffset(Address - SD.getAddress());
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001115
1116 // FIXME: This is misnamed.
1117 F.setFileSize(ZFF.getSize());
1118 break;
1119 }
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001120 }
1121
Daniel Dunbar6742e342009-08-26 04:13:32 +00001122 Address += F.getFileSize();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001123 }
1124
Daniel Dunbar6742e342009-08-26 04:13:32 +00001125 // Set the section sizes.
1126 SD.setSize(Address - SD.getAddress());
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001127 if (isVirtualSection(SD.getSection()))
1128 SD.setFileSize(0);
1129 else
1130 SD.setFileSize(Address - SD.getAddress());
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001131}
1132
Kevin Enderby6e720482010-02-23 18:26:34 +00001133/// WriteNopData - Write optimal nops to the output file for the \arg Count
1134/// bytes. This returns the number of bytes written. It may return 0 if
1135/// the \arg Count is more than the maximum optimal nops.
1136///
1137/// FIXME this is X86 32-bit specific and should move to a better place.
1138static uint64_t WriteNopData(uint64_t Count, MachObjectWriter &MOW) {
Kevin Enderby76687082010-02-23 21:41:24 +00001139 static const uint8_t Nops[16][16] = {
1140 // nop
1141 {0x90},
1142 // xchg %ax,%ax
1143 {0x66, 0x90},
1144 // nopl (%[re]ax)
1145 {0x0f, 0x1f, 0x00},
1146 // nopl 0(%[re]ax)
1147 {0x0f, 0x1f, 0x40, 0x00},
1148 // nopl 0(%[re]ax,%[re]ax,1)
1149 {0x0f, 0x1f, 0x44, 0x00, 0x00},
1150 // nopw 0(%[re]ax,%[re]ax,1)
1151 {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1152 // nopl 0L(%[re]ax)
1153 {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1154 // nopl 0L(%[re]ax,%[re]ax,1)
1155 {0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1156 // nopw 0L(%[re]ax,%[re]ax,1)
1157 {0x66, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1158 // nopw %cs:0L(%[re]ax,%[re]ax,1)
1159 {0x66, 0x2e, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1160 // nopl 0(%[re]ax,%[re]ax,1)
1161 // nopw 0(%[re]ax,%[re]ax,1)
1162 {0x0f, 0x1f, 0x44, 0x00, 0x00,
1163 0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1164 // nopw 0(%[re]ax,%[re]ax,1)
1165 // nopw 0(%[re]ax,%[re]ax,1)
1166 {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00,
1167 0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1168 // nopw 0(%[re]ax,%[re]ax,1)
1169 // nopl 0L(%[re]ax) */
1170 {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00,
1171 0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1172 // nopl 0L(%[re]ax)
1173 // nopl 0L(%[re]ax)
1174 {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00,
1175 0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1176 // nopl 0L(%[re]ax)
1177 // nopl 0L(%[re]ax,%[re]ax,1)
1178 {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00,
1179 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00}
1180 };
1181
1182 if (Count > 15)
1183 return 0;
1184
Kevin Enderby6e720482010-02-23 18:26:34 +00001185 for (uint64_t i = 0; i < Count; i++)
Kevin Enderby76687082010-02-23 21:41:24 +00001186 MOW.Write8 (uint8_t(Nops[Count - 1][i]));
Kevin Enderby6e720482010-02-23 18:26:34 +00001187
1188 return Count;
1189}
1190
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001191/// WriteFileData - Write the \arg F data to the output file.
1192static void WriteFileData(raw_ostream &OS, const MCFragment &F,
1193 MachObjectWriter &MOW) {
1194 uint64_t Start = OS.tell();
1195 (void) Start;
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001196
Daniel Dunbar0adcd352009-08-25 21:10:45 +00001197 ++EmittedFragments;
1198
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001199 // FIXME: Embed in fragments instead?
1200 switch (F.getKind()) {
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001201 case MCFragment::FT_Align: {
1202 MCAlignFragment &AF = cast<MCAlignFragment>(F);
1203 uint64_t Count = AF.getFileSize() / AF.getValueSize();
1204
1205 // FIXME: This error shouldn't actually occur (the front end should emit
1206 // multiple .align directives to enforce the semantics it wants), but is
1207 // severe enough that we want to report it. How to handle this?
1208 if (Count * AF.getValueSize() != AF.getFileSize())
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001209 llvm_report_error("undefined .align directive, value size '" +
1210 Twine(AF.getValueSize()) +
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001211 "' is not a divisor of padding size '" +
1212 Twine(AF.getFileSize()) + "'");
1213
Kevin Enderby6e720482010-02-23 18:26:34 +00001214 // See if we are aligning with nops, and if so do that first to try to fill
1215 // the Count bytes. Then if that did not fill any bytes or there are any
1216 // bytes left to fill use the the Value and ValueSize to fill the rest.
1217 if (AF.getEmitNops()) {
1218 uint64_t NopByteCount = WriteNopData(Count, MOW);
1219 Count -= NopByteCount;
1220 }
1221
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001222 for (uint64_t i = 0; i != Count; ++i) {
1223 switch (AF.getValueSize()) {
1224 default:
1225 assert(0 && "Invalid size!");
1226 case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
1227 case 2: MOW.Write16(uint16_t(AF.getValue())); break;
1228 case 4: MOW.Write32(uint32_t(AF.getValue())); break;
1229 case 8: MOW.Write64(uint64_t(AF.getValue())); break;
1230 }
1231 }
1232 break;
1233 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001234
Daniel Dunbar3a30b822010-02-13 09:28:15 +00001235 case MCFragment::FT_Data: {
1236 MCDataFragment &DF = cast<MCDataFragment>(F);
1237
1238 // Apply the fixups.
1239 //
1240 // FIXME: Move elsewhere.
1241 for (MCDataFragment::const_fixup_iterator it = DF.fixup_begin(),
1242 ie = DF.fixup_end(); it != ie; ++it)
1243 MOW.ApplyFixup(*it, DF);
1244
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001245 OS << cast<MCDataFragment>(F).getContents().str();
1246 break;
Daniel Dunbar3a30b822010-02-13 09:28:15 +00001247 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001248
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001249 case MCFragment::FT_Fill: {
1250 MCFillFragment &FF = cast<MCFillFragment>(F);
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001251 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
1252 switch (FF.getValueSize()) {
1253 default:
1254 assert(0 && "Invalid size!");
Daniel Dunbara4766d72010-02-13 09:28:32 +00001255 case 1: MOW.Write8 (uint8_t (FF.getValue())); break;
1256 case 2: MOW.Write16(uint16_t(FF.getValue())); break;
1257 case 4: MOW.Write32(uint32_t(FF.getValue())); break;
1258 case 8: MOW.Write64(uint64_t(FF.getValue())); break;
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001259 }
1260 }
1261 break;
1262 }
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001263
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001264 case MCFragment::FT_Org: {
1265 MCOrgFragment &OF = cast<MCOrgFragment>(F);
1266
1267 for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
1268 MOW.Write8(uint8_t(OF.getValue()));
1269
1270 break;
1271 }
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001272
1273 case MCFragment::FT_ZeroFill: {
1274 assert(0 && "Invalid zero fill fragment in concrete section!");
1275 break;
1276 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001277 }
1278
1279 assert(OS.tell() - Start == F.getFileSize());
1280}
1281
1282/// WriteFileData - Write the \arg SD data to the output file.
1283static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
1284 MachObjectWriter &MOW) {
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001285 // Ignore virtual sections.
1286 if (isVirtualSection(SD.getSection())) {
1287 assert(SD.getFileSize() == 0);
1288 return;
1289 }
1290
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001291 uint64_t Start = OS.tell();
1292 (void) Start;
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001293
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001294 for (MCSectionData::const_iterator it = SD.begin(),
1295 ie = SD.end(); it != ie; ++it)
1296 WriteFileData(OS, *it, MOW);
1297
Daniel Dunbar6742e342009-08-26 04:13:32 +00001298 // Add section padding.
1299 assert(SD.getFileSize() >= SD.getSize() && "Invalid section sizes!");
1300 MOW.WriteZeros(SD.getFileSize() - SD.getSize());
1301
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001302 assert(OS.tell() - Start == SD.getFileSize());
1303}
1304
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +00001305void MCAssembler::Finish() {
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001306 DEBUG_WITH_TYPE("mc-dump", {
1307 llvm::errs() << "assembler backend - pre-layout\n--\n";
1308 dump(); });
1309
Daniel Dunbarf08fde42010-03-12 22:07:14 +00001310 // Layout until everything fits.
1311 while (LayoutOnce())
1312 continue;
1313
1314 DEBUG_WITH_TYPE("mc-dump", {
1315 llvm::errs() << "assembler backend - post-layout\n--\n";
1316 dump(); });
1317
1318 // Write the object file.
Daniel Dunbaree0d8922010-03-13 22:10:17 +00001319 //
1320 // FIXME: Factor out MCObjectWriter.
1321 bool Is64Bit = StringRef(getBackend().getTarget().getName()) == "x86-64";
1322 MachObjectWriter MOW(OS, Is64Bit);
Daniel Dunbarf08fde42010-03-12 22:07:14 +00001323 MOW.WriteObject(*this);
1324
1325 OS.flush();
1326}
1327
1328bool MCAssembler::FixupNeedsRelaxation(MCAsmFixup &Fixup, MCDataFragment *DF) {
1329 // FIXME: Share layout object.
1330 MCAsmLayout Layout(*this);
1331
1332 // Currently we only need to relax X86::reloc_pcrel_1byte.
1333 if (unsigned(Fixup.Kind) != X86::reloc_pcrel_1byte)
1334 return false;
1335
1336 // If we cannot resolve the fixup value, it requires relaxation.
1337 MCValue Target;
1338 uint64_t Value;
1339 if (!EvaluateFixup(Layout, Fixup, DF, Target, Value))
1340 return true;
1341
1342 // Otherwise, relax if the value is too big for a (signed) i8.
1343 return int64_t(Value) != int64_t(int8_t(Value));
1344}
1345
1346bool MCAssembler::LayoutOnce() {
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001347 // Layout the concrete sections and fragments.
Daniel Dunbar5e835962009-08-26 02:48:04 +00001348 uint64_t Address = 0;
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001349 MCSectionData *Prev = 0;
1350 for (iterator it = begin(), ie = end(); it != ie; ++it) {
Daniel Dunbar6742e342009-08-26 04:13:32 +00001351 MCSectionData &SD = *it;
1352
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001353 // Skip virtual sections.
1354 if (isVirtualSection(SD.getSection()))
1355 continue;
1356
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001357 // Align this section if necessary by adding padding bytes to the previous
1358 // section.
1359 if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment())) {
1360 assert(Prev && "Missing prev section!");
1361 Prev->setFileSize(Prev->getFileSize() + Pad);
1362 Address += Pad;
1363 }
Daniel Dunbar6742e342009-08-26 04:13:32 +00001364
1365 // Layout the section fragments and its size.
1366 SD.setAddress(Address);
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001367 LayoutSection(SD);
Daniel Dunbar6742e342009-08-26 04:13:32 +00001368 Address += SD.getFileSize();
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001369
1370 Prev = &SD;
Daniel Dunbar5e835962009-08-26 02:48:04 +00001371 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001372
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001373 // Layout the virtual sections.
1374 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1375 MCSectionData &SD = *it;
1376
1377 if (!isVirtualSection(SD.getSection()))
1378 continue;
1379
Daniel Dunbarb2b4acd2010-03-08 22:03:42 +00001380 // Align this section if necessary by adding padding bytes to the previous
1381 // section.
Daniel Dunbarf8b8ad72010-03-09 01:12:20 +00001382 if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment()))
Daniel Dunbarb2b4acd2010-03-08 22:03:42 +00001383 Address += Pad;
Daniel Dunbarb2b4acd2010-03-08 22:03:42 +00001384
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001385 SD.setAddress(Address);
1386 LayoutSection(SD);
1387 Address += SD.getSize();
1388 }
1389
Daniel Dunbarf08fde42010-03-12 22:07:14 +00001390 // Scan the fixups in order and relax any that don't fit.
1391 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1392 MCSectionData &SD = *it;
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001393
Daniel Dunbarf08fde42010-03-12 22:07:14 +00001394 for (MCSectionData::iterator it2 = SD.begin(),
1395 ie2 = SD.end(); it2 != ie2; ++it2) {
1396 MCDataFragment *DF = dyn_cast<MCDataFragment>(it2);
1397 if (!DF)
1398 continue;
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001399
Daniel Dunbarf08fde42010-03-12 22:07:14 +00001400 for (MCDataFragment::fixup_iterator it3 = DF->fixup_begin(),
1401 ie3 = DF->fixup_end(); it3 != ie3; ++it3) {
1402 MCAsmFixup &Fixup = *it3;
1403
1404 // Check whether we need to relax this fixup.
1405 if (!FixupNeedsRelaxation(Fixup, DF))
1406 continue;
1407
1408 // Relax the instruction.
1409 //
1410 // FIXME: This is a huge temporary hack which just looks for x86
1411 // branches; the only thing we need to relax on x86 is
1412 // 'X86::reloc_pcrel_1byte'. Once we have MCInst fragments, this will be
1413 // replaced by a TargetAsmBackend hook (most likely tblgen'd) to relax
1414 // an individual MCInst.
1415 SmallVectorImpl<char> &C = DF->getContents();
1416 uint64_t PrevOffset = Fixup.Offset;
1417 unsigned Amt = 0;
1418
1419 // jcc instructions
1420 if (unsigned(C[Fixup.Offset-1]) >= 0x70 &&
1421 unsigned(C[Fixup.Offset-1]) <= 0x7f) {
1422 C[Fixup.Offset] = C[Fixup.Offset-1] + 0x10;
1423 C[Fixup.Offset-1] = char(0x0f);
1424 ++Fixup.Offset;
1425 Amt = 4;
1426
1427 // jmp rel8
1428 } else if (C[Fixup.Offset-1] == char(0xeb)) {
1429 C[Fixup.Offset-1] = char(0xe9);
1430 Amt = 3;
1431
1432 } else
1433 llvm_unreachable("unknown 1 byte pcrel instruction!");
1434
1435 Fixup.Value = MCBinaryExpr::Create(
1436 MCBinaryExpr::Sub, Fixup.Value,
1437 MCConstantExpr::Create(3, getContext()),
1438 getContext());
1439 C.insert(C.begin() + Fixup.Offset, Amt, char(0));
1440 Fixup.Kind = MCFixupKind(X86::reloc_pcrel_4byte);
1441
1442 // Update the remaining fixups, which have slid.
1443 //
1444 // FIXME: This is bad for performance, but will be eliminated by the
1445 // move to MCInst specific fragments.
1446 ++it3;
1447 for (; it3 != ie3; ++it3)
1448 it3->Offset += Amt;
1449
1450 // Update all the symbols for this fragment, which may have slid.
1451 //
1452 // FIXME: This is really really bad for performance, but will be
1453 // eliminated by the move to MCInst specific fragments.
1454 for (MCAssembler::symbol_iterator it = symbol_begin(),
1455 ie = symbol_end(); it != ie; ++it) {
1456 MCSymbolData &SD = *it;
1457
1458 if (it->getFragment() != DF)
1459 continue;
1460
1461 if (SD.getOffset() > PrevOffset)
1462 SD.setOffset(SD.getOffset() + Amt);
1463 }
1464
1465 // Restart layout.
1466 //
1467 // FIXME: This is O(N^2), but will be eliminated once we have a smart
1468 // MCAsmLayout object.
1469 return true;
1470 }
1471 }
1472 }
1473
1474 return false;
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +00001475}
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001476
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001477// Debugging methods
1478
1479namespace llvm {
1480
1481raw_ostream &operator<<(raw_ostream &OS, const MCAsmFixup &AF) {
Daniel Dunbar2be2fd02010-02-13 09:28:54 +00001482 OS << "<MCAsmFixup" << " Offset:" << AF.Offset << " Value:" << *AF.Value
1483 << " Kind:" << AF.Kind << ">";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001484 return OS;
1485}
1486
1487}
1488
1489void MCFragment::dump() {
1490 raw_ostream &OS = llvm::errs();
1491
1492 OS << "<MCFragment " << (void*) this << " Offset:" << Offset
1493 << " FileSize:" << FileSize;
1494
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001495 OS << ">";
1496}
1497
1498void MCAlignFragment::dump() {
1499 raw_ostream &OS = llvm::errs();
1500
1501 OS << "<MCAlignFragment ";
1502 this->MCFragment::dump();
1503 OS << "\n ";
1504 OS << " Alignment:" << getAlignment()
1505 << " Value:" << getValue() << " ValueSize:" << getValueSize()
1506 << " MaxBytesToEmit:" << getMaxBytesToEmit() << ">";
1507}
1508
1509void MCDataFragment::dump() {
1510 raw_ostream &OS = llvm::errs();
1511
1512 OS << "<MCDataFragment ";
1513 this->MCFragment::dump();
1514 OS << "\n ";
1515 OS << " Contents:[";
1516 for (unsigned i = 0, e = getContents().size(); i != e; ++i) {
1517 if (i) OS << ",";
1518 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1519 }
Daniel Dunbar2be2fd02010-02-13 09:28:54 +00001520 OS << "] (" << getContents().size() << " bytes)";
Daniel Dunbar0bcf0742010-02-13 09:28:43 +00001521
1522 if (!getFixups().empty()) {
1523 OS << ",\n ";
1524 OS << " Fixups:[";
1525 for (fixup_iterator it = fixup_begin(), ie = fixup_end(); it != ie; ++it) {
Daniel Dunbar45aefff2010-03-09 01:12:23 +00001526 if (it != fixup_begin()) OS << ",\n ";
Daniel Dunbar0bcf0742010-02-13 09:28:43 +00001527 OS << *it;
1528 }
1529 OS << "]";
1530 }
1531
1532 OS << ">";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001533}
1534
1535void MCFillFragment::dump() {
1536 raw_ostream &OS = llvm::errs();
1537
1538 OS << "<MCFillFragment ";
1539 this->MCFragment::dump();
1540 OS << "\n ";
1541 OS << " Value:" << getValue() << " ValueSize:" << getValueSize()
1542 << " Count:" << getCount() << ">";
1543}
1544
1545void MCOrgFragment::dump() {
1546 raw_ostream &OS = llvm::errs();
1547
1548 OS << "<MCOrgFragment ";
1549 this->MCFragment::dump();
1550 OS << "\n ";
1551 OS << " Offset:" << getOffset() << " Value:" << getValue() << ">";
1552}
1553
1554void MCZeroFillFragment::dump() {
1555 raw_ostream &OS = llvm::errs();
1556
1557 OS << "<MCZeroFillFragment ";
1558 this->MCFragment::dump();
1559 OS << "\n ";
1560 OS << " Size:" << getSize() << " Alignment:" << getAlignment() << ">";
1561}
1562
1563void MCSectionData::dump() {
1564 raw_ostream &OS = llvm::errs();
1565
1566 OS << "<MCSectionData";
1567 OS << " Alignment:" << getAlignment() << " Address:" << Address
1568 << " Size:" << Size << " FileSize:" << FileSize
Daniel Dunbar45aefff2010-03-09 01:12:23 +00001569 << " Fragments:[\n ";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001570 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1571 if (it != begin()) OS << ",\n ";
1572 it->dump();
1573 }
1574 OS << "]>";
1575}
1576
1577void MCSymbolData::dump() {
1578 raw_ostream &OS = llvm::errs();
1579
1580 OS << "<MCSymbolData Symbol:" << getSymbol()
1581 << " Fragment:" << getFragment() << " Offset:" << getOffset()
1582 << " Flags:" << getFlags() << " Index:" << getIndex();
1583 if (isCommon())
1584 OS << " (common, size:" << getCommonSize()
1585 << " align: " << getCommonAlignment() << ")";
1586 if (isExternal())
1587 OS << " (external)";
1588 if (isPrivateExtern())
1589 OS << " (private extern)";
1590 OS << ">";
1591}
1592
1593void MCAssembler::dump() {
1594 raw_ostream &OS = llvm::errs();
1595
1596 OS << "<MCAssembler\n";
Daniel Dunbar45aefff2010-03-09 01:12:23 +00001597 OS << " Sections:[\n ";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001598 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1599 if (it != begin()) OS << ",\n ";
1600 it->dump();
1601 }
1602 OS << "],\n";
1603 OS << " Symbols:[";
1604
1605 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
Daniel Dunbar45aefff2010-03-09 01:12:23 +00001606 if (it != symbol_begin()) OS << ",\n ";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001607 it->dump();
1608 }
1609 OS << "]>\n";
1610}