blob: ff930156a047a688750bbc60aede0f7866750741 [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 Dunbardf3c8f22010-03-12 21:00:49 +000027#include "llvm/Target/TargetAsmBackend.h"
Daniel Dunbarf6346762010-02-13 09:29:02 +000028
29// FIXME: Gross.
30#include "../Target/X86/X86FixupKinds.h"
31
Chris Lattner23132b12009-08-24 03:52:50 +000032#include <vector>
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000033using namespace llvm;
34
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000035class MachObjectWriter;
36
Daniel Dunbar0adcd352009-08-25 21:10:45 +000037STATISTIC(EmittedFragments, "Number of emitted assembler fragments");
38
Daniel Dunbar8f4d1462009-08-28 07:08:35 +000039// FIXME FIXME FIXME: There are number of places in this file where we convert
40// what is a 64-bit assembler value used for computation into a value in the
41// object file, which may truncate it. We should detect that truncation where
42// invalid and report errors back.
43
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000044static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
45 MachObjectWriter &MOW);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000046
Kevin Enderby6e720482010-02-23 18:26:34 +000047static uint64_t WriteNopData(uint64_t Count, MachObjectWriter &MOW);
48
Daniel Dunbard5a8e982009-08-28 05:49:21 +000049/// isVirtualSection - Check if this is a section which does not actually exist
50/// in the object file.
51static bool isVirtualSection(const MCSection &Section) {
52 // FIXME: Lame.
53 const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
54 unsigned Type = SMO.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
55 return (Type == MCSectionMachO::S_ZEROFILL);
56}
57
Duncan Sands9a7795c2010-02-17 14:52:22 +000058static unsigned getFixupKindLog2Size(unsigned Kind) {
Daniel Dunbar2be2fd02010-02-13 09:28:54 +000059 switch (Kind) {
60 default: llvm_unreachable("invalid fixup kind!");
Daniel Dunbarf6346762010-02-13 09:29:02 +000061 case X86::reloc_pcrel_1byte:
Daniel Dunbar2be2fd02010-02-13 09:28:54 +000062 case FK_Data_1: return 0;
63 case FK_Data_2: return 1;
Daniel Dunbarf6346762010-02-13 09:29:02 +000064 case X86::reloc_pcrel_4byte:
65 case X86::reloc_riprel_4byte:
Daniel Dunbar2be2fd02010-02-13 09:28:54 +000066 case FK_Data_4: return 2;
67 case FK_Data_8: return 3;
68 }
69}
70
Duncan Sands9a7795c2010-02-17 14:52:22 +000071static bool isFixupKindPCRel(unsigned Kind) {
Daniel Dunbar591047f2010-02-13 09:45:59 +000072 switch (Kind) {
73 default:
74 return false;
75 case X86::reloc_pcrel_1byte:
76 case X86::reloc_pcrel_4byte:
77 case X86::reloc_riprel_4byte:
78 return true;
79 }
80}
81
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000082class MachObjectWriter {
83 // See <mach-o/loader.h>.
84 enum {
85 Header_Magic32 = 0xFEEDFACE,
86 Header_Magic64 = 0xFEEDFACF
87 };
Daniel Dunbar7eb85192009-10-16 01:58:15 +000088
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000089 static const unsigned Header32Size = 28;
90 static const unsigned Header64Size = 32;
91 static const unsigned SegmentLoadCommand32Size = 56;
92 static const unsigned Section32Size = 68;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000093 static const unsigned SymtabLoadCommandSize = 24;
94 static const unsigned DysymtabLoadCommandSize = 80;
95 static const unsigned Nlist32Size = 12;
Daniel Dunbar3f6a9602009-08-26 13:58:10 +000096 static const unsigned RelocationInfoSize = 8;
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000097
98 enum HeaderFileType {
99 HFT_Object = 0x1
100 };
101
Daniel Dunbar6009db42009-08-26 21:22:22 +0000102 enum HeaderFlags {
103 HF_SubsectionsViaSymbols = 0x2000
104 };
105
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000106 enum LoadCommandType {
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000107 LCT_Segment = 0x1,
108 LCT_Symtab = 0x2,
109 LCT_Dysymtab = 0xb
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000110 };
111
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000112 // See <mach-o/nlist.h>.
113 enum SymbolTypeType {
114 STT_Undefined = 0x00,
115 STT_Absolute = 0x02,
116 STT_Section = 0x0e
117 };
118
119 enum SymbolTypeFlags {
120 // If any of these bits are set, then the entry is a stab entry number (see
121 // <mach-o/stab.h>. Otherwise the other masks apply.
122 STF_StabsEntryMask = 0xe0,
123
124 STF_TypeMask = 0x0e,
125 STF_External = 0x01,
126 STF_PrivateExtern = 0x10
127 };
128
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000129 /// IndirectSymbolFlags - Flags for encoding special values in the indirect
130 /// symbol entry.
131 enum IndirectSymbolFlags {
132 ISF_Local = 0x80000000,
133 ISF_Absolute = 0x40000000
134 };
135
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000136 /// RelocationFlags - Special flags for addresses.
137 enum RelocationFlags {
138 RF_Scattered = 0x80000000
139 };
140
141 enum RelocationInfoType {
142 RIT_Vanilla = 0,
143 RIT_Pair = 1,
144 RIT_Difference = 2,
145 RIT_PreboundLazyPointer = 3,
146 RIT_LocalDifference = 4
147 };
148
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000149 /// MachSymbolData - Helper struct for containing some precomputed information
150 /// on symbols.
151 struct MachSymbolData {
152 MCSymbolData *SymbolData;
153 uint64_t StringIndex;
154 uint8_t SectionIndex;
155
156 // Support lexicographic sorting.
157 bool operator<(const MachSymbolData &RHS) const {
158 const std::string &Name = SymbolData->getSymbol().getName();
159 return Name < RHS.SymbolData->getSymbol().getName();
160 }
161 };
162
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000163 raw_ostream &OS;
164 bool IsLSB;
165
166public:
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000167 MachObjectWriter(raw_ostream &_OS, bool _IsLSB = true)
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000168 : OS(_OS), IsLSB(_IsLSB) {
169 }
170
171 /// @name Helper Methods
172 /// @{
173
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000174 void Write8(uint8_t Value) {
175 OS << char(Value);
176 }
177
178 void Write16(uint16_t Value) {
179 if (IsLSB) {
180 Write8(uint8_t(Value >> 0));
181 Write8(uint8_t(Value >> 8));
182 } else {
183 Write8(uint8_t(Value >> 8));
184 Write8(uint8_t(Value >> 0));
185 }
186 }
187
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000188 void Write32(uint32_t Value) {
189 if (IsLSB) {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000190 Write16(uint16_t(Value >> 0));
191 Write16(uint16_t(Value >> 16));
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000192 } else {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000193 Write16(uint16_t(Value >> 16));
194 Write16(uint16_t(Value >> 0));
195 }
196 }
197
198 void Write64(uint64_t Value) {
199 if (IsLSB) {
200 Write32(uint32_t(Value >> 0));
201 Write32(uint32_t(Value >> 32));
202 } else {
203 Write32(uint32_t(Value >> 32));
204 Write32(uint32_t(Value >> 0));
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000205 }
206 }
207
208 void WriteZeros(unsigned N) {
209 const char Zeros[16] = { 0 };
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000210
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000211 for (unsigned i = 0, e = N / 16; i != e; ++i)
212 OS << StringRef(Zeros, 16);
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000213
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000214 OS << StringRef(Zeros, N % 16);
215 }
216
Daniel Dunbar2928c832009-11-06 10:58:06 +0000217 void WriteString(StringRef Str, unsigned ZeroFillSize = 0) {
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000218 OS << Str;
219 if (ZeroFillSize)
220 WriteZeros(ZeroFillSize - Str.size());
221 }
222
223 /// @}
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000224
Daniel Dunbar6009db42009-08-26 21:22:22 +0000225 void WriteHeader32(unsigned NumLoadCommands, unsigned LoadCommandsSize,
226 bool SubsectionsViaSymbols) {
227 uint32_t Flags = 0;
228
229 if (SubsectionsViaSymbols)
230 Flags |= HF_SubsectionsViaSymbols;
231
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000232 // struct mach_header (28 bytes)
233
234 uint64_t Start = OS.tell();
235 (void) Start;
236
237 Write32(Header_Magic32);
238
239 // FIXME: Support cputype.
Chris Lattner45f8c092010-02-02 19:38:14 +0000240 Write32(MachO::CPUTypeI386);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000241 // FIXME: Support cpusubtype.
Chris Lattner45f8c092010-02-02 19:38:14 +0000242 Write32(MachO::CPUSubType_I386_ALL);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000243 Write32(HFT_Object);
Daniel Dunbar6009db42009-08-26 21:22:22 +0000244 Write32(NumLoadCommands); // Object files have a single load command, the
245 // segment.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000246 Write32(LoadCommandsSize);
Daniel Dunbar6009db42009-08-26 21:22:22 +0000247 Write32(Flags);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000248
249 assert(OS.tell() - Start == Header32Size);
250 }
251
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000252 /// WriteSegmentLoadCommand32 - Write a 32-bit segment load command.
253 ///
254 /// \arg NumSections - The number of sections in this segment.
255 /// \arg SectionDataSize - The total size of the sections.
256 void WriteSegmentLoadCommand32(unsigned NumSections,
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000257 uint64_t VMSize,
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000258 uint64_t SectionDataStartOffset,
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000259 uint64_t SectionDataSize) {
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000260 // struct segment_command (56 bytes)
261
262 uint64_t Start = OS.tell();
263 (void) Start;
264
265 Write32(LCT_Segment);
266 Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
267
268 WriteString("", 16);
269 Write32(0); // vmaddr
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000270 Write32(VMSize); // vmsize
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000271 Write32(SectionDataStartOffset); // file offset
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000272 Write32(SectionDataSize); // file size
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000273 Write32(0x7); // maxprot
274 Write32(0x7); // initprot
275 Write32(NumSections);
276 Write32(0); // flags
277
278 assert(OS.tell() - Start == SegmentLoadCommand32Size);
279 }
280
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000281 void WriteSection32(const MCSectionData &SD, uint64_t FileOffset,
282 uint64_t RelocationsStart, unsigned NumRelocations) {
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000283 // The offset is unused for virtual sections.
284 if (isVirtualSection(SD.getSection())) {
285 assert(SD.getFileSize() == 0 && "Invalid file size!");
286 FileOffset = 0;
287 }
288
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000289 // struct section (68 bytes)
290
291 uint64_t Start = OS.tell();
292 (void) Start;
293
294 // FIXME: cast<> support!
295 const MCSectionMachO &Section =
296 static_cast<const MCSectionMachO&>(SD.getSection());
297 WriteString(Section.getSectionName(), 16);
298 WriteString(Section.getSegmentName(), 16);
Daniel Dunbar5e835962009-08-26 02:48:04 +0000299 Write32(SD.getAddress()); // address
Daniel Dunbar6742e342009-08-26 04:13:32 +0000300 Write32(SD.getSize()); // size
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000301 Write32(FileOffset);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000302
Daniel Dunbare1ec6172010-02-02 21:44:01 +0000303 unsigned Flags = Section.getTypeAndAttributes();
304 if (SD.hasInstructions())
305 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
306
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000307 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
308 Write32(Log2_32(SD.getAlignment()));
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000309 Write32(NumRelocations ? RelocationsStart : 0);
310 Write32(NumRelocations);
Daniel Dunbare1ec6172010-02-02 21:44:01 +0000311 Write32(Flags);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000312 Write32(0); // reserved1
313 Write32(Section.getStubSize()); // reserved2
314
315 assert(OS.tell() - Start == Section32Size);
316 }
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000317
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000318 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
319 uint32_t StringTableOffset,
320 uint32_t StringTableSize) {
321 // struct symtab_command (24 bytes)
322
323 uint64_t Start = OS.tell();
324 (void) Start;
325
326 Write32(LCT_Symtab);
327 Write32(SymtabLoadCommandSize);
328 Write32(SymbolOffset);
329 Write32(NumSymbols);
330 Write32(StringTableOffset);
331 Write32(StringTableSize);
332
333 assert(OS.tell() - Start == SymtabLoadCommandSize);
334 }
335
336 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
337 uint32_t NumLocalSymbols,
338 uint32_t FirstExternalSymbol,
339 uint32_t NumExternalSymbols,
340 uint32_t FirstUndefinedSymbol,
341 uint32_t NumUndefinedSymbols,
342 uint32_t IndirectSymbolOffset,
343 uint32_t NumIndirectSymbols) {
344 // struct dysymtab_command (80 bytes)
345
346 uint64_t Start = OS.tell();
347 (void) Start;
348
349 Write32(LCT_Dysymtab);
350 Write32(DysymtabLoadCommandSize);
351 Write32(FirstLocalSymbol);
352 Write32(NumLocalSymbols);
353 Write32(FirstExternalSymbol);
354 Write32(NumExternalSymbols);
355 Write32(FirstUndefinedSymbol);
356 Write32(NumUndefinedSymbols);
357 Write32(0); // tocoff
358 Write32(0); // ntoc
359 Write32(0); // modtaboff
360 Write32(0); // nmodtab
361 Write32(0); // extrefsymoff
362 Write32(0); // nextrefsyms
363 Write32(IndirectSymbolOffset);
364 Write32(NumIndirectSymbols);
365 Write32(0); // extreloff
366 Write32(0); // nextrel
367 Write32(0); // locreloff
368 Write32(0); // nlocrel
369
370 assert(OS.tell() - Start == DysymtabLoadCommandSize);
371 }
372
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000373 void WriteNlist32(MachSymbolData &MSD) {
Daniel Dunbar5e835962009-08-26 02:48:04 +0000374 MCSymbolData &Data = *MSD.SymbolData;
Daniel Dunbarcb579b32009-08-31 08:08:06 +0000375 const MCSymbol &Symbol = Data.getSymbol();
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000376 uint8_t Type = 0;
Daniel Dunbar8f4d1462009-08-28 07:08:35 +0000377 uint16_t Flags = Data.getFlags();
378 uint32_t Address = 0;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000379
380 // Set the N_TYPE bits. See <mach-o/nlist.h>.
381 //
382 // FIXME: Are the prebound or indirect fields possible here?
383 if (Symbol.isUndefined())
384 Type = STT_Undefined;
385 else if (Symbol.isAbsolute())
386 Type = STT_Absolute;
387 else
388 Type = STT_Section;
389
390 // FIXME: Set STAB bits.
391
Daniel Dunbar5e835962009-08-26 02:48:04 +0000392 if (Data.isPrivateExtern())
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000393 Type |= STF_PrivateExtern;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000394
395 // Set external bit.
Daniel Dunbar5e835962009-08-26 02:48:04 +0000396 if (Data.isExternal() || Symbol.isUndefined())
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000397 Type |= STF_External;
398
Daniel Dunbar8f4d1462009-08-28 07:08:35 +0000399 // Compute the symbol address.
400 if (Symbol.isDefined()) {
401 if (Symbol.isAbsolute()) {
402 llvm_unreachable("FIXME: Not yet implemented!");
403 } else {
Daniel Dunbar8f0448c2010-03-11 18:22:51 +0000404 Address = Data.getAddress();
Daniel Dunbar8f4d1462009-08-28 07:08:35 +0000405 }
406 } else if (Data.isCommon()) {
407 // Common symbols are encoded with the size in the address
408 // field, and their alignment in the flags.
409 Address = Data.getCommonSize();
410
411 // Common alignment is packed into the 'desc' bits.
412 if (unsigned Align = Data.getCommonAlignment()) {
413 unsigned Log2Size = Log2_32(Align);
414 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
415 if (Log2Size > 15)
416 llvm_report_error("invalid 'common' alignment '" +
417 Twine(Align) + "'");
418 // FIXME: Keep this mask with the SymbolFlags enumeration.
419 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
420 }
421 }
422
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000423 // struct nlist (12 bytes)
424
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000425 Write32(MSD.StringIndex);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000426 Write8(Type);
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000427 Write8(MSD.SectionIndex);
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000428
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000429 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
430 // value.
Daniel Dunbar8f4d1462009-08-28 07:08:35 +0000431 Write16(Flags);
Daniel Dunbar5e835962009-08-26 02:48:04 +0000432 Write32(Address);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000433 }
434
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000435 struct MachRelocationEntry {
436 uint32_t Word0;
437 uint32_t Word1;
438 };
Daniel Dunbarcb7d7432010-02-11 21:29:46 +0000439 void ComputeScatteredRelocationInfo(MCAssembler &Asm, MCFragment &Fragment,
Daniel Dunbar27ade182010-02-11 21:29:29 +0000440 MCAsmFixup &Fixup,
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000441 const MCValue &Target,
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000442 std::vector<MachRelocationEntry> &Relocs) {
Daniel Dunbarcb7d7432010-02-11 21:29:46 +0000443 uint32_t Address = Fragment.getOffset() + Fixup.Offset;
Daniel Dunbare180fa92010-03-09 21:27:30 +0000444 unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
Daniel Dunbareb3804e2010-02-17 23:45:16 +0000445 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000446 unsigned Type = RIT_Vanilla;
447
448 // See <reloc.h>.
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000449 const MCSymbol *A = Target.getSymA();
Daniel Dunbar2101d9c2010-03-10 20:58:31 +0000450 MCSymbolData *A_SD = &Asm.getSymbolData(*A);
Daniel Dunbar0ce6bd52010-03-08 21:10:39 +0000451
Daniel Dunbara015c1c2010-03-10 00:58:25 +0000452 if (!A_SD->getFragment())
Daniel Dunbar0ce6bd52010-03-08 21:10:39 +0000453 llvm_report_error("symbol '" + A->getName() +
454 "' can not be undefined in a subtraction expression");
455
Daniel Dunbar8f0448c2010-03-11 18:22:51 +0000456 uint32_t Value = A_SD->getAddress();
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000457 uint32_t Value2 = 0;
458
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000459 if (const MCSymbol *B = Target.getSymB()) {
Daniel Dunbar2101d9c2010-03-10 20:58:31 +0000460 MCSymbolData *B_SD = &Asm.getSymbolData(*B);
Daniel Dunbar0ce6bd52010-03-08 21:10:39 +0000461
Daniel Dunbara015c1c2010-03-10 00:58:25 +0000462 if (!B_SD->getFragment())
Daniel Dunbar0ce6bd52010-03-08 21:10:39 +0000463 llvm_report_error("symbol '" + B->getName() +
464 "' can not be undefined in a subtraction expression");
465
Daniel Dunbar07a96412010-03-10 02:10:29 +0000466 // Select the appropriate difference relocation type.
467 //
468 // Note that there is no longer any semantic difference between these two
469 // relocation types from the linkers point of view, this is done solely
470 // for pedantic compatibility with 'as'.
Daniel Dunbara015c1c2010-03-10 00:58:25 +0000471 Type = A_SD->isExternal() ? RIT_Difference : RIT_LocalDifference;
Daniel Dunbar8f0448c2010-03-11 18:22:51 +0000472 Value2 = B_SD->getAddress();
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000473 }
474
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000475 MachRelocationEntry MRE;
476 MRE.Word0 = ((Address << 0) |
477 (Type << 24) |
478 (Log2Size << 28) |
479 (IsPCRel << 30) |
480 RF_Scattered);
481 MRE.Word1 = Value;
482 Relocs.push_back(MRE);
483
Daniel Dunbara015c1c2010-03-10 00:58:25 +0000484 if (Type == RIT_Difference || Type == RIT_LocalDifference) {
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000485 MachRelocationEntry MRE;
486 MRE.Word0 = ((0 << 0) |
Daniel Dunbaraef9d7a2010-03-09 21:27:47 +0000487 (RIT_Pair << 24) |
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000488 (Log2Size << 28) |
Daniel Dunbaraef9d7a2010-03-09 21:27:47 +0000489 (IsPCRel << 30) |
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000490 RF_Scattered);
491 MRE.Word1 = Value2;
492 Relocs.push_back(MRE);
493 }
494 }
495
Daniel Dunbar0bcf0742010-02-13 09:28:43 +0000496 void ComputeRelocationInfo(MCAssembler &Asm, MCDataFragment &Fragment,
Daniel Dunbar27ade182010-02-11 21:29:29 +0000497 MCAsmFixup &Fixup,
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000498 std::vector<MachRelocationEntry> &Relocs) {
Daniel Dunbarf3a066f2010-03-09 21:27:58 +0000499 unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
500 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
501
Daniel Dunbar18ff2cc2010-03-11 05:53:33 +0000502 // FIXME: Share layout object.
503 MCAsmLayout Layout(Asm);
504
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000505 // Evaluate the fixup; if the value was resolved, no relocation is needed.
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000506 MCValue Target;
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000507 if (Asm.EvaluateFixup(Layout, Fixup, &Fragment, Target, Fixup.FixedValue))
508 return;
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000509
Daniel Dunbarf3a066f2010-03-09 21:27:58 +0000510 // If this is a difference or a defined symbol plus an offset, then we need
511 // a scattered relocation entry.
512 uint32_t Offset = Target.getConstant();
513 if (IsPCRel)
514 Offset += 1 << Log2Size;
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000515 if (Target.getSymB() ||
516 (Target.getSymA() && !Target.getSymA()->isUndefined() &&
Daniel Dunbarf3a066f2010-03-09 21:27:58 +0000517 Offset))
Daniel Dunbarcb7d7432010-02-11 21:29:46 +0000518 return ComputeScatteredRelocationInfo(Asm, Fragment, Fixup, Target,
Daniel Dunbar2101d9c2010-03-10 20:58:31 +0000519 Relocs);
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000520
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000521 // See <reloc.h>.
Daniel Dunbarcb7d7432010-02-11 21:29:46 +0000522 uint32_t Address = Fragment.getOffset() + Fixup.Offset;
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000523 uint32_t Value = 0;
524 unsigned Index = 0;
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000525 unsigned IsExtern = 0;
526 unsigned Type = 0;
527
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000528 if (Target.isAbsolute()) { // constant
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000529 // SymbolNum of 0 indicates the absolute section.
Daniel Dunbar3a30b822010-02-13 09:28:15 +0000530 //
Daniel Dunbar979ba5b2010-03-11 05:53:37 +0000531 // FIXME: Currently, these are never generated (see code below). I cannot
532 // find a case where they are actually emitted.
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000533 Type = RIT_Vanilla;
534 Value = 0;
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000535 } else {
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000536 const MCSymbol *Symbol = Target.getSymA();
Daniel Dunbar2101d9c2010-03-10 20:58:31 +0000537 MCSymbolData *SD = &Asm.getSymbolData(*Symbol);
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000538
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000539 if (Symbol->isUndefined()) {
540 IsExtern = 1;
541 Index = SD->getIndex();
542 Value = 0;
543 } else {
544 // The index is the section ordinal.
545 //
546 // FIXME: O(N)
547 Index = 1;
Daniel Dunbar591047f2010-02-13 09:45:59 +0000548 MCAssembler::iterator it = Asm.begin(), ie = Asm.end();
549 for (; it != ie; ++it, ++Index)
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000550 if (&*it == SD->getFragment()->getParent())
551 break;
Daniel Dunbar591047f2010-02-13 09:45:59 +0000552 assert(it != ie && "Unable to find section index!");
Daniel Dunbar8f0448c2010-03-11 18:22:51 +0000553 Value = SD->getAddress();
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000554 }
555
556 Type = RIT_Vanilla;
557 }
558
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000559 // struct relocation_info (8 bytes)
560 MachRelocationEntry MRE;
561 MRE.Word0 = Address;
562 MRE.Word1 = ((Index << 0) |
563 (IsPCRel << 24) |
564 (Log2Size << 25) |
565 (IsExtern << 27) |
566 (Type << 28));
567 Relocs.push_back(MRE);
568 }
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000569
Daniel Dunbar2101d9c2010-03-10 20:58:31 +0000570 void BindIndirectSymbols(MCAssembler &Asm) {
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000571 // This is the point where 'as' creates actual symbols for indirect symbols
572 // (in the following two passes). It would be easier for us to do this
573 // sooner when we see the attribute, but that makes getting the order in the
574 // symbol table much more complicated than it is worth.
575 //
576 // FIXME: Revisit this when the dust settles.
577
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000578 // Bind non lazy symbol pointers first.
579 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
580 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
581 // FIXME: cast<> support!
582 const MCSectionMachO &Section =
583 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
584
585 unsigned Type =
586 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
587 if (Type != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
588 continue;
589
Daniel Dunbar2101d9c2010-03-10 20:58:31 +0000590 Asm.getOrCreateSymbolData(*it->Symbol);
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000591 }
592
593 // Then lazy symbol pointers and symbol stubs.
594 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
595 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
596 // FIXME: cast<> support!
597 const MCSectionMachO &Section =
598 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
599
600 unsigned Type =
601 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
602 if (Type != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
603 Type != MCSectionMachO::S_SYMBOL_STUBS)
604 continue;
605
Daniel Dunbar2101d9c2010-03-10 20:58:31 +0000606 // Set the symbol type to undefined lazy, but only on construction.
607 //
608 // FIXME: Do not hardcode.
609 bool Created;
610 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
611 if (Created)
612 Entry.setFlags(Entry.getFlags() | 0x0001);
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000613 }
614 }
615
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000616 /// ComputeSymbolTable - Compute the symbol table data
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000617 ///
618 /// \param StringTable [out] - The string table data.
619 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
620 /// string table.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000621 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
622 std::vector<MachSymbolData> &LocalSymbolData,
623 std::vector<MachSymbolData> &ExternalSymbolData,
624 std::vector<MachSymbolData> &UndefinedSymbolData) {
625 // Build section lookup table.
626 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
627 unsigned Index = 1;
628 for (MCAssembler::iterator it = Asm.begin(),
629 ie = Asm.end(); it != ie; ++it, ++Index)
630 SectionIndexMap[&it->getSection()] = Index;
631 assert(Index <= 256 && "Too many sections!");
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000632
633 // Index 0 is always the empty string.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000634 StringMap<uint64_t> StringIndexMap;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000635 StringTable += '\x00';
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000636
637 // Build the symbol arrays and the string table, but only for non-local
638 // symbols.
639 //
640 // The particular order that we collect the symbols and create the string
641 // table, then sort the symbols is chosen to match 'as'. Even though it
642 // doesn't matter for correctness, this is important for letting us diff .o
643 // files.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000644 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
645 ie = Asm.symbol_end(); it != ie; ++it) {
Daniel Dunbarcb579b32009-08-31 08:08:06 +0000646 const MCSymbol &Symbol = it->getSymbol();
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000647
Daniel Dunbar959fd882009-08-26 22:13:22 +0000648 // Ignore assembler temporaries.
649 if (it->getSymbol().isTemporary())
650 continue;
651
Daniel Dunbar50e48b32009-08-24 08:39:57 +0000652 if (!it->isExternal() && !Symbol.isUndefined())
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000653 continue;
654
655 uint64_t &Entry = StringIndexMap[Symbol.getName()];
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000656 if (!Entry) {
657 Entry = StringTable.size();
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000658 StringTable += Symbol.getName();
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000659 StringTable += '\x00';
660 }
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000661
662 MachSymbolData MSD;
663 MSD.SymbolData = it;
664 MSD.StringIndex = Entry;
665
666 if (Symbol.isUndefined()) {
667 MSD.SectionIndex = 0;
668 UndefinedSymbolData.push_back(MSD);
669 } else if (Symbol.isAbsolute()) {
670 MSD.SectionIndex = 0;
671 ExternalSymbolData.push_back(MSD);
672 } else {
673 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
674 assert(MSD.SectionIndex && "Invalid section index!");
675 ExternalSymbolData.push_back(MSD);
676 }
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000677 }
678
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000679 // Now add the data for local symbols.
680 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
681 ie = Asm.symbol_end(); it != ie; ++it) {
Daniel Dunbarcb579b32009-08-31 08:08:06 +0000682 const MCSymbol &Symbol = it->getSymbol();
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000683
Daniel Dunbar959fd882009-08-26 22:13:22 +0000684 // Ignore assembler temporaries.
685 if (it->getSymbol().isTemporary())
686 continue;
687
Daniel Dunbar50e48b32009-08-24 08:39:57 +0000688 if (it->isExternal() || Symbol.isUndefined())
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000689 continue;
690
691 uint64_t &Entry = StringIndexMap[Symbol.getName()];
692 if (!Entry) {
693 Entry = StringTable.size();
694 StringTable += Symbol.getName();
695 StringTable += '\x00';
696 }
697
698 MachSymbolData MSD;
699 MSD.SymbolData = it;
700 MSD.StringIndex = Entry;
701
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000702 if (Symbol.isAbsolute()) {
703 MSD.SectionIndex = 0;
704 LocalSymbolData.push_back(MSD);
705 } else {
706 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
707 assert(MSD.SectionIndex && "Invalid section index!");
708 LocalSymbolData.push_back(MSD);
709 }
710 }
711
712 // External and undefined symbols are required to be in lexicographic order.
713 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
714 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
715
Daniel Dunbarbe963552009-08-26 13:57:54 +0000716 // Set the symbol indices.
717 Index = 0;
718 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
719 LocalSymbolData[i].SymbolData->setIndex(Index++);
720 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
721 ExternalSymbolData[i].SymbolData->setIndex(Index++);
722 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
723 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
724
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000725 // The string table is padded to a multiple of 4.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000726 while (StringTable.size() % 4)
727 StringTable += '\x00';
728 }
729
730 void WriteObject(MCAssembler &Asm) {
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000731 unsigned NumSections = Asm.size();
732
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000733 // Create symbol data for any indirect symbols.
Daniel Dunbar2101d9c2010-03-10 20:58:31 +0000734 BindIndirectSymbols(Asm);
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000735
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000736 // Compute symbol table information.
737 SmallString<256> StringTable;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000738 std::vector<MachSymbolData> LocalSymbolData;
739 std::vector<MachSymbolData> ExternalSymbolData;
740 std::vector<MachSymbolData> UndefinedSymbolData;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000741 unsigned NumSymbols = Asm.symbol_size();
742
743 // No symbol table command is written if there are no symbols.
744 if (NumSymbols)
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000745 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
746 UndefinedSymbolData);
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000747
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000748 // The section data starts after the header, the segment load command (and
749 // section headers) and the symbol table.
750 unsigned NumLoadCommands = 1;
751 uint64_t LoadCommandsSize =
752 SegmentLoadCommand32Size + NumSections * Section32Size;
753
754 // Add the symbol table load command sizes, if used.
755 if (NumSymbols) {
756 NumLoadCommands += 2;
757 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
758 }
759
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000760 // Compute the total size of the section data, as well as its file size and
761 // vm size.
Daniel Dunbar6742e342009-08-26 04:13:32 +0000762 uint64_t SectionDataStart = Header32Size + LoadCommandsSize;
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000763 uint64_t SectionDataSize = 0;
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000764 uint64_t SectionDataFileSize = 0;
765 uint64_t VMSize = 0;
766 for (MCAssembler::iterator it = Asm.begin(),
767 ie = Asm.end(); it != ie; ++it) {
768 MCSectionData &SD = *it;
769
770 VMSize = std::max(VMSize, SD.getAddress() + SD.getSize());
771
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000772 if (isVirtualSection(SD.getSection()))
773 continue;
774
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000775 SectionDataSize = std::max(SectionDataSize,
776 SD.getAddress() + SD.getSize());
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000777 SectionDataFileSize = std::max(SectionDataFileSize,
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000778 SD.getAddress() + SD.getFileSize());
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000779 }
780
Daniel Dunbar6b716532010-02-09 23:00:14 +0000781 // The section data is padded to 4 bytes.
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000782 //
783 // FIXME: Is this machine dependent?
784 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
785 SectionDataFileSize += SectionDataPadding;
786
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000787 // Write the prolog, starting with the header and load command...
Daniel Dunbar6009db42009-08-26 21:22:22 +0000788 WriteHeader32(NumLoadCommands, LoadCommandsSize,
789 Asm.getSubsectionsViaSymbols());
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000790 WriteSegmentLoadCommand32(NumSections, VMSize,
791 SectionDataStart, SectionDataSize);
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000792
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000793 // ... and then the section headers.
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000794 //
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000795 // We also compute the section relocations while we do this. Note that
Daniel Dunbar6b716532010-02-09 23:00:14 +0000796 // computing relocation info will also update the fixup to have the correct
797 // value; this will overwrite the appropriate data in the fragment when it
798 // is written.
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000799 std::vector<MachRelocationEntry> RelocInfos;
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000800 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
Daniel Dunbarcb7d7432010-02-11 21:29:46 +0000801 for (MCAssembler::iterator it = Asm.begin(),
802 ie = Asm.end(); it != ie; ++it) {
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000803 MCSectionData &SD = *it;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000804
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000805 // The assembler writes relocations in the reverse order they were seen.
806 //
807 // FIXME: It is probably more complicated than this.
808 unsigned NumRelocsStart = RelocInfos.size();
Daniel Dunbarcb7d7432010-02-11 21:29:46 +0000809 for (MCSectionData::reverse_iterator it2 = SD.rbegin(),
810 ie2 = SD.rend(); it2 != ie2; ++it2)
Daniel Dunbar0bcf0742010-02-13 09:28:43 +0000811 if (MCDataFragment *DF = dyn_cast<MCDataFragment>(&*it2))
812 for (unsigned i = 0, e = DF->fixup_size(); i != e; ++i)
813 ComputeRelocationInfo(Asm, *DF, DF->getFixups()[e - i - 1],
Daniel Dunbar2101d9c2010-03-10 20:58:31 +0000814 RelocInfos);
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000815
816 unsigned NumRelocs = RelocInfos.size() - NumRelocsStart;
817 uint64_t SectionStart = SectionDataStart + SD.getAddress();
818 WriteSection32(SD, SectionStart, RelocTableEnd, NumRelocs);
819 RelocTableEnd += NumRelocs * RelocationInfoSize;
820 }
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000821
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000822 // Write the symbol table load command, if used.
823 if (NumSymbols) {
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000824 unsigned FirstLocalSymbol = 0;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000825 unsigned NumLocalSymbols = LocalSymbolData.size();
826 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
827 unsigned NumExternalSymbols = ExternalSymbolData.size();
828 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
829 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000830 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
831 unsigned NumSymTabSymbols =
832 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
833 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
834 uint64_t IndirectSymbolOffset = 0;
835
836 // If used, the indirect symbols are written after the section data.
837 if (NumIndirectSymbols)
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000838 IndirectSymbolOffset = RelocTableEnd;
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000839
840 // The symbol table is written after the indirect symbol data.
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000841 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000842
843 // The string table is written after symbol table.
844 uint64_t StringTableOffset =
845 SymbolTableOffset + NumSymTabSymbols * Nlist32Size;
846 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
847 StringTableOffset, StringTable.size());
848
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000849 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
850 FirstExternalSymbol, NumExternalSymbols,
851 FirstUndefinedSymbol, NumUndefinedSymbols,
852 IndirectSymbolOffset, NumIndirectSymbols);
853 }
854
855 // Write the actual section data.
856 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
857 WriteFileData(OS, *it, *this);
858
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000859 // Write the extra padding.
860 WriteZeros(SectionDataPadding);
861
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000862 // Write the relocation entries.
863 for (unsigned i = 0, e = RelocInfos.size(); i != e; ++i) {
864 Write32(RelocInfos[i].Word0);
865 Write32(RelocInfos[i].Word1);
866 }
867
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000868 // Write the symbol table data, if used.
869 if (NumSymbols) {
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000870 // Write the indirect symbol entries.
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000871 for (MCAssembler::indirect_symbol_iterator
872 it = Asm.indirect_symbol_begin(),
873 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
874 // Indirect symbols in the non lazy symbol pointer section have some
875 // special handling.
876 const MCSectionMachO &Section =
877 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
878 unsigned Type =
879 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
880 if (Type == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
881 // If this symbol is defined and internal, mark it as such.
882 if (it->Symbol->isDefined() &&
Daniel Dunbar2101d9c2010-03-10 20:58:31 +0000883 !Asm.getSymbolData(*it->Symbol).isExternal()) {
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000884 uint32_t Flags = ISF_Local;
885 if (it->Symbol->isAbsolute())
886 Flags |= ISF_Absolute;
887 Write32(Flags);
888 continue;
889 }
890 }
891
Daniel Dunbar2101d9c2010-03-10 20:58:31 +0000892 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000893 }
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000894
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000895 // FIXME: Check that offsets match computed ones.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000896
897 // Write the symbol table entries.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000898 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
899 WriteNlist32(LocalSymbolData[i]);
900 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
901 WriteNlist32(ExternalSymbolData[i]);
902 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
903 WriteNlist32(UndefinedSymbolData[i]);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000904
905 // Write the string table.
906 OS << StringTable.str();
907 }
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000908 }
Daniel Dunbar3a30b822010-02-13 09:28:15 +0000909
910 void ApplyFixup(const MCAsmFixup &Fixup, MCDataFragment &DF) {
Daniel Dunbar2be2fd02010-02-13 09:28:54 +0000911 unsigned Size = 1 << getFixupKindLog2Size(Fixup.Kind);
912
Daniel Dunbar3a30b822010-02-13 09:28:15 +0000913 // FIXME: Endianness assumption.
Daniel Dunbar2be2fd02010-02-13 09:28:54 +0000914 assert(Fixup.Offset + Size <= DF.getContents().size() &&
915 "Invalid fixup offset!");
916 for (unsigned i = 0; i != Size; ++i)
Daniel Dunbar3a30b822010-02-13 09:28:15 +0000917 DF.getContents()[Fixup.Offset + i] = uint8_t(Fixup.FixedValue >> (i * 8));
918 }
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000919};
920
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000921/* *** */
922
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000923MCFragment::MCFragment() : Kind(FragmentType(~0)) {
924}
925
Daniel Dunbar5e835962009-08-26 02:48:04 +0000926MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000927 : Kind(_Kind),
Daniel Dunbar5e835962009-08-26 02:48:04 +0000928 Parent(_Parent),
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000929 FileSize(~UINT64_C(0))
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000930{
Daniel Dunbar5e835962009-08-26 02:48:04 +0000931 if (Parent)
932 Parent->getFragmentList().push_back(this);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000933}
934
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000935MCFragment::~MCFragment() {
936}
937
Daniel Dunbar5e835962009-08-26 02:48:04 +0000938uint64_t MCFragment::getAddress() const {
939 assert(getParent() && "Missing Section!");
940 return getParent()->getAddress() + Offset;
941}
942
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000943/* *** */
944
Daniel Dunbar81e40002009-08-27 00:38:04 +0000945MCSectionData::MCSectionData() : Section(0) {}
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000946
947MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
Daniel Dunbar81e40002009-08-27 00:38:04 +0000948 : Section(&_Section),
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000949 Alignment(1),
Daniel Dunbar5e835962009-08-26 02:48:04 +0000950 Address(~UINT64_C(0)),
Daniel Dunbar6742e342009-08-26 04:13:32 +0000951 Size(~UINT64_C(0)),
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000952 FileSize(~UINT64_C(0)),
Daniel Dunbare1ec6172010-02-02 21:44:01 +0000953 HasInstructions(false)
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000954{
955 if (A)
956 A->getSectionList().push_back(this);
957}
958
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000959/* *** */
960
Daniel Dunbarefbb5332009-09-01 04:09:03 +0000961MCSymbolData::MCSymbolData() : Symbol(0) {}
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000962
Daniel Dunbarcb579b32009-08-31 08:08:06 +0000963MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000964 uint64_t _Offset, MCAssembler *A)
Daniel Dunbarefbb5332009-09-01 04:09:03 +0000965 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
Daniel Dunbar8f4d1462009-08-28 07:08:35 +0000966 IsExternal(false), IsPrivateExtern(false),
967 CommonSize(0), CommonAlign(0), Flags(0), Index(0)
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000968{
969 if (A)
970 A->getSymbolList().push_back(this);
971}
972
973/* *** */
974
Daniel Dunbar1f3e4452010-03-11 01:34:27 +0000975MCAssembler::MCAssembler(MCContext &_Context, TargetAsmBackend &_Backend,
976 raw_ostream &_OS)
977 : Context(_Context), Backend(_Backend), OS(_OS), SubsectionsViaSymbols(false)
Daniel Dunbar6009db42009-08-26 21:22:22 +0000978{
979}
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000980
981MCAssembler::~MCAssembler() {
982}
983
Daniel Dunbardf3c8f22010-03-12 21:00:49 +0000984bool MCAssembler::EvaluateFixup(const MCAsmLayout &Layout, MCAsmFixup &Fixup,
985 MCDataFragment *DF,
986 MCValue &Target, uint64_t &Value) const {
987 if (!Fixup.Value->EvaluateAsRelocatable(Target, &Layout))
988 llvm_report_error("expected relocatable expression");
989
990 // FIXME: How do non-scattered symbols work in ELF? I presume the linker
991 // doesn't support small relocations, but then under what criteria does the
992 // assembler allow symbol differences?
993
994 Value = Target.getConstant();
995
996 // FIXME: This "resolved" check isn't quite right. The assumption is that if
997 // we have a PCrel access to a temporary, then that temporary is in the same
998 // atom, and so the value is resolved. We need explicit atom's to implement
999 // this more precisely.
1000 bool IsResolved = true, IsPCRel = isFixupKindPCRel(Fixup.Kind);
1001 if (const MCSymbol *Symbol = Target.getSymA()) {
1002 if (Symbol->isDefined())
1003 Value += getSymbolData(*Symbol).getAddress();
1004 else
1005 IsResolved = false;
1006
1007 // With scattered symbols, we assume anything that isn't a PCrel temporary
1008 // access can have an arbitrary value.
1009 if (getBackend().hasScatteredSymbols() &&
1010 (!IsPCRel || !Symbol->isTemporary()))
1011 IsResolved = false;
1012 }
1013 if (const MCSymbol *Symbol = Target.getSymB()) {
1014 if (Symbol->isDefined())
1015 Value -= getSymbolData(*Symbol).getAddress();
1016 else
1017 IsResolved = false;
1018
1019 // With scattered symbols, we assume anything that isn't a PCrel temporary
1020 // access can have an arbitrary value.
1021 if (getBackend().hasScatteredSymbols() &&
1022 (!IsPCRel || !Symbol->isTemporary()))
1023 IsResolved = false;
1024 }
1025
1026 if (IsPCRel)
1027 Value -= DF->getOffset() + Fixup.Offset;
1028
1029 return IsResolved;
1030}
1031
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001032void MCAssembler::LayoutSection(MCSectionData &SD) {
Daniel Dunbar18ff2cc2010-03-11 05:53:33 +00001033 MCAsmLayout Layout(*this);
Daniel Dunbar6742e342009-08-26 04:13:32 +00001034 uint64_t Address = SD.getAddress();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001035
1036 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
1037 MCFragment &F = *it;
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001038
Daniel Dunbar6742e342009-08-26 04:13:32 +00001039 F.setOffset(Address - SD.getAddress());
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001040
1041 // Evaluate fragment size.
1042 switch (F.getKind()) {
1043 case MCFragment::FT_Align: {
1044 MCAlignFragment &AF = cast<MCAlignFragment>(F);
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001045
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001046 uint64_t Size = OffsetToAlignment(Address, AF.getAlignment());
Daniel Dunbar6742e342009-08-26 04:13:32 +00001047 if (Size > AF.getMaxBytesToEmit())
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001048 AF.setFileSize(0);
1049 else
Daniel Dunbar6742e342009-08-26 04:13:32 +00001050 AF.setFileSize(Size);
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001051 break;
1052 }
1053
1054 case MCFragment::FT_Data:
Daniel Dunbara4766d72010-02-13 09:28:32 +00001055 case MCFragment::FT_Fill:
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001056 F.setFileSize(F.getMaxFileSize());
1057 break;
1058
1059 case MCFragment::FT_Org: {
1060 MCOrgFragment &OF = cast<MCOrgFragment>(F);
1061
Daniel Dunbar18ff2cc2010-03-11 05:53:33 +00001062 int64_t TargetLocation;
1063 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, &Layout))
1064 llvm_report_error("expected assembly-time absolute expression");
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001065
1066 // FIXME: We need a way to communicate this error.
Daniel Dunbar18ff2cc2010-03-11 05:53:33 +00001067 int64_t Offset = TargetLocation - F.getOffset();
1068 if (Offset < 0)
1069 llvm_report_error("invalid .org offset '" + Twine(TargetLocation) +
1070 "' (at offset '" + Twine(F.getOffset()) + "'");
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001071
Daniel Dunbar18ff2cc2010-03-11 05:53:33 +00001072 F.setFileSize(Offset);
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001073 break;
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001074 }
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001075
1076 case MCFragment::FT_ZeroFill: {
1077 MCZeroFillFragment &ZFF = cast<MCZeroFillFragment>(F);
1078
1079 // Align the fragment offset; it is safe to adjust the offset freely since
1080 // this is only in virtual sections.
Daniel Dunbar37fad5c2010-03-08 21:10:42 +00001081 Address = RoundUpToAlignment(Address, ZFF.getAlignment());
1082 F.setOffset(Address - SD.getAddress());
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001083
1084 // FIXME: This is misnamed.
1085 F.setFileSize(ZFF.getSize());
1086 break;
1087 }
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001088 }
1089
Daniel Dunbar6742e342009-08-26 04:13:32 +00001090 Address += F.getFileSize();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001091 }
1092
Daniel Dunbar6742e342009-08-26 04:13:32 +00001093 // Set the section sizes.
1094 SD.setSize(Address - SD.getAddress());
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001095 if (isVirtualSection(SD.getSection()))
1096 SD.setFileSize(0);
1097 else
1098 SD.setFileSize(Address - SD.getAddress());
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001099}
1100
Kevin Enderby6e720482010-02-23 18:26:34 +00001101/// WriteNopData - Write optimal nops to the output file for the \arg Count
1102/// bytes. This returns the number of bytes written. It may return 0 if
1103/// the \arg Count is more than the maximum optimal nops.
1104///
1105/// FIXME this is X86 32-bit specific and should move to a better place.
1106static uint64_t WriteNopData(uint64_t Count, MachObjectWriter &MOW) {
Kevin Enderby76687082010-02-23 21:41:24 +00001107 static const uint8_t Nops[16][16] = {
1108 // nop
1109 {0x90},
1110 // xchg %ax,%ax
1111 {0x66, 0x90},
1112 // nopl (%[re]ax)
1113 {0x0f, 0x1f, 0x00},
1114 // nopl 0(%[re]ax)
1115 {0x0f, 0x1f, 0x40, 0x00},
1116 // nopl 0(%[re]ax,%[re]ax,1)
1117 {0x0f, 0x1f, 0x44, 0x00, 0x00},
1118 // nopw 0(%[re]ax,%[re]ax,1)
1119 {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1120 // nopl 0L(%[re]ax)
1121 {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1122 // nopl 0L(%[re]ax,%[re]ax,1)
1123 {0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1124 // nopw 0L(%[re]ax,%[re]ax,1)
1125 {0x66, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1126 // nopw %cs:0L(%[re]ax,%[re]ax,1)
1127 {0x66, 0x2e, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1128 // nopl 0(%[re]ax,%[re]ax,1)
1129 // nopw 0(%[re]ax,%[re]ax,1)
1130 {0x0f, 0x1f, 0x44, 0x00, 0x00,
1131 0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1132 // nopw 0(%[re]ax,%[re]ax,1)
1133 // nopw 0(%[re]ax,%[re]ax,1)
1134 {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00,
1135 0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1136 // nopw 0(%[re]ax,%[re]ax,1)
1137 // nopl 0L(%[re]ax) */
1138 {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00,
1139 0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1140 // nopl 0L(%[re]ax)
1141 // nopl 0L(%[re]ax)
1142 {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00,
1143 0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1144 // nopl 0L(%[re]ax)
1145 // nopl 0L(%[re]ax,%[re]ax,1)
1146 {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00,
1147 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00}
1148 };
1149
1150 if (Count > 15)
1151 return 0;
1152
Kevin Enderby6e720482010-02-23 18:26:34 +00001153 for (uint64_t i = 0; i < Count; i++)
Kevin Enderby76687082010-02-23 21:41:24 +00001154 MOW.Write8 (uint8_t(Nops[Count - 1][i]));
Kevin Enderby6e720482010-02-23 18:26:34 +00001155
1156 return Count;
1157}
1158
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001159/// WriteFileData - Write the \arg F data to the output file.
1160static void WriteFileData(raw_ostream &OS, const MCFragment &F,
1161 MachObjectWriter &MOW) {
1162 uint64_t Start = OS.tell();
1163 (void) Start;
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001164
Daniel Dunbar0adcd352009-08-25 21:10:45 +00001165 ++EmittedFragments;
1166
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001167 // FIXME: Embed in fragments instead?
1168 switch (F.getKind()) {
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001169 case MCFragment::FT_Align: {
1170 MCAlignFragment &AF = cast<MCAlignFragment>(F);
1171 uint64_t Count = AF.getFileSize() / AF.getValueSize();
1172
1173 // FIXME: This error shouldn't actually occur (the front end should emit
1174 // multiple .align directives to enforce the semantics it wants), but is
1175 // severe enough that we want to report it. How to handle this?
1176 if (Count * AF.getValueSize() != AF.getFileSize())
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001177 llvm_report_error("undefined .align directive, value size '" +
1178 Twine(AF.getValueSize()) +
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001179 "' is not a divisor of padding size '" +
1180 Twine(AF.getFileSize()) + "'");
1181
Kevin Enderby6e720482010-02-23 18:26:34 +00001182 // See if we are aligning with nops, and if so do that first to try to fill
1183 // the Count bytes. Then if that did not fill any bytes or there are any
1184 // bytes left to fill use the the Value and ValueSize to fill the rest.
1185 if (AF.getEmitNops()) {
1186 uint64_t NopByteCount = WriteNopData(Count, MOW);
1187 Count -= NopByteCount;
1188 }
1189
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001190 for (uint64_t i = 0; i != Count; ++i) {
1191 switch (AF.getValueSize()) {
1192 default:
1193 assert(0 && "Invalid size!");
1194 case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
1195 case 2: MOW.Write16(uint16_t(AF.getValue())); break;
1196 case 4: MOW.Write32(uint32_t(AF.getValue())); break;
1197 case 8: MOW.Write64(uint64_t(AF.getValue())); break;
1198 }
1199 }
1200 break;
1201 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001202
Daniel Dunbar3a30b822010-02-13 09:28:15 +00001203 case MCFragment::FT_Data: {
1204 MCDataFragment &DF = cast<MCDataFragment>(F);
1205
1206 // Apply the fixups.
1207 //
1208 // FIXME: Move elsewhere.
1209 for (MCDataFragment::const_fixup_iterator it = DF.fixup_begin(),
1210 ie = DF.fixup_end(); it != ie; ++it)
1211 MOW.ApplyFixup(*it, DF);
1212
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001213 OS << cast<MCDataFragment>(F).getContents().str();
1214 break;
Daniel Dunbar3a30b822010-02-13 09:28:15 +00001215 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001216
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001217 case MCFragment::FT_Fill: {
1218 MCFillFragment &FF = cast<MCFillFragment>(F);
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001219 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
1220 switch (FF.getValueSize()) {
1221 default:
1222 assert(0 && "Invalid size!");
Daniel Dunbara4766d72010-02-13 09:28:32 +00001223 case 1: MOW.Write8 (uint8_t (FF.getValue())); break;
1224 case 2: MOW.Write16(uint16_t(FF.getValue())); break;
1225 case 4: MOW.Write32(uint32_t(FF.getValue())); break;
1226 case 8: MOW.Write64(uint64_t(FF.getValue())); break;
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001227 }
1228 }
1229 break;
1230 }
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001231
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001232 case MCFragment::FT_Org: {
1233 MCOrgFragment &OF = cast<MCOrgFragment>(F);
1234
1235 for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
1236 MOW.Write8(uint8_t(OF.getValue()));
1237
1238 break;
1239 }
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001240
1241 case MCFragment::FT_ZeroFill: {
1242 assert(0 && "Invalid zero fill fragment in concrete section!");
1243 break;
1244 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001245 }
1246
1247 assert(OS.tell() - Start == F.getFileSize());
1248}
1249
1250/// WriteFileData - Write the \arg SD data to the output file.
1251static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
1252 MachObjectWriter &MOW) {
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001253 // Ignore virtual sections.
1254 if (isVirtualSection(SD.getSection())) {
1255 assert(SD.getFileSize() == 0);
1256 return;
1257 }
1258
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001259 uint64_t Start = OS.tell();
1260 (void) Start;
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001261
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001262 for (MCSectionData::const_iterator it = SD.begin(),
1263 ie = SD.end(); it != ie; ++it)
1264 WriteFileData(OS, *it, MOW);
1265
Daniel Dunbar6742e342009-08-26 04:13:32 +00001266 // Add section padding.
1267 assert(SD.getFileSize() >= SD.getSize() && "Invalid section sizes!");
1268 MOW.WriteZeros(SD.getFileSize() - SD.getSize());
1269
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001270 assert(OS.tell() - Start == SD.getFileSize());
1271}
1272
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +00001273void MCAssembler::Finish() {
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001274 DEBUG_WITH_TYPE("mc-dump", {
1275 llvm::errs() << "assembler backend - pre-layout\n--\n";
1276 dump(); });
1277
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001278 // Layout the concrete sections and fragments.
Daniel Dunbar5e835962009-08-26 02:48:04 +00001279 uint64_t Address = 0;
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001280 MCSectionData *Prev = 0;
1281 for (iterator it = begin(), ie = end(); it != ie; ++it) {
Daniel Dunbar6742e342009-08-26 04:13:32 +00001282 MCSectionData &SD = *it;
1283
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001284 // Skip virtual sections.
1285 if (isVirtualSection(SD.getSection()))
1286 continue;
1287
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001288 // Align this section if necessary by adding padding bytes to the previous
1289 // section.
1290 if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment())) {
1291 assert(Prev && "Missing prev section!");
1292 Prev->setFileSize(Prev->getFileSize() + Pad);
1293 Address += Pad;
1294 }
Daniel Dunbar6742e342009-08-26 04:13:32 +00001295
1296 // Layout the section fragments and its size.
1297 SD.setAddress(Address);
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001298 LayoutSection(SD);
Daniel Dunbar6742e342009-08-26 04:13:32 +00001299 Address += SD.getFileSize();
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001300
1301 Prev = &SD;
Daniel Dunbar5e835962009-08-26 02:48:04 +00001302 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001303
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001304 // Layout the virtual sections.
1305 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1306 MCSectionData &SD = *it;
1307
1308 if (!isVirtualSection(SD.getSection()))
1309 continue;
1310
Daniel Dunbarb2b4acd2010-03-08 22:03:42 +00001311 // Align this section if necessary by adding padding bytes to the previous
1312 // section.
Daniel Dunbarf8b8ad72010-03-09 01:12:20 +00001313 if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment()))
Daniel Dunbarb2b4acd2010-03-08 22:03:42 +00001314 Address += Pad;
Daniel Dunbarb2b4acd2010-03-08 22:03:42 +00001315
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001316 SD.setAddress(Address);
1317 LayoutSection(SD);
1318 Address += SD.getSize();
Daniel Dunbarb2b4acd2010-03-08 22:03:42 +00001319
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001320 }
1321
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001322 DEBUG_WITH_TYPE("mc-dump", {
1323 llvm::errs() << "assembler backend - post-layout\n--\n";
1324 dump(); });
1325
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +00001326 // Write the object file.
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +00001327 MachObjectWriter MOW(OS);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +00001328 MOW.WriteObject(*this);
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001329
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +00001330 OS.flush();
1331}
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001332
1333
1334// Debugging methods
1335
1336namespace llvm {
1337
1338raw_ostream &operator<<(raw_ostream &OS, const MCAsmFixup &AF) {
Daniel Dunbar2be2fd02010-02-13 09:28:54 +00001339 OS << "<MCAsmFixup" << " Offset:" << AF.Offset << " Value:" << *AF.Value
1340 << " Kind:" << AF.Kind << ">";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001341 return OS;
1342}
1343
1344}
1345
1346void MCFragment::dump() {
1347 raw_ostream &OS = llvm::errs();
1348
1349 OS << "<MCFragment " << (void*) this << " Offset:" << Offset
1350 << " FileSize:" << FileSize;
1351
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001352 OS << ">";
1353}
1354
1355void MCAlignFragment::dump() {
1356 raw_ostream &OS = llvm::errs();
1357
1358 OS << "<MCAlignFragment ";
1359 this->MCFragment::dump();
1360 OS << "\n ";
1361 OS << " Alignment:" << getAlignment()
1362 << " Value:" << getValue() << " ValueSize:" << getValueSize()
1363 << " MaxBytesToEmit:" << getMaxBytesToEmit() << ">";
1364}
1365
1366void MCDataFragment::dump() {
1367 raw_ostream &OS = llvm::errs();
1368
1369 OS << "<MCDataFragment ";
1370 this->MCFragment::dump();
1371 OS << "\n ";
1372 OS << " Contents:[";
1373 for (unsigned i = 0, e = getContents().size(); i != e; ++i) {
1374 if (i) OS << ",";
1375 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1376 }
Daniel Dunbar2be2fd02010-02-13 09:28:54 +00001377 OS << "] (" << getContents().size() << " bytes)";
Daniel Dunbar0bcf0742010-02-13 09:28:43 +00001378
1379 if (!getFixups().empty()) {
1380 OS << ",\n ";
1381 OS << " Fixups:[";
1382 for (fixup_iterator it = fixup_begin(), ie = fixup_end(); it != ie; ++it) {
Daniel Dunbar45aefff2010-03-09 01:12:23 +00001383 if (it != fixup_begin()) OS << ",\n ";
Daniel Dunbar0bcf0742010-02-13 09:28:43 +00001384 OS << *it;
1385 }
1386 OS << "]";
1387 }
1388
1389 OS << ">";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001390}
1391
1392void MCFillFragment::dump() {
1393 raw_ostream &OS = llvm::errs();
1394
1395 OS << "<MCFillFragment ";
1396 this->MCFragment::dump();
1397 OS << "\n ";
1398 OS << " Value:" << getValue() << " ValueSize:" << getValueSize()
1399 << " Count:" << getCount() << ">";
1400}
1401
1402void MCOrgFragment::dump() {
1403 raw_ostream &OS = llvm::errs();
1404
1405 OS << "<MCOrgFragment ";
1406 this->MCFragment::dump();
1407 OS << "\n ";
1408 OS << " Offset:" << getOffset() << " Value:" << getValue() << ">";
1409}
1410
1411void MCZeroFillFragment::dump() {
1412 raw_ostream &OS = llvm::errs();
1413
1414 OS << "<MCZeroFillFragment ";
1415 this->MCFragment::dump();
1416 OS << "\n ";
1417 OS << " Size:" << getSize() << " Alignment:" << getAlignment() << ">";
1418}
1419
1420void MCSectionData::dump() {
1421 raw_ostream &OS = llvm::errs();
1422
1423 OS << "<MCSectionData";
1424 OS << " Alignment:" << getAlignment() << " Address:" << Address
1425 << " Size:" << Size << " FileSize:" << FileSize
Daniel Dunbar45aefff2010-03-09 01:12:23 +00001426 << " Fragments:[\n ";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001427 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1428 if (it != begin()) OS << ",\n ";
1429 it->dump();
1430 }
1431 OS << "]>";
1432}
1433
1434void MCSymbolData::dump() {
1435 raw_ostream &OS = llvm::errs();
1436
1437 OS << "<MCSymbolData Symbol:" << getSymbol()
1438 << " Fragment:" << getFragment() << " Offset:" << getOffset()
1439 << " Flags:" << getFlags() << " Index:" << getIndex();
1440 if (isCommon())
1441 OS << " (common, size:" << getCommonSize()
1442 << " align: " << getCommonAlignment() << ")";
1443 if (isExternal())
1444 OS << " (external)";
1445 if (isPrivateExtern())
1446 OS << " (private extern)";
1447 OS << ">";
1448}
1449
1450void MCAssembler::dump() {
1451 raw_ostream &OS = llvm::errs();
1452
1453 OS << "<MCAssembler\n";
Daniel Dunbar45aefff2010-03-09 01:12:23 +00001454 OS << " Sections:[\n ";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001455 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1456 if (it != begin()) OS << ",\n ";
1457 it->dump();
1458 }
1459 OS << "],\n";
1460 OS << " Symbols:[";
1461
1462 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
Daniel Dunbar45aefff2010-03-09 01:12:23 +00001463 if (it != symbol_begin()) OS << ",\n ";
Daniel Dunbarb7c3a4b2010-02-13 09:28:03 +00001464 it->dump();
1465 }
1466 OS << "]>\n";
1467}