blob: 64e11010b3c508246c6ab58d732f427804285d41 [file] [log] [blame]
Nate Begemaneb883af2006-08-23 21:08:52 +00001//===-- MachOWriter.cpp - Target-independent Mach-O Writer code -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Nate Begeman and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the target-independent Mach-O writer. This file writes
11// out the Mach-O file in the following order:
12//
13// #1 FatHeader (universal-only)
14// #2 FatArch (universal-only, 1 per universal arch)
15// Per arch:
16// #3 Header
17// #4 Load Commands
18// #5 Sections
19// #6 Relocations
20// #7 Symbols
21// #8 Strings
22//
23//===----------------------------------------------------------------------===//
24
Nate Begemanbfaaaa62006-12-11 02:20:45 +000025#include "llvm/Constants.h"
26#include "llvm/DerivedTypes.h"
Nate Begemaneb883af2006-08-23 21:08:52 +000027#include "llvm/Module.h"
28#include "llvm/CodeGen/MachineCodeEmitter.h"
29#include "llvm/CodeGen/MachineConstantPool.h"
Nate Begeman019f8512006-09-10 23:03:44 +000030#include "llvm/CodeGen/MachineJumpTableInfo.h"
Nate Begemaneb883af2006-08-23 21:08:52 +000031#include "llvm/CodeGen/MachOWriter.h"
Nate Begeman94be2482006-09-08 22:42:09 +000032#include "llvm/ExecutionEngine/ExecutionEngine.h"
Nate Begemanbfaaaa62006-12-11 02:20:45 +000033#include "llvm/Target/TargetAsmInfo.h"
Nate Begemaneb883af2006-08-23 21:08:52 +000034#include "llvm/Target/TargetJITInfo.h"
Nate Begemaneb883af2006-08-23 21:08:52 +000035#include "llvm/Support/Mangler.h"
Nate Begemanf8f2c5a2006-08-25 06:36:58 +000036#include "llvm/Support/MathExtras.h"
Bill Wendling203d3e42007-01-17 22:22:31 +000037#include "llvm/Support/OutputBuffer.h"
Nate Begemanbfaaaa62006-12-11 02:20:45 +000038#include "llvm/Support/Streams.h"
Nate Begemand2030e62006-08-26 15:46:34 +000039#include <algorithm>
Bill Wendlinge9116152007-01-17 09:06:13 +000040
Nate Begemaneb883af2006-08-23 21:08:52 +000041using namespace llvm;
42
43//===----------------------------------------------------------------------===//
44// MachOCodeEmitter Implementation
45//===----------------------------------------------------------------------===//
46
47namespace llvm {
48 /// MachOCodeEmitter - This class is used by the MachOWriter to emit the code
49 /// for functions to the Mach-O file.
50 class MachOCodeEmitter : public MachineCodeEmitter {
51 MachOWriter &MOW;
Nate Begemaneb883af2006-08-23 21:08:52 +000052
Bill Wendling203d3e42007-01-17 22:22:31 +000053 /// Target machine description.
54 TargetMachine &TM;
55
Bill Wendlingc904a5b2007-01-18 01:23:11 +000056 /// is64Bit/isLittleEndian - This information is inferred from the target
57 /// machine directly, indicating what header values and flags to set.
58 bool is64Bit, isLittleEndian;
59
Nate Begemaneb883af2006-08-23 21:08:52 +000060 /// Relocations - These are the relocations that the function needs, as
61 /// emitted.
62 std::vector<MachineRelocation> Relocations;
Nate Begeman019f8512006-09-10 23:03:44 +000063
64 /// CPLocations - This is a map of constant pool indices to offsets from the
65 /// start of the section for that constant pool index.
66 std::vector<intptr_t> CPLocations;
67
Nate Begemanbfaaaa62006-12-11 02:20:45 +000068 /// CPSections - This is a map of constant pool indices to the MachOSection
69 /// containing the constant pool entry for that index.
70 std::vector<unsigned> CPSections;
71
Nate Begeman019f8512006-09-10 23:03:44 +000072 /// JTLocations - This is a map of jump table indices to offsets from the
73 /// start of the section for that jump table index.
74 std::vector<intptr_t> JTLocations;
Nate Begemaneb883af2006-08-23 21:08:52 +000075
76 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
77 /// It is filled in by the StartMachineBasicBlock callback and queried by
78 /// the getMachineBasicBlockAddress callback.
79 std::vector<intptr_t> MBBLocations;
80
81 public:
Bill Wendlingc904a5b2007-01-18 01:23:11 +000082 MachOCodeEmitter(MachOWriter &mow) : MOW(mow), TM(MOW.TM) {
83 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
84 isLittleEndian = TM.getTargetData()->isLittleEndian();
85 }
Nate Begemaneb883af2006-08-23 21:08:52 +000086
Nate Begemanbfaaaa62006-12-11 02:20:45 +000087 virtual void startFunction(MachineFunction &F);
88 virtual bool finishFunction(MachineFunction &F);
Nate Begemaneb883af2006-08-23 21:08:52 +000089
Nate Begemanbfaaaa62006-12-11 02:20:45 +000090 virtual void addRelocation(const MachineRelocation &MR) {
Nate Begemaneb883af2006-08-23 21:08:52 +000091 Relocations.push_back(MR);
92 }
93
Nate Begeman019f8512006-09-10 23:03:44 +000094 void emitConstantPool(MachineConstantPool *MCP);
95 void emitJumpTables(MachineJumpTableInfo *MJTI);
96
Nate Begemaneb883af2006-08-23 21:08:52 +000097 virtual intptr_t getConstantPoolEntryAddress(unsigned Index) const {
Nate Begemanbfaaaa62006-12-11 02:20:45 +000098 assert(CPLocations.size() > Index && "CP not emitted!");
99 return CPLocations[Index];
Nate Begemaneb883af2006-08-23 21:08:52 +0000100 }
101 virtual intptr_t getJumpTableEntryAddress(unsigned Index) const {
Nate Begeman019f8512006-09-10 23:03:44 +0000102 assert(JTLocations.size() > Index && "JT not emitted!");
103 return JTLocations[Index];
104 }
105
106 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
107 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
108 MBBLocations.resize((MBB->getNumber()+1)*2);
109 MBBLocations[MBB->getNumber()] = getCurrentPCOffset();
Nate Begemaneb883af2006-08-23 21:08:52 +0000110 }
111
112 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
113 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
114 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
115 return MBBLocations[MBB->getNumber()];
116 }
117
118 /// JIT SPECIFIC FUNCTIONS - DO NOT IMPLEMENT THESE HERE!
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000119 virtual void startFunctionStub(unsigned StubSize, unsigned Alignment = 1) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000120 assert(0 && "JIT specific function called!");
121 abort();
122 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000123 virtual void *finishFunctionStub(const Function *F) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000124 assert(0 && "JIT specific function called!");
125 abort();
126 return 0;
127 }
128 };
129}
130
131/// startFunction - This callback is invoked when a new machine function is
132/// about to be emitted.
133void MachOCodeEmitter::startFunction(MachineFunction &F) {
134 // Align the output buffer to the appropriate alignment, power of 2.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000135 // FIXME: MachineFunction or TargetData should probably carry an alignment
136 // field for functions that we can query here instead of hard coding 4 in both
137 // the object writer and asm printer.
Nate Begemaneb883af2006-08-23 21:08:52 +0000138 unsigned Align = 4;
139
140 // Get the Mach-O Section that this function belongs in.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000141 MachOWriter::MachOSection *MOS = MOW.getTextSection();
Nate Begemaneb883af2006-08-23 21:08:52 +0000142
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000143 // FIXME: better memory management
Nate Begemaneb883af2006-08-23 21:08:52 +0000144 MOS->SectionData.reserve(4096);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000145 BufferBegin = &MOS->SectionData[0];
Nate Begemaneb883af2006-08-23 21:08:52 +0000146 BufferEnd = BufferBegin + MOS->SectionData.capacity();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000147
148 // FIXME: Using MOS->size directly here instead of calculating it from the
149 // output buffer size (impossible because the code emitter deals only in raw
150 // bytes) forces us to manually synchronize size and write padding zero bytes
151 // to the output buffer for all non-text sections. For text sections, we do
152 // not synchonize the output buffer, and we just blow up if anyone tries to
153 // write non-code to it. An assert should probably be added to
154 // AddSymbolToSection to prevent calling it on the text section.
Nate Begemaneb883af2006-08-23 21:08:52 +0000155 CurBufferPtr = BufferBegin + MOS->size;
156
157 // Upgrade the section alignment if required.
158 if (MOS->align < Align) MOS->align = Align;
159
Nate Begeman019f8512006-09-10 23:03:44 +0000160 // Clear per-function data structures.
161 CPLocations.clear();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000162 CPSections.clear();
Nate Begeman019f8512006-09-10 23:03:44 +0000163 JTLocations.clear();
Nate Begemaneb883af2006-08-23 21:08:52 +0000164 MBBLocations.clear();
165}
166
167/// finishFunction - This callback is invoked after the function is completely
168/// finished.
169bool MachOCodeEmitter::finishFunction(MachineFunction &F) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000170 // Get the Mach-O Section that this function belongs in.
171 MachOWriter::MachOSection *MOS = MOW.getTextSection();
172
Nate Begemaneb883af2006-08-23 21:08:52 +0000173 MOS->size += CurBufferPtr - BufferBegin;
174
175 // Get a symbol for the function to add to the symbol table
Nate Begemand2030e62006-08-26 15:46:34 +0000176 const GlobalValue *FuncV = F.getFunction();
Bill Wendling203d3e42007-01-17 22:22:31 +0000177 MachOSym FnSym(FuncV, MOW.Mang->getValueName(FuncV), MOS->Index, TM);
Nate Begeman94be2482006-09-08 22:42:09 +0000178
Nate Begeman019f8512006-09-10 23:03:44 +0000179 // Emit constant pool to appropriate section(s)
180 emitConstantPool(F.getConstantPool());
181
182 // Emit jump tables to appropriate section
183 emitJumpTables(F.getJumpTableInfo());
Nate Begemaneb883af2006-08-23 21:08:52 +0000184
Nate Begeman019f8512006-09-10 23:03:44 +0000185 // If we have emitted any relocations to function-specific objects such as
186 // basic blocks, constant pools entries, or jump tables, record their
187 // addresses now so that we can rewrite them with the correct addresses
188 // later.
Nate Begemaneb883af2006-08-23 21:08:52 +0000189 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
190 MachineRelocation &MR = Relocations[i];
Nate Begeman019f8512006-09-10 23:03:44 +0000191 intptr_t Addr;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000192
Nate Begemaneb883af2006-08-23 21:08:52 +0000193 if (MR.isBasicBlock()) {
Nate Begeman019f8512006-09-10 23:03:44 +0000194 Addr = getMachineBasicBlockAddress(MR.getBasicBlock());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000195 MR.setConstantVal(MOS->Index);
196 MR.setResultPointer((void*)Addr);
197 } else if (MR.isJumpTableIndex()) {
198 Addr = getJumpTableEntryAddress(MR.getJumpTableIndex());
199 MR.setConstantVal(MOW.getJumpTableSection()->Index);
200 MR.setResultPointer((void*)Addr);
Nate Begeman019f8512006-09-10 23:03:44 +0000201 } else if (MR.isConstantPoolIndex()) {
202 Addr = getConstantPoolEntryAddress(MR.getConstantPoolIndex());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000203 MR.setConstantVal(CPSections[MR.getConstantPoolIndex()]);
204 MR.setResultPointer((void*)Addr);
205 } else if (!MR.isGlobalValue()) {
206 assert(0 && "Unhandled relocation type");
Nate Begemaneb883af2006-08-23 21:08:52 +0000207 }
Nate Begeman019f8512006-09-10 23:03:44 +0000208 MOS->Relocations.push_back(MR);
Nate Begemaneb883af2006-08-23 21:08:52 +0000209 }
210 Relocations.clear();
211
212 // Finally, add it to the symtab.
213 MOW.SymbolTable.push_back(FnSym);
214 return false;
215}
216
Nate Begeman019f8512006-09-10 23:03:44 +0000217/// emitConstantPool - For each constant pool entry, figure out which section
218/// the constant should live in, allocate space for it, and emit it to the
219/// Section data buffer.
220void MachOCodeEmitter::emitConstantPool(MachineConstantPool *MCP) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000221 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
222 if (CP.empty()) return;
223
224 // FIXME: handle PIC codegen
Bill Wendling203d3e42007-01-17 22:22:31 +0000225 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000226 assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
227
228 // Although there is no strict necessity that I am aware of, we will do what
229 // gcc for OS X does and put each constant pool entry in a section of constant
230 // objects of a certain size. That means that float constants go in the
231 // literal4 section, and double objects go in literal8, etc.
232 //
233 // FIXME: revisit this decision if we ever do the "stick everything into one
234 // "giant object for PIC" optimization.
235 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
236 const Type *Ty = CP[i].getType();
Bill Wendling203d3e42007-01-17 22:22:31 +0000237 unsigned Size = TM.getTargetData()->getTypeSize(Ty);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000238
239 MachOWriter::MachOSection *Sec = MOW.getConstSection(Ty);
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000240 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000241
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000242 CPLocations.push_back(Sec->SectionData.size());
243 CPSections.push_back(Sec->Index);
244
245 // FIXME: remove when we have unified size + output buffer
246 Sec->size += Size;
247
248 // Allocate space in the section for the global.
249 // FIXME: need alignment?
250 // FIXME: share between here and AddSymbolToSection?
251 for (unsigned j = 0; j < Size; ++j)
Bill Wendling203d3e42007-01-17 22:22:31 +0000252 SecDataOut.outbyte(0);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000253
254 MOW.InitMem(CP[i].Val.ConstVal, &Sec->SectionData[0], CPLocations[i],
Bill Wendling203d3e42007-01-17 22:22:31 +0000255 TM.getTargetData(), Sec->Relocations);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000256 }
Nate Begeman019f8512006-09-10 23:03:44 +0000257}
258
259/// emitJumpTables - Emit all the jump tables for a given jump table info
260/// record to the appropriate section.
261void MachOCodeEmitter::emitJumpTables(MachineJumpTableInfo *MJTI) {
262 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
263 if (JT.empty()) return;
264
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000265 // FIXME: handle PIC codegen
Bill Wendling203d3e42007-01-17 22:22:31 +0000266 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
Nate Begeman019f8512006-09-10 23:03:44 +0000267 assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
268
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000269 MachOWriter::MachOSection *Sec = MOW.getJumpTableSection();
270 unsigned TextSecIndex = MOW.getTextSection()->Index;
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000271 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
Nate Begeman019f8512006-09-10 23:03:44 +0000272
273 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
274 // For each jump table, record its offset from the start of the section,
275 // reserve space for the relocations to the MBBs, and add the relocations.
276 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000277 JTLocations.push_back(Sec->SectionData.size());
Nate Begeman019f8512006-09-10 23:03:44 +0000278 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000279 MachineRelocation MR(MOW.GetJTRelocation(Sec->SectionData.size(),
Nate Begeman019f8512006-09-10 23:03:44 +0000280 MBBs[mi]));
281 MR.setResultPointer((void *)JTLocations[i]);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000282 MR.setConstantVal(TextSecIndex);
283 Sec->Relocations.push_back(MR);
Bill Wendling203d3e42007-01-17 22:22:31 +0000284 SecDataOut.outaddr(0);
Nate Begeman019f8512006-09-10 23:03:44 +0000285 }
286 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000287 // FIXME: remove when we have unified size + output buffer
288 Sec->size = Sec->SectionData.size();
Nate Begeman019f8512006-09-10 23:03:44 +0000289}
290
Nate Begemaneb883af2006-08-23 21:08:52 +0000291//===----------------------------------------------------------------------===//
292// MachOWriter Implementation
293//===----------------------------------------------------------------------===//
294
295MachOWriter::MachOWriter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000296 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
297 isLittleEndian = TM.getTargetData()->isLittleEndian();
298
299 // Create the machine code emitter object for this target.
Bill Wendlinge9116152007-01-17 09:06:13 +0000300 MCE = new MachOCodeEmitter(*this);
Nate Begemaneb883af2006-08-23 21:08:52 +0000301}
302
303MachOWriter::~MachOWriter() {
304 delete MCE;
305}
306
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000307void MachOWriter::AddSymbolToSection(MachOSection *Sec, GlobalVariable *GV) {
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000308 const Type *Ty = GV->getType()->getElementType();
309 unsigned Size = TM.getTargetData()->getTypeSize(Ty);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000310 unsigned Align = GV->getAlignment();
311 if (Align == 0)
312 Align = TM.getTargetData()->getTypeAlignment(Ty);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000313
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000314 MachOSym Sym(GV, Mang->getValueName(GV), Sec->Index, TM);
315
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000316 // Reserve space in the .bss section for this symbol while maintaining the
317 // desired section alignment, which must be at least as much as required by
318 // this symbol.
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000319 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000320
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000321 if (Align) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000322 uint64_t OrigSize = Sec->size;
323 Align = Log2_32(Align);
324 Sec->align = std::max(unsigned(Sec->align), Align);
325 Sec->size = (Sec->size + Align - 1) & ~(Align-1);
326
327 // Add alignment padding to buffer as well.
328 // FIXME: remove when we have unified size + output buffer
329 unsigned AlignedSize = Sec->size - OrigSize;
330 for (unsigned i = 0; i < AlignedSize; ++i)
Bill Wendling203d3e42007-01-17 22:22:31 +0000331 SecDataOut.outbyte(0);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000332 }
333 // Record the offset of the symbol, and then allocate space for it.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000334 // FIXME: remove when we have unified size + output buffer
335 Sym.n_value = Sec->size;
336 Sec->size += Size;
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000337 SymbolTable.push_back(Sym);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000338
339 // Now that we know what section the GlovalVariable is going to be emitted
340 // into, update our mappings.
341 // FIXME: We may also need to update this when outputting non-GlobalVariable
342 // GlobalValues such as functions.
343 GVSection[GV] = Sec;
344 GVOffset[GV] = Sec->SectionData.size();
345
346 // Allocate space in the section for the global.
347 for (unsigned i = 0; i < Size; ++i)
Bill Wendling203d3e42007-01-17 22:22:31 +0000348 SecDataOut.outbyte(0);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000349}
350
Nate Begemaneb883af2006-08-23 21:08:52 +0000351void MachOWriter::EmitGlobal(GlobalVariable *GV) {
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000352 const Type *Ty = GV->getType()->getElementType();
353 unsigned Size = TM.getTargetData()->getTypeSize(Ty);
354 bool NoInit = !GV->hasInitializer();
Nate Begemand2030e62006-08-26 15:46:34 +0000355
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000356 // If this global has a zero initializer, it is part of the .bss or common
357 // section.
358 if (NoInit || GV->getInitializer()->isNullValue()) {
359 // If this global is part of the common block, add it now. Variables are
360 // part of the common block if they are zero initialized and allowed to be
361 // merged with other symbols.
362 if (NoInit || GV->hasLinkOnceLinkage() || GV->hasWeakLinkage()) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000363 MachOSym ExtOrCommonSym(GV, Mang->getValueName(GV), MachOSym::NO_SECT,TM);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000364 // For undefined (N_UNDF) external (N_EXT) types, n_value is the size in
365 // bytes of the symbol.
366 ExtOrCommonSym.n_value = Size;
367 // If the symbol is external, we'll put it on a list of symbols whose
368 // addition to the symbol table is being pended until we find a reference
369 if (NoInit)
370 PendingSyms.push_back(ExtOrCommonSym);
371 else
372 SymbolTable.push_back(ExtOrCommonSym);
373 return;
374 }
375 // Otherwise, this symbol is part of the .bss section.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000376 MachOSection *BSS = getBSSSection();
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000377 AddSymbolToSection(BSS, GV);
378 return;
379 }
380
381 // Scalar read-only data goes in a literal section if the scalar is 4, 8, or
382 // 16 bytes, or a cstring. Other read only data goes into a regular const
383 // section. Read-write data goes in the data section.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000384 MachOSection *Sec = GV->isConstant() ? getConstSection(Ty) : getDataSection();
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000385 AddSymbolToSection(Sec, GV);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000386 InitMem(GV->getInitializer(), &Sec->SectionData[0], GVOffset[GV],
387 TM.getTargetData(), Sec->Relocations);
Nate Begemaneb883af2006-08-23 21:08:52 +0000388}
389
390
391bool MachOWriter::runOnMachineFunction(MachineFunction &MF) {
392 // Nothing to do here, this is all done through the MCE object.
393 return false;
394}
395
396bool MachOWriter::doInitialization(Module &M) {
397 // Set the magic value, now that we know the pointer size and endianness
398 Header.setMagic(isLittleEndian, is64Bit);
399
400 // Set the file type
401 // FIXME: this only works for object files, we do not support the creation
402 // of dynamic libraries or executables at this time.
403 Header.filetype = MachOHeader::MH_OBJECT;
404
405 Mang = new Mangler(M);
406 return false;
407}
408
409/// doFinalization - Now that the module has been completely processed, emit
410/// the Mach-O file to 'O'.
411bool MachOWriter::doFinalization(Module &M) {
Nate Begemand2030e62006-08-26 15:46:34 +0000412 // FIXME: we don't handle debug info yet, we should probably do that.
413
Nate Begemaneb883af2006-08-23 21:08:52 +0000414 // Okay, the.text section has been completed, build the .data, .bss, and
415 // "common" sections next.
416 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
417 I != E; ++I)
418 EmitGlobal(I);
419
420 // Emit the header and load commands.
421 EmitHeaderAndLoadCommands();
422
Nate Begeman019f8512006-09-10 23:03:44 +0000423 // Emit the various sections and their relocation info.
Nate Begemaneb883af2006-08-23 21:08:52 +0000424 EmitSections();
425
Nate Begemand2030e62006-08-26 15:46:34 +0000426 // Write the symbol table and the string table to the end of the file.
427 O.write((char*)&SymT[0], SymT.size());
428 O.write((char*)&StrT[0], StrT.size());
Nate Begemaneb883af2006-08-23 21:08:52 +0000429
430 // We are done with the abstract symbols.
431 SectionList.clear();
432 SymbolTable.clear();
433 DynamicSymbolTable.clear();
434
435 // Release the name mangler object.
436 delete Mang; Mang = 0;
437 return false;
438}
439
440void MachOWriter::EmitHeaderAndLoadCommands() {
441 // Step #0: Fill in the segment load command size, since we need it to figure
442 // out the rest of the header fields
443 MachOSegment SEG("", is64Bit);
444 SEG.nsects = SectionList.size();
445 SEG.cmdsize = SEG.cmdSize(is64Bit) +
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000446 SEG.nsects * SectionList[0]->cmdSize(is64Bit);
Nate Begemaneb883af2006-08-23 21:08:52 +0000447
448 // Step #1: calculate the number of load commands. We always have at least
449 // one, for the LC_SEGMENT load command, plus two for the normal
450 // and dynamic symbol tables, if there are any symbols.
451 Header.ncmds = SymbolTable.empty() ? 1 : 3;
452
453 // Step #2: calculate the size of the load commands
454 Header.sizeofcmds = SEG.cmdsize;
455 if (!SymbolTable.empty())
456 Header.sizeofcmds += SymTab.cmdsize + DySymTab.cmdsize;
457
458 // Step #3: write the header to the file
459 // Local alias to shortenify coming code.
460 DataBuffer &FH = Header.HeaderData;
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000461 OutputBuffer FHOut(FH, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000462
463 FHOut.outword(Header.magic);
464 FHOut.outword(Header.cputype);
465 FHOut.outword(Header.cpusubtype);
466 FHOut.outword(Header.filetype);
467 FHOut.outword(Header.ncmds);
468 FHOut.outword(Header.sizeofcmds);
469 FHOut.outword(Header.flags);
Nate Begemaneb883af2006-08-23 21:08:52 +0000470 if (is64Bit)
Bill Wendling203d3e42007-01-17 22:22:31 +0000471 FHOut.outword(Header.reserved);
Nate Begemaneb883af2006-08-23 21:08:52 +0000472
473 // Step #4: Finish filling in the segment load command and write it out
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000474 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begemaneb883af2006-08-23 21:08:52 +0000475 E = SectionList.end(); I != E; ++I)
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000476 SEG.filesize += (*I)->size;
477
Nate Begemaneb883af2006-08-23 21:08:52 +0000478 SEG.vmsize = SEG.filesize;
479 SEG.fileoff = Header.cmdSize(is64Bit) + Header.sizeofcmds;
480
Bill Wendling203d3e42007-01-17 22:22:31 +0000481 FHOut.outword(SEG.cmd);
482 FHOut.outword(SEG.cmdsize);
483 FHOut.outstring(SEG.segname, 16);
484 FHOut.outaddr(SEG.vmaddr);
485 FHOut.outaddr(SEG.vmsize);
486 FHOut.outaddr(SEG.fileoff);
487 FHOut.outaddr(SEG.filesize);
488 FHOut.outword(SEG.maxprot);
489 FHOut.outword(SEG.initprot);
490 FHOut.outword(SEG.nsects);
491 FHOut.outword(SEG.flags);
Nate Begemaneb883af2006-08-23 21:08:52 +0000492
Nate Begeman94be2482006-09-08 22:42:09 +0000493 // Step #5: Finish filling in the fields of the MachOSections
494 uint64_t currentAddr = 0;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000495 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begemaneb883af2006-08-23 21:08:52 +0000496 E = SectionList.end(); I != E; ++I) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000497 MachOSection *MOS = *I;
498 MOS->addr = currentAddr;
499 MOS->offset = currentAddr + SEG.fileoff;
Nate Begeman019f8512006-09-10 23:03:44 +0000500
Nate Begeman94be2482006-09-08 22:42:09 +0000501 // FIXME: do we need to do something with alignment here?
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000502 currentAddr += MOS->size;
Nate Begeman94be2482006-09-08 22:42:09 +0000503 }
504
505 // Step #6: Calculate the number of relocations for each section and write out
506 // the section commands for each section
507 currentAddr += SEG.fileoff;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000508 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman94be2482006-09-08 22:42:09 +0000509 E = SectionList.end(); I != E; ++I) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000510 MachOSection *MOS = *I;
511 // Convert the relocations to target-specific relocations, and fill in the
512 // relocation offset for this section.
513 CalculateRelocations(*MOS);
514 MOS->reloff = MOS->nreloc ? currentAddr : 0;
515 currentAddr += MOS->nreloc * 8;
Nate Begeman94be2482006-09-08 22:42:09 +0000516
517 // write the finalized section command to the output buffer
Bill Wendling203d3e42007-01-17 22:22:31 +0000518 FHOut.outstring(MOS->sectname, 16);
519 FHOut.outstring(MOS->segname, 16);
520 FHOut.outaddr(MOS->addr);
521 FHOut.outaddr(MOS->size);
522 FHOut.outword(MOS->offset);
523 FHOut.outword(MOS->align);
524 FHOut.outword(MOS->reloff);
525 FHOut.outword(MOS->nreloc);
526 FHOut.outword(MOS->flags);
527 FHOut.outword(MOS->reserved1);
528 FHOut.outword(MOS->reserved2);
Nate Begemaneb883af2006-08-23 21:08:52 +0000529 if (is64Bit)
Bill Wendling203d3e42007-01-17 22:22:31 +0000530 FHOut.outword(MOS->reserved3);
Nate Begemaneb883af2006-08-23 21:08:52 +0000531 }
532
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000533 // Step #7: Emit the symbol table to temporary buffers, so that we know the
534 // size of the string table when we write the next load command.
535 BufferSymbolAndStringTable();
536
537 // Step #8: Emit LC_SYMTAB/LC_DYSYMTAB load commands
Nate Begeman94be2482006-09-08 22:42:09 +0000538 SymTab.symoff = currentAddr;
Nate Begemaneb883af2006-08-23 21:08:52 +0000539 SymTab.nsyms = SymbolTable.size();
Nate Begemand2030e62006-08-26 15:46:34 +0000540 SymTab.stroff = SymTab.symoff + SymT.size();
541 SymTab.strsize = StrT.size();
Bill Wendling203d3e42007-01-17 22:22:31 +0000542 FHOut.outword(SymTab.cmd);
543 FHOut.outword(SymTab.cmdsize);
544 FHOut.outword(SymTab.symoff);
545 FHOut.outword(SymTab.nsyms);
546 FHOut.outword(SymTab.stroff);
547 FHOut.outword(SymTab.strsize);
Nate Begemaneb883af2006-08-23 21:08:52 +0000548
549 // FIXME: set DySymTab fields appropriately
Nate Begemand2030e62006-08-26 15:46:34 +0000550 // We should probably just update these in BufferSymbolAndStringTable since
551 // thats where we're partitioning up the different kinds of symbols.
Bill Wendling203d3e42007-01-17 22:22:31 +0000552 FHOut.outword(DySymTab.cmd);
553 FHOut.outword(DySymTab.cmdsize);
554 FHOut.outword(DySymTab.ilocalsym);
555 FHOut.outword(DySymTab.nlocalsym);
556 FHOut.outword(DySymTab.iextdefsym);
557 FHOut.outword(DySymTab.nextdefsym);
558 FHOut.outword(DySymTab.iundefsym);
559 FHOut.outword(DySymTab.nundefsym);
560 FHOut.outword(DySymTab.tocoff);
561 FHOut.outword(DySymTab.ntoc);
562 FHOut.outword(DySymTab.modtaboff);
563 FHOut.outword(DySymTab.nmodtab);
564 FHOut.outword(DySymTab.extrefsymoff);
565 FHOut.outword(DySymTab.nextrefsyms);
566 FHOut.outword(DySymTab.indirectsymoff);
567 FHOut.outword(DySymTab.nindirectsyms);
568 FHOut.outword(DySymTab.extreloff);
569 FHOut.outword(DySymTab.nextrel);
570 FHOut.outword(DySymTab.locreloff);
571 FHOut.outword(DySymTab.nlocrel);
Nate Begemaneb883af2006-08-23 21:08:52 +0000572
573 O.write((char*)&FH[0], FH.size());
574}
575
576/// EmitSections - Now that we have constructed the file header and load
577/// commands, emit the data for each section to the file.
578void MachOWriter::EmitSections() {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000579 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman019f8512006-09-10 23:03:44 +0000580 E = SectionList.end(); I != E; ++I)
581 // Emit the contents of each section
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000582 O.write((char*)&(*I)->SectionData[0], (*I)->size);
583 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman019f8512006-09-10 23:03:44 +0000584 E = SectionList.end(); I != E; ++I)
585 // Emit the relocation entry data for each section.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000586 O.write((char*)&(*I)->RelocBuffer[0], (*I)->RelocBuffer.size());
Nate Begemaneb883af2006-08-23 21:08:52 +0000587}
588
Nate Begemand2030e62006-08-26 15:46:34 +0000589/// PartitionByLocal - Simple boolean predicate that returns true if Sym is
590/// a local symbol rather than an external symbol.
591bool MachOWriter::PartitionByLocal(const MachOSym &Sym) {
Nate Begemand2030e62006-08-26 15:46:34 +0000592 return (Sym.n_type & (MachOSym::N_EXT | MachOSym::N_PEXT)) == 0;
Nate Begemaneb883af2006-08-23 21:08:52 +0000593}
594
Nate Begemand2030e62006-08-26 15:46:34 +0000595/// PartitionByDefined - Simple boolean predicate that returns true if Sym is
596/// defined in this module.
597bool MachOWriter::PartitionByDefined(const MachOSym &Sym) {
598 // FIXME: Do N_ABS or N_INDR count as defined?
599 return (Sym.n_type & MachOSym::N_SECT) == MachOSym::N_SECT;
600}
Nate Begemaneb883af2006-08-23 21:08:52 +0000601
Nate Begemand2030e62006-08-26 15:46:34 +0000602/// BufferSymbolAndStringTable - Sort the symbols we encountered and assign them
603/// each a string table index so that they appear in the correct order in the
604/// output file.
605void MachOWriter::BufferSymbolAndStringTable() {
606 // The order of the symbol table is:
607 // 1. local symbols
608 // 2. defined external symbols (sorted by name)
609 // 3. undefined external symbols (sorted by name)
610
611 // Sort the symbols by name, so that when we partition the symbols by scope
612 // of definition, we won't have to sort by name within each partition.
613 std::sort(SymbolTable.begin(), SymbolTable.end(), MachOSymCmp());
614
615 // Parition the symbol table entries so that all local symbols come before
616 // all symbols with external linkage. { 1 | 2 3 }
617 std::partition(SymbolTable.begin(), SymbolTable.end(), PartitionByLocal);
618
619 // Advance iterator to beginning of external symbols and partition so that
620 // all external symbols defined in this module come before all external
621 // symbols defined elsewhere. { 1 | 2 | 3 }
622 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
623 E = SymbolTable.end(); I != E; ++I) {
624 if (!PartitionByLocal(*I)) {
625 std::partition(I, E, PartitionByDefined);
626 break;
627 }
628 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000629
630 // Calculate the starting index for each of the local, extern defined, and
631 // undefined symbols, as well as the number of each to put in the LC_DYSYMTAB
632 // load command.
633 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
634 E = SymbolTable.end(); I != E; ++I) {
635 if (PartitionByLocal(*I)) {
636 ++DySymTab.nlocalsym;
637 ++DySymTab.iextdefsym;
638 } else if (PartitionByDefined(*I)) {
639 ++DySymTab.nextdefsym;
640 ++DySymTab.iundefsym;
641 } else {
642 ++DySymTab.nundefsym;
643 }
644 }
Nate Begemand2030e62006-08-26 15:46:34 +0000645
Nate Begemaneb883af2006-08-23 21:08:52 +0000646 // Write out a leading zero byte when emitting string table, for n_strx == 0
647 // which means an empty string.
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000648 OutputBuffer StrTOut(StrT, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000649 StrTOut.outbyte(0);
Nate Begemaneb883af2006-08-23 21:08:52 +0000650
Nate Begemand2030e62006-08-26 15:46:34 +0000651 // The order of the string table is:
652 // 1. strings for external symbols
653 // 2. strings for local symbols
654 // Since this is the opposite order from the symbol table, which we have just
655 // sorted, we can walk the symbol table backwards to output the string table.
656 for (std::vector<MachOSym>::reverse_iterator I = SymbolTable.rbegin(),
657 E = SymbolTable.rend(); I != E; ++I) {
658 if (I->GVName == "") {
659 I->n_strx = 0;
660 } else {
661 I->n_strx = StrT.size();
Bill Wendling203d3e42007-01-17 22:22:31 +0000662 StrTOut.outstring(I->GVName, I->GVName.length()+1);
Nate Begemand2030e62006-08-26 15:46:34 +0000663 }
Nate Begemaneb883af2006-08-23 21:08:52 +0000664 }
Nate Begemand2030e62006-08-26 15:46:34 +0000665
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000666 OutputBuffer SymTOut(SymT, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000667
Nate Begemand2030e62006-08-26 15:46:34 +0000668 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
669 E = SymbolTable.end(); I != E; ++I) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000670 // Add the section base address to the section offset in the n_value field
671 // to calculate the full address.
672 // FIXME: handle symbols where the n_value field is not the address
673 GlobalValue *GV = const_cast<GlobalValue*>(I->GV);
674 if (GV && GVSection[GV])
675 I->n_value += GVSection[GV]->addr;
676
Nate Begemand2030e62006-08-26 15:46:34 +0000677 // Emit nlist to buffer
Bill Wendling203d3e42007-01-17 22:22:31 +0000678 SymTOut.outword(I->n_strx);
679 SymTOut.outbyte(I->n_type);
680 SymTOut.outbyte(I->n_sect);
681 SymTOut.outhalf(I->n_desc);
682 SymTOut.outaddr(I->n_value);
Nate Begemand2030e62006-08-26 15:46:34 +0000683 }
Nate Begemaneb883af2006-08-23 21:08:52 +0000684}
Nate Begeman94be2482006-09-08 22:42:09 +0000685
Nate Begeman019f8512006-09-10 23:03:44 +0000686/// CalculateRelocations - For each MachineRelocation in the current section,
687/// calculate the index of the section containing the object to be relocated,
688/// and the offset into that section. From this information, create the
689/// appropriate target-specific MachORelocation type and add buffer it to be
690/// written out after we are finished writing out sections.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000691void MachOWriter::CalculateRelocations(MachOSection &MOS) {
Nate Begeman019f8512006-09-10 23:03:44 +0000692 for (unsigned i = 0, e = MOS.Relocations.size(); i != e; ++i) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000693 MachineRelocation &MR = MOS.Relocations[i];
694 unsigned TargetSection = MR.getConstantVal();
695
696 // Since we may not have seen the GlobalValue we were interested in yet at
697 // the time we emitted the relocation for it, fix it up now so that it
698 // points to the offset into the correct section.
699 if (MR.isGlobalValue()) {
700 GlobalValue *GV = MR.getGlobalValue();
701 MachOSection *MOSPtr = GVSection[GV];
702 intptr_t offset = GVOffset[GV];
703
704 assert(MOSPtr && "Trying to relocate unknown global!");
705
706 TargetSection = MOSPtr->Index;
707 MR.setResultPointer((void*)offset);
708 }
709
710 GetTargetRelocation(MR, MOS, *SectionList[TargetSection-1]);
Nate Begeman019f8512006-09-10 23:03:44 +0000711 }
Nate Begeman019f8512006-09-10 23:03:44 +0000712}
713
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000714// InitMem - Write the value of a Constant to the specified memory location,
715// converting it into bytes and relocations.
716void MachOWriter::InitMem(const Constant *C, void *Addr, intptr_t Offset,
717 const TargetData *TD,
718 std::vector<MachineRelocation> &MRs) {
719 typedef std::pair<const Constant*, intptr_t> CPair;
720 std::vector<CPair> WorkList;
721
722 WorkList.push_back(CPair(C,(intptr_t)Addr + Offset));
723
724 while (!WorkList.empty()) {
725 const Constant *PC = WorkList.back().first;
726 intptr_t PA = WorkList.back().second;
727 WorkList.pop_back();
728
729 if (isa<UndefValue>(PC)) {
730 continue;
731 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(PC)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000732 unsigned ElementSize = TD->getTypeSize(CP->getType()->getElementType());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000733 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
734 WorkList.push_back(CPair(CP->getOperand(i), PA+i*ElementSize));
735 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(PC)) {
736 //
737 // FIXME: Handle ConstantExpression. See EE::getConstantValue()
738 //
739 switch (CE->getOpcode()) {
740 case Instruction::GetElementPtr:
741 case Instruction::Add:
742 default:
743 cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
744 abort();
745 break;
746 }
747 } else if (PC->getType()->isFirstClassType()) {
748 unsigned char *ptr = (unsigned char *)PA;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000749 switch (PC->getType()->getTypeID()) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000750 case Type::IntegerTyID: {
751 unsigned NumBits = cast<IntegerType>(PC->getType())->getBitWidth();
752 uint64_t val = cast<ConstantInt>(PC)->getZExtValue();
753 if (NumBits <= 8)
754 ptr[0] = val;
755 else if (NumBits <= 16) {
756 if (TD->isBigEndian())
757 val = ByteSwap_16(val);
758 ptr[0] = val;
759 ptr[1] = val >> 8;
760 } else if (NumBits <= 32) {
761 if (TD->isBigEndian())
762 val = ByteSwap_32(val);
763 ptr[0] = val;
764 ptr[1] = val >> 8;
765 ptr[2] = val >> 16;
766 ptr[3] = val >> 24;
767 } else if (NumBits <= 64) {
768 if (TD->isBigEndian())
769 val = ByteSwap_64(val);
770 ptr[0] = val;
771 ptr[1] = val >> 8;
772 ptr[2] = val >> 16;
773 ptr[3] = val >> 24;
774 ptr[4] = val >> 32;
775 ptr[5] = val >> 40;
776 ptr[6] = val >> 48;
777 ptr[7] = val >> 56;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000778 } else {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000779 assert(0 && "Not implemented: bit widths > 64");
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000780 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000781 break;
782 }
783 case Type::FloatTyID: {
784 uint64_t val = FloatToBits(cast<ConstantFP>(PC)->getValue());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000785 if (TD->isBigEndian())
786 val = ByteSwap_32(val);
787 ptr[0] = val;
788 ptr[1] = val >> 8;
789 ptr[2] = val >> 16;
790 ptr[3] = val >> 24;
791 break;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000792 }
793 case Type::DoubleTyID: {
794 uint64_t val = DoubleToBits(cast<ConstantFP>(PC)->getValue());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000795 if (TD->isBigEndian())
796 val = ByteSwap_64(val);
797 ptr[0] = val;
798 ptr[1] = val >> 8;
799 ptr[2] = val >> 16;
800 ptr[3] = val >> 24;
801 ptr[4] = val >> 32;
802 ptr[5] = val >> 40;
803 ptr[6] = val >> 48;
804 ptr[7] = val >> 56;
805 break;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000806 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000807 case Type::PointerTyID:
808 if (isa<ConstantPointerNull>(C))
809 memset(ptr, 0, TD->getPointerSize());
810 else if (const GlobalValue* GV = dyn_cast<GlobalValue>(C))
811 // FIXME: what about function stubs?
812 MRs.push_back(MachineRelocation::getGV(PA-(intptr_t)Addr,
813 MachineRelocation::VANILLA,
814 const_cast<GlobalValue*>(GV)));
815 else
816 assert(0 && "Unknown constant pointer type!");
817 break;
818 default:
819 cerr << "ERROR: Constant unimp for type: " << *PC->getType() << "\n";
820 abort();
821 }
822 } else if (isa<ConstantAggregateZero>(PC)) {
823 memset((void*)PA, 0, (size_t)TD->getTypeSize(PC->getType()));
824 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(PC)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000825 unsigned ElementSize = TD->getTypeSize(CPA->getType()->getElementType());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000826 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
827 WorkList.push_back(CPair(CPA->getOperand(i), PA+i*ElementSize));
828 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(PC)) {
829 const StructLayout *SL =
830 TD->getStructLayout(cast<StructType>(CPS->getType()));
831 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
832 WorkList.push_back(CPair(CPS->getOperand(i), PA+SL->MemberOffsets[i]));
833 } else {
834 cerr << "Bad Type: " << *PC->getType() << "\n";
835 assert(0 && "Unknown constant type to initialize memory with!");
836 }
837 }
838}
839
840MachOSym::MachOSym(const GlobalValue *gv, std::string name, uint8_t sect,
841 TargetMachine &TM) :
842 GV(gv), n_strx(0), n_type(sect == NO_SECT ? N_UNDF : N_SECT), n_sect(sect),
843 n_desc(0), n_value(0) {
844
845 const TargetAsmInfo *TAI = TM.getTargetAsmInfo();
846
Nate Begeman94be2482006-09-08 22:42:09 +0000847 switch (GV->getLinkage()) {
848 default:
849 assert(0 && "Unexpected linkage type!");
850 break;
851 case GlobalValue::WeakLinkage:
852 case GlobalValue::LinkOnceLinkage:
853 assert(!isa<Function>(gv) && "Unexpected linkage type for Function!");
854 case GlobalValue::ExternalLinkage:
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000855 GVName = TAI->getGlobalPrefix() + name;
Nate Begeman94be2482006-09-08 22:42:09 +0000856 n_type |= N_EXT;
857 break;
858 case GlobalValue::InternalLinkage:
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000859 GVName = TAI->getPrivateGlobalPrefix() + name;
Nate Begeman94be2482006-09-08 22:42:09 +0000860 break;
861 }
862}