blob: 29c070b3712eea3781c933e3f1c7b80441f757c7 [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
Nate Begemaneb883af2006-08-23 21:08:52 +000056 /// Relocations - These are the relocations that the function needs, as
57 /// emitted.
58 std::vector<MachineRelocation> Relocations;
Nate Begeman019f8512006-09-10 23:03:44 +000059
60 /// CPLocations - This is a map of constant pool indices to offsets from the
61 /// start of the section for that constant pool index.
62 std::vector<intptr_t> CPLocations;
63
Nate Begemanbfaaaa62006-12-11 02:20:45 +000064 /// CPSections - This is a map of constant pool indices to the MachOSection
65 /// containing the constant pool entry for that index.
66 std::vector<unsigned> CPSections;
67
Nate Begeman019f8512006-09-10 23:03:44 +000068 /// JTLocations - This is a map of jump table indices to offsets from the
69 /// start of the section for that jump table index.
70 std::vector<intptr_t> JTLocations;
Nate Begemaneb883af2006-08-23 21:08:52 +000071
72 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
73 /// It is filled in by the StartMachineBasicBlock callback and queried by
74 /// the getMachineBasicBlockAddress callback.
75 std::vector<intptr_t> MBBLocations;
76
77 public:
Bill Wendling203d3e42007-01-17 22:22:31 +000078 MachOCodeEmitter(MachOWriter &mow) : MOW(mow), TM(MOW.TM) {}
Nate Begemaneb883af2006-08-23 21:08:52 +000079
Nate Begemanbfaaaa62006-12-11 02:20:45 +000080 virtual void startFunction(MachineFunction &F);
81 virtual bool finishFunction(MachineFunction &F);
Nate Begemaneb883af2006-08-23 21:08:52 +000082
Nate Begemanbfaaaa62006-12-11 02:20:45 +000083 virtual void addRelocation(const MachineRelocation &MR) {
Nate Begemaneb883af2006-08-23 21:08:52 +000084 Relocations.push_back(MR);
85 }
86
Nate Begeman019f8512006-09-10 23:03:44 +000087 void emitConstantPool(MachineConstantPool *MCP);
88 void emitJumpTables(MachineJumpTableInfo *MJTI);
89
Nate Begemaneb883af2006-08-23 21:08:52 +000090 virtual intptr_t getConstantPoolEntryAddress(unsigned Index) const {
Nate Begemanbfaaaa62006-12-11 02:20:45 +000091 assert(CPLocations.size() > Index && "CP not emitted!");
92 return CPLocations[Index];
Nate Begemaneb883af2006-08-23 21:08:52 +000093 }
94 virtual intptr_t getJumpTableEntryAddress(unsigned Index) const {
Nate Begeman019f8512006-09-10 23:03:44 +000095 assert(JTLocations.size() > Index && "JT not emitted!");
96 return JTLocations[Index];
97 }
98
99 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
100 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
101 MBBLocations.resize((MBB->getNumber()+1)*2);
102 MBBLocations[MBB->getNumber()] = getCurrentPCOffset();
Nate Begemaneb883af2006-08-23 21:08:52 +0000103 }
104
105 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
106 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
107 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
108 return MBBLocations[MBB->getNumber()];
109 }
110
111 /// JIT SPECIFIC FUNCTIONS - DO NOT IMPLEMENT THESE HERE!
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000112 virtual void startFunctionStub(unsigned StubSize, unsigned Alignment = 1) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000113 assert(0 && "JIT specific function called!");
114 abort();
115 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000116 virtual void *finishFunctionStub(const Function *F) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000117 assert(0 && "JIT specific function called!");
118 abort();
119 return 0;
120 }
121 };
122}
123
124/// startFunction - This callback is invoked when a new machine function is
125/// about to be emitted.
126void MachOCodeEmitter::startFunction(MachineFunction &F) {
127 // Align the output buffer to the appropriate alignment, power of 2.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000128 // FIXME: MachineFunction or TargetData should probably carry an alignment
129 // field for functions that we can query here instead of hard coding 4 in both
130 // the object writer and asm printer.
Nate Begemaneb883af2006-08-23 21:08:52 +0000131 unsigned Align = 4;
132
133 // Get the Mach-O Section that this function belongs in.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000134 MachOWriter::MachOSection *MOS = MOW.getTextSection();
Nate Begemaneb883af2006-08-23 21:08:52 +0000135
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000136 // FIXME: better memory management
Nate Begemaneb883af2006-08-23 21:08:52 +0000137 MOS->SectionData.reserve(4096);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000138 BufferBegin = &MOS->SectionData[0];
Nate Begemaneb883af2006-08-23 21:08:52 +0000139 BufferEnd = BufferBegin + MOS->SectionData.capacity();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000140
141 // FIXME: Using MOS->size directly here instead of calculating it from the
142 // output buffer size (impossible because the code emitter deals only in raw
143 // bytes) forces us to manually synchronize size and write padding zero bytes
144 // to the output buffer for all non-text sections. For text sections, we do
145 // not synchonize the output buffer, and we just blow up if anyone tries to
146 // write non-code to it. An assert should probably be added to
147 // AddSymbolToSection to prevent calling it on the text section.
Nate Begemaneb883af2006-08-23 21:08:52 +0000148 CurBufferPtr = BufferBegin + MOS->size;
149
150 // Upgrade the section alignment if required.
151 if (MOS->align < Align) MOS->align = Align;
152
Nate Begeman019f8512006-09-10 23:03:44 +0000153 // Clear per-function data structures.
154 CPLocations.clear();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000155 CPSections.clear();
Nate Begeman019f8512006-09-10 23:03:44 +0000156 JTLocations.clear();
Nate Begemaneb883af2006-08-23 21:08:52 +0000157 MBBLocations.clear();
158}
159
160/// finishFunction - This callback is invoked after the function is completely
161/// finished.
162bool MachOCodeEmitter::finishFunction(MachineFunction &F) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000163 // Get the Mach-O Section that this function belongs in.
164 MachOWriter::MachOSection *MOS = MOW.getTextSection();
165
Nate Begemaneb883af2006-08-23 21:08:52 +0000166 MOS->size += CurBufferPtr - BufferBegin;
167
168 // Get a symbol for the function to add to the symbol table
Nate Begemand2030e62006-08-26 15:46:34 +0000169 const GlobalValue *FuncV = F.getFunction();
Bill Wendling203d3e42007-01-17 22:22:31 +0000170 MachOSym FnSym(FuncV, MOW.Mang->getValueName(FuncV), MOS->Index, TM);
Nate Begeman94be2482006-09-08 22:42:09 +0000171
Nate Begeman019f8512006-09-10 23:03:44 +0000172 // Emit constant pool to appropriate section(s)
173 emitConstantPool(F.getConstantPool());
174
175 // Emit jump tables to appropriate section
176 emitJumpTables(F.getJumpTableInfo());
Nate Begemaneb883af2006-08-23 21:08:52 +0000177
Nate Begeman019f8512006-09-10 23:03:44 +0000178 // If we have emitted any relocations to function-specific objects such as
179 // basic blocks, constant pools entries, or jump tables, record their
180 // addresses now so that we can rewrite them with the correct addresses
181 // later.
Nate Begemaneb883af2006-08-23 21:08:52 +0000182 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
183 MachineRelocation &MR = Relocations[i];
Nate Begeman019f8512006-09-10 23:03:44 +0000184 intptr_t Addr;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000185
Nate Begemaneb883af2006-08-23 21:08:52 +0000186 if (MR.isBasicBlock()) {
Nate Begeman019f8512006-09-10 23:03:44 +0000187 Addr = getMachineBasicBlockAddress(MR.getBasicBlock());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000188 MR.setConstantVal(MOS->Index);
189 MR.setResultPointer((void*)Addr);
190 } else if (MR.isJumpTableIndex()) {
191 Addr = getJumpTableEntryAddress(MR.getJumpTableIndex());
192 MR.setConstantVal(MOW.getJumpTableSection()->Index);
193 MR.setResultPointer((void*)Addr);
Nate Begeman019f8512006-09-10 23:03:44 +0000194 } else if (MR.isConstantPoolIndex()) {
195 Addr = getConstantPoolEntryAddress(MR.getConstantPoolIndex());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000196 MR.setConstantVal(CPSections[MR.getConstantPoolIndex()]);
197 MR.setResultPointer((void*)Addr);
198 } else if (!MR.isGlobalValue()) {
199 assert(0 && "Unhandled relocation type");
Nate Begemaneb883af2006-08-23 21:08:52 +0000200 }
Nate Begeman019f8512006-09-10 23:03:44 +0000201 MOS->Relocations.push_back(MR);
Nate Begemaneb883af2006-08-23 21:08:52 +0000202 }
203 Relocations.clear();
204
205 // Finally, add it to the symtab.
206 MOW.SymbolTable.push_back(FnSym);
207 return false;
208}
209
Nate Begeman019f8512006-09-10 23:03:44 +0000210/// emitConstantPool - For each constant pool entry, figure out which section
211/// the constant should live in, allocate space for it, and emit it to the
212/// Section data buffer.
213void MachOCodeEmitter::emitConstantPool(MachineConstantPool *MCP) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000214 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
215 if (CP.empty()) return;
216
217 // FIXME: handle PIC codegen
Bill Wendling203d3e42007-01-17 22:22:31 +0000218 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000219 assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
220
221 // Although there is no strict necessity that I am aware of, we will do what
222 // gcc for OS X does and put each constant pool entry in a section of constant
223 // objects of a certain size. That means that float constants go in the
224 // literal4 section, and double objects go in literal8, etc.
225 //
226 // FIXME: revisit this decision if we ever do the "stick everything into one
227 // "giant object for PIC" optimization.
228 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
229 const Type *Ty = CP[i].getType();
Bill Wendling203d3e42007-01-17 22:22:31 +0000230 unsigned Size = TM.getTargetData()->getTypeSize(Ty);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000231
232 MachOWriter::MachOSection *Sec = MOW.getConstSection(Ty);
Bill Wendling203d3e42007-01-17 22:22:31 +0000233 OutputBuffer SecDataOut(TM, Sec->SectionData);
234
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000235 CPLocations.push_back(Sec->SectionData.size());
236 CPSections.push_back(Sec->Index);
237
238 // FIXME: remove when we have unified size + output buffer
239 Sec->size += Size;
240
241 // Allocate space in the section for the global.
242 // FIXME: need alignment?
243 // FIXME: share between here and AddSymbolToSection?
244 for (unsigned j = 0; j < Size; ++j)
Bill Wendling203d3e42007-01-17 22:22:31 +0000245 SecDataOut.outbyte(0);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000246
247 MOW.InitMem(CP[i].Val.ConstVal, &Sec->SectionData[0], CPLocations[i],
Bill Wendling203d3e42007-01-17 22:22:31 +0000248 TM.getTargetData(), Sec->Relocations);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000249 }
Nate Begeman019f8512006-09-10 23:03:44 +0000250}
251
252/// emitJumpTables - Emit all the jump tables for a given jump table info
253/// record to the appropriate section.
254void MachOCodeEmitter::emitJumpTables(MachineJumpTableInfo *MJTI) {
255 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
256 if (JT.empty()) return;
257
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000258 // FIXME: handle PIC codegen
Bill Wendling203d3e42007-01-17 22:22:31 +0000259 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
Nate Begeman019f8512006-09-10 23:03:44 +0000260 assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
261
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000262 MachOWriter::MachOSection *Sec = MOW.getJumpTableSection();
263 unsigned TextSecIndex = MOW.getTextSection()->Index;
Bill Wendling203d3e42007-01-17 22:22:31 +0000264 OutputBuffer SecDataOut(TM, Sec->SectionData);
Nate Begeman019f8512006-09-10 23:03:44 +0000265
266 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
267 // For each jump table, record its offset from the start of the section,
268 // reserve space for the relocations to the MBBs, and add the relocations.
269 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000270 JTLocations.push_back(Sec->SectionData.size());
Nate Begeman019f8512006-09-10 23:03:44 +0000271 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000272 MachineRelocation MR(MOW.GetJTRelocation(Sec->SectionData.size(),
Nate Begeman019f8512006-09-10 23:03:44 +0000273 MBBs[mi]));
274 MR.setResultPointer((void *)JTLocations[i]);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000275 MR.setConstantVal(TextSecIndex);
276 Sec->Relocations.push_back(MR);
Bill Wendling203d3e42007-01-17 22:22:31 +0000277 SecDataOut.outaddr(0);
Nate Begeman019f8512006-09-10 23:03:44 +0000278 }
279 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000280 // FIXME: remove when we have unified size + output buffer
281 Sec->size = Sec->SectionData.size();
Nate Begeman019f8512006-09-10 23:03:44 +0000282}
283
Nate Begemaneb883af2006-08-23 21:08:52 +0000284//===----------------------------------------------------------------------===//
285// MachOWriter Implementation
286//===----------------------------------------------------------------------===//
287
288MachOWriter::MachOWriter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000289 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
290 isLittleEndian = TM.getTargetData()->isLittleEndian();
291
292 // Create the machine code emitter object for this target.
Bill Wendlinge9116152007-01-17 09:06:13 +0000293 MCE = new MachOCodeEmitter(*this);
Nate Begemaneb883af2006-08-23 21:08:52 +0000294}
295
296MachOWriter::~MachOWriter() {
297 delete MCE;
298}
299
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000300void MachOWriter::AddSymbolToSection(MachOSection *Sec, GlobalVariable *GV) {
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000301 const Type *Ty = GV->getType()->getElementType();
302 unsigned Size = TM.getTargetData()->getTypeSize(Ty);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000303 unsigned Align = GV->getAlignment();
304 if (Align == 0)
305 Align = TM.getTargetData()->getTypeAlignment(Ty);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000306
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000307 MachOSym Sym(GV, Mang->getValueName(GV), Sec->Index, TM);
308
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000309 // Reserve space in the .bss section for this symbol while maintaining the
310 // desired section alignment, which must be at least as much as required by
311 // this symbol.
Bill Wendling203d3e42007-01-17 22:22:31 +0000312 OutputBuffer SecDataOut(TM, Sec->SectionData);
313
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000314 if (Align) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000315 uint64_t OrigSize = Sec->size;
316 Align = Log2_32(Align);
317 Sec->align = std::max(unsigned(Sec->align), Align);
318 Sec->size = (Sec->size + Align - 1) & ~(Align-1);
319
320 // Add alignment padding to buffer as well.
321 // FIXME: remove when we have unified size + output buffer
322 unsigned AlignedSize = Sec->size - OrigSize;
323 for (unsigned i = 0; i < AlignedSize; ++i)
Bill Wendling203d3e42007-01-17 22:22:31 +0000324 SecDataOut.outbyte(0);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000325 }
326 // Record the offset of the symbol, and then allocate space for it.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000327 // FIXME: remove when we have unified size + output buffer
328 Sym.n_value = Sec->size;
329 Sec->size += Size;
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000330 SymbolTable.push_back(Sym);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000331
332 // Now that we know what section the GlovalVariable is going to be emitted
333 // into, update our mappings.
334 // FIXME: We may also need to update this when outputting non-GlobalVariable
335 // GlobalValues such as functions.
336 GVSection[GV] = Sec;
337 GVOffset[GV] = Sec->SectionData.size();
338
339 // Allocate space in the section for the global.
340 for (unsigned i = 0; i < Size; ++i)
Bill Wendling203d3e42007-01-17 22:22:31 +0000341 SecDataOut.outbyte(0);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000342}
343
Nate Begemaneb883af2006-08-23 21:08:52 +0000344void MachOWriter::EmitGlobal(GlobalVariable *GV) {
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000345 const Type *Ty = GV->getType()->getElementType();
346 unsigned Size = TM.getTargetData()->getTypeSize(Ty);
347 bool NoInit = !GV->hasInitializer();
Nate Begemand2030e62006-08-26 15:46:34 +0000348
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000349 // If this global has a zero initializer, it is part of the .bss or common
350 // section.
351 if (NoInit || GV->getInitializer()->isNullValue()) {
352 // If this global is part of the common block, add it now. Variables are
353 // part of the common block if they are zero initialized and allowed to be
354 // merged with other symbols.
355 if (NoInit || GV->hasLinkOnceLinkage() || GV->hasWeakLinkage()) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000356 MachOSym ExtOrCommonSym(GV, Mang->getValueName(GV), MachOSym::NO_SECT,TM);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000357 // For undefined (N_UNDF) external (N_EXT) types, n_value is the size in
358 // bytes of the symbol.
359 ExtOrCommonSym.n_value = Size;
360 // If the symbol is external, we'll put it on a list of symbols whose
361 // addition to the symbol table is being pended until we find a reference
362 if (NoInit)
363 PendingSyms.push_back(ExtOrCommonSym);
364 else
365 SymbolTable.push_back(ExtOrCommonSym);
366 return;
367 }
368 // Otherwise, this symbol is part of the .bss section.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000369 MachOSection *BSS = getBSSSection();
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000370 AddSymbolToSection(BSS, GV);
371 return;
372 }
373
374 // Scalar read-only data goes in a literal section if the scalar is 4, 8, or
375 // 16 bytes, or a cstring. Other read only data goes into a regular const
376 // section. Read-write data goes in the data section.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000377 MachOSection *Sec = GV->isConstant() ? getConstSection(Ty) : getDataSection();
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000378 AddSymbolToSection(Sec, GV);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000379 InitMem(GV->getInitializer(), &Sec->SectionData[0], GVOffset[GV],
380 TM.getTargetData(), Sec->Relocations);
Nate Begemaneb883af2006-08-23 21:08:52 +0000381}
382
383
384bool MachOWriter::runOnMachineFunction(MachineFunction &MF) {
385 // Nothing to do here, this is all done through the MCE object.
386 return false;
387}
388
389bool MachOWriter::doInitialization(Module &M) {
390 // Set the magic value, now that we know the pointer size and endianness
391 Header.setMagic(isLittleEndian, is64Bit);
392
393 // Set the file type
394 // FIXME: this only works for object files, we do not support the creation
395 // of dynamic libraries or executables at this time.
396 Header.filetype = MachOHeader::MH_OBJECT;
397
398 Mang = new Mangler(M);
399 return false;
400}
401
402/// doFinalization - Now that the module has been completely processed, emit
403/// the Mach-O file to 'O'.
404bool MachOWriter::doFinalization(Module &M) {
Nate Begemand2030e62006-08-26 15:46:34 +0000405 // FIXME: we don't handle debug info yet, we should probably do that.
406
Nate Begemaneb883af2006-08-23 21:08:52 +0000407 // Okay, the.text section has been completed, build the .data, .bss, and
408 // "common" sections next.
409 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
410 I != E; ++I)
411 EmitGlobal(I);
412
413 // Emit the header and load commands.
414 EmitHeaderAndLoadCommands();
415
Nate Begeman019f8512006-09-10 23:03:44 +0000416 // Emit the various sections and their relocation info.
Nate Begemaneb883af2006-08-23 21:08:52 +0000417 EmitSections();
418
Nate Begemand2030e62006-08-26 15:46:34 +0000419 // Write the symbol table and the string table to the end of the file.
420 O.write((char*)&SymT[0], SymT.size());
421 O.write((char*)&StrT[0], StrT.size());
Nate Begemaneb883af2006-08-23 21:08:52 +0000422
423 // We are done with the abstract symbols.
424 SectionList.clear();
425 SymbolTable.clear();
426 DynamicSymbolTable.clear();
427
428 // Release the name mangler object.
429 delete Mang; Mang = 0;
430 return false;
431}
432
433void MachOWriter::EmitHeaderAndLoadCommands() {
434 // Step #0: Fill in the segment load command size, since we need it to figure
435 // out the rest of the header fields
436 MachOSegment SEG("", is64Bit);
437 SEG.nsects = SectionList.size();
438 SEG.cmdsize = SEG.cmdSize(is64Bit) +
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000439 SEG.nsects * SectionList[0]->cmdSize(is64Bit);
Nate Begemaneb883af2006-08-23 21:08:52 +0000440
441 // Step #1: calculate the number of load commands. We always have at least
442 // one, for the LC_SEGMENT load command, plus two for the normal
443 // and dynamic symbol tables, if there are any symbols.
444 Header.ncmds = SymbolTable.empty() ? 1 : 3;
445
446 // Step #2: calculate the size of the load commands
447 Header.sizeofcmds = SEG.cmdsize;
448 if (!SymbolTable.empty())
449 Header.sizeofcmds += SymTab.cmdsize + DySymTab.cmdsize;
450
451 // Step #3: write the header to the file
452 // Local alias to shortenify coming code.
453 DataBuffer &FH = Header.HeaderData;
Bill Wendling203d3e42007-01-17 22:22:31 +0000454 OutputBuffer FHOut(TM, FH);
455
456 FHOut.outword(Header.magic);
457 FHOut.outword(Header.cputype);
458 FHOut.outword(Header.cpusubtype);
459 FHOut.outword(Header.filetype);
460 FHOut.outword(Header.ncmds);
461 FHOut.outword(Header.sizeofcmds);
462 FHOut.outword(Header.flags);
Nate Begemaneb883af2006-08-23 21:08:52 +0000463 if (is64Bit)
Bill Wendling203d3e42007-01-17 22:22:31 +0000464 FHOut.outword(Header.reserved);
Nate Begemaneb883af2006-08-23 21:08:52 +0000465
466 // Step #4: Finish filling in the segment load command and write it out
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000467 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begemaneb883af2006-08-23 21:08:52 +0000468 E = SectionList.end(); I != E; ++I)
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000469 SEG.filesize += (*I)->size;
470
Nate Begemaneb883af2006-08-23 21:08:52 +0000471 SEG.vmsize = SEG.filesize;
472 SEG.fileoff = Header.cmdSize(is64Bit) + Header.sizeofcmds;
473
Bill Wendling203d3e42007-01-17 22:22:31 +0000474 FHOut.outword(SEG.cmd);
475 FHOut.outword(SEG.cmdsize);
476 FHOut.outstring(SEG.segname, 16);
477 FHOut.outaddr(SEG.vmaddr);
478 FHOut.outaddr(SEG.vmsize);
479 FHOut.outaddr(SEG.fileoff);
480 FHOut.outaddr(SEG.filesize);
481 FHOut.outword(SEG.maxprot);
482 FHOut.outword(SEG.initprot);
483 FHOut.outword(SEG.nsects);
484 FHOut.outword(SEG.flags);
Nate Begemaneb883af2006-08-23 21:08:52 +0000485
Nate Begeman94be2482006-09-08 22:42:09 +0000486 // Step #5: Finish filling in the fields of the MachOSections
487 uint64_t currentAddr = 0;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000488 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begemaneb883af2006-08-23 21:08:52 +0000489 E = SectionList.end(); I != E; ++I) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000490 MachOSection *MOS = *I;
491 MOS->addr = currentAddr;
492 MOS->offset = currentAddr + SEG.fileoff;
Nate Begeman019f8512006-09-10 23:03:44 +0000493
Nate Begeman94be2482006-09-08 22:42:09 +0000494 // FIXME: do we need to do something with alignment here?
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000495 currentAddr += MOS->size;
Nate Begeman94be2482006-09-08 22:42:09 +0000496 }
497
498 // Step #6: Calculate the number of relocations for each section and write out
499 // the section commands for each section
500 currentAddr += SEG.fileoff;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000501 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman94be2482006-09-08 22:42:09 +0000502 E = SectionList.end(); I != E; ++I) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000503 MachOSection *MOS = *I;
504 // Convert the relocations to target-specific relocations, and fill in the
505 // relocation offset for this section.
506 CalculateRelocations(*MOS);
507 MOS->reloff = MOS->nreloc ? currentAddr : 0;
508 currentAddr += MOS->nreloc * 8;
Nate Begeman94be2482006-09-08 22:42:09 +0000509
510 // write the finalized section command to the output buffer
Bill Wendling203d3e42007-01-17 22:22:31 +0000511 FHOut.outstring(MOS->sectname, 16);
512 FHOut.outstring(MOS->segname, 16);
513 FHOut.outaddr(MOS->addr);
514 FHOut.outaddr(MOS->size);
515 FHOut.outword(MOS->offset);
516 FHOut.outword(MOS->align);
517 FHOut.outword(MOS->reloff);
518 FHOut.outword(MOS->nreloc);
519 FHOut.outword(MOS->flags);
520 FHOut.outword(MOS->reserved1);
521 FHOut.outword(MOS->reserved2);
Nate Begemaneb883af2006-08-23 21:08:52 +0000522 if (is64Bit)
Bill Wendling203d3e42007-01-17 22:22:31 +0000523 FHOut.outword(MOS->reserved3);
Nate Begemaneb883af2006-08-23 21:08:52 +0000524 }
525
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000526 // Step #7: Emit the symbol table to temporary buffers, so that we know the
527 // size of the string table when we write the next load command.
528 BufferSymbolAndStringTable();
529
530 // Step #8: Emit LC_SYMTAB/LC_DYSYMTAB load commands
Nate Begeman94be2482006-09-08 22:42:09 +0000531 SymTab.symoff = currentAddr;
Nate Begemaneb883af2006-08-23 21:08:52 +0000532 SymTab.nsyms = SymbolTable.size();
Nate Begemand2030e62006-08-26 15:46:34 +0000533 SymTab.stroff = SymTab.symoff + SymT.size();
534 SymTab.strsize = StrT.size();
Bill Wendling203d3e42007-01-17 22:22:31 +0000535 FHOut.outword(SymTab.cmd);
536 FHOut.outword(SymTab.cmdsize);
537 FHOut.outword(SymTab.symoff);
538 FHOut.outword(SymTab.nsyms);
539 FHOut.outword(SymTab.stroff);
540 FHOut.outword(SymTab.strsize);
Nate Begemaneb883af2006-08-23 21:08:52 +0000541
542 // FIXME: set DySymTab fields appropriately
Nate Begemand2030e62006-08-26 15:46:34 +0000543 // We should probably just update these in BufferSymbolAndStringTable since
544 // thats where we're partitioning up the different kinds of symbols.
Bill Wendling203d3e42007-01-17 22:22:31 +0000545 FHOut.outword(DySymTab.cmd);
546 FHOut.outword(DySymTab.cmdsize);
547 FHOut.outword(DySymTab.ilocalsym);
548 FHOut.outword(DySymTab.nlocalsym);
549 FHOut.outword(DySymTab.iextdefsym);
550 FHOut.outword(DySymTab.nextdefsym);
551 FHOut.outword(DySymTab.iundefsym);
552 FHOut.outword(DySymTab.nundefsym);
553 FHOut.outword(DySymTab.tocoff);
554 FHOut.outword(DySymTab.ntoc);
555 FHOut.outword(DySymTab.modtaboff);
556 FHOut.outword(DySymTab.nmodtab);
557 FHOut.outword(DySymTab.extrefsymoff);
558 FHOut.outword(DySymTab.nextrefsyms);
559 FHOut.outword(DySymTab.indirectsymoff);
560 FHOut.outword(DySymTab.nindirectsyms);
561 FHOut.outword(DySymTab.extreloff);
562 FHOut.outword(DySymTab.nextrel);
563 FHOut.outword(DySymTab.locreloff);
564 FHOut.outword(DySymTab.nlocrel);
Nate Begemaneb883af2006-08-23 21:08:52 +0000565
566 O.write((char*)&FH[0], FH.size());
567}
568
569/// EmitSections - Now that we have constructed the file header and load
570/// commands, emit the data for each section to the file.
571void MachOWriter::EmitSections() {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000572 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman019f8512006-09-10 23:03:44 +0000573 E = SectionList.end(); I != E; ++I)
574 // Emit the contents of each section
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000575 O.write((char*)&(*I)->SectionData[0], (*I)->size);
576 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman019f8512006-09-10 23:03:44 +0000577 E = SectionList.end(); I != E; ++I)
578 // Emit the relocation entry data for each section.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000579 O.write((char*)&(*I)->RelocBuffer[0], (*I)->RelocBuffer.size());
Nate Begemaneb883af2006-08-23 21:08:52 +0000580}
581
Nate Begemand2030e62006-08-26 15:46:34 +0000582/// PartitionByLocal - Simple boolean predicate that returns true if Sym is
583/// a local symbol rather than an external symbol.
584bool MachOWriter::PartitionByLocal(const MachOSym &Sym) {
Nate Begemand2030e62006-08-26 15:46:34 +0000585 return (Sym.n_type & (MachOSym::N_EXT | MachOSym::N_PEXT)) == 0;
Nate Begemaneb883af2006-08-23 21:08:52 +0000586}
587
Nate Begemand2030e62006-08-26 15:46:34 +0000588/// PartitionByDefined - Simple boolean predicate that returns true if Sym is
589/// defined in this module.
590bool MachOWriter::PartitionByDefined(const MachOSym &Sym) {
591 // FIXME: Do N_ABS or N_INDR count as defined?
592 return (Sym.n_type & MachOSym::N_SECT) == MachOSym::N_SECT;
593}
Nate Begemaneb883af2006-08-23 21:08:52 +0000594
Nate Begemand2030e62006-08-26 15:46:34 +0000595/// BufferSymbolAndStringTable - Sort the symbols we encountered and assign them
596/// each a string table index so that they appear in the correct order in the
597/// output file.
598void MachOWriter::BufferSymbolAndStringTable() {
599 // The order of the symbol table is:
600 // 1. local symbols
601 // 2. defined external symbols (sorted by name)
602 // 3. undefined external symbols (sorted by name)
603
604 // Sort the symbols by name, so that when we partition the symbols by scope
605 // of definition, we won't have to sort by name within each partition.
606 std::sort(SymbolTable.begin(), SymbolTable.end(), MachOSymCmp());
607
608 // Parition the symbol table entries so that all local symbols come before
609 // all symbols with external linkage. { 1 | 2 3 }
610 std::partition(SymbolTable.begin(), SymbolTable.end(), PartitionByLocal);
611
612 // Advance iterator to beginning of external symbols and partition so that
613 // all external symbols defined in this module come before all external
614 // symbols defined elsewhere. { 1 | 2 | 3 }
615 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
616 E = SymbolTable.end(); I != E; ++I) {
617 if (!PartitionByLocal(*I)) {
618 std::partition(I, E, PartitionByDefined);
619 break;
620 }
621 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000622
623 // Calculate the starting index for each of the local, extern defined, and
624 // undefined symbols, as well as the number of each to put in the LC_DYSYMTAB
625 // load command.
626 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
627 E = SymbolTable.end(); I != E; ++I) {
628 if (PartitionByLocal(*I)) {
629 ++DySymTab.nlocalsym;
630 ++DySymTab.iextdefsym;
631 } else if (PartitionByDefined(*I)) {
632 ++DySymTab.nextdefsym;
633 ++DySymTab.iundefsym;
634 } else {
635 ++DySymTab.nundefsym;
636 }
637 }
Nate Begemand2030e62006-08-26 15:46:34 +0000638
Nate Begemaneb883af2006-08-23 21:08:52 +0000639 // Write out a leading zero byte when emitting string table, for n_strx == 0
640 // which means an empty string.
Bill Wendling203d3e42007-01-17 22:22:31 +0000641 OutputBuffer StrTOut(TM, StrT);
642 StrTOut.outbyte(0);
Nate Begemaneb883af2006-08-23 21:08:52 +0000643
Nate Begemand2030e62006-08-26 15:46:34 +0000644 // The order of the string table is:
645 // 1. strings for external symbols
646 // 2. strings for local symbols
647 // Since this is the opposite order from the symbol table, which we have just
648 // sorted, we can walk the symbol table backwards to output the string table.
649 for (std::vector<MachOSym>::reverse_iterator I = SymbolTable.rbegin(),
650 E = SymbolTable.rend(); I != E; ++I) {
651 if (I->GVName == "") {
652 I->n_strx = 0;
653 } else {
654 I->n_strx = StrT.size();
Bill Wendling203d3e42007-01-17 22:22:31 +0000655 StrTOut.outstring(I->GVName, I->GVName.length()+1);
Nate Begemand2030e62006-08-26 15:46:34 +0000656 }
Nate Begemaneb883af2006-08-23 21:08:52 +0000657 }
Nate Begemand2030e62006-08-26 15:46:34 +0000658
Bill Wendling203d3e42007-01-17 22:22:31 +0000659 OutputBuffer SymTOut(TM, SymT);
660
Nate Begemand2030e62006-08-26 15:46:34 +0000661 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
662 E = SymbolTable.end(); I != E; ++I) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000663 // Add the section base address to the section offset in the n_value field
664 // to calculate the full address.
665 // FIXME: handle symbols where the n_value field is not the address
666 GlobalValue *GV = const_cast<GlobalValue*>(I->GV);
667 if (GV && GVSection[GV])
668 I->n_value += GVSection[GV]->addr;
669
Nate Begemand2030e62006-08-26 15:46:34 +0000670 // Emit nlist to buffer
Bill Wendling203d3e42007-01-17 22:22:31 +0000671 SymTOut.outword(I->n_strx);
672 SymTOut.outbyte(I->n_type);
673 SymTOut.outbyte(I->n_sect);
674 SymTOut.outhalf(I->n_desc);
675 SymTOut.outaddr(I->n_value);
Nate Begemand2030e62006-08-26 15:46:34 +0000676 }
Nate Begemaneb883af2006-08-23 21:08:52 +0000677}
Nate Begeman94be2482006-09-08 22:42:09 +0000678
Nate Begeman019f8512006-09-10 23:03:44 +0000679/// CalculateRelocations - For each MachineRelocation in the current section,
680/// calculate the index of the section containing the object to be relocated,
681/// and the offset into that section. From this information, create the
682/// appropriate target-specific MachORelocation type and add buffer it to be
683/// written out after we are finished writing out sections.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000684void MachOWriter::CalculateRelocations(MachOSection &MOS) {
Nate Begeman019f8512006-09-10 23:03:44 +0000685 for (unsigned i = 0, e = MOS.Relocations.size(); i != e; ++i) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000686 MachineRelocation &MR = MOS.Relocations[i];
687 unsigned TargetSection = MR.getConstantVal();
688
689 // Since we may not have seen the GlobalValue we were interested in yet at
690 // the time we emitted the relocation for it, fix it up now so that it
691 // points to the offset into the correct section.
692 if (MR.isGlobalValue()) {
693 GlobalValue *GV = MR.getGlobalValue();
694 MachOSection *MOSPtr = GVSection[GV];
695 intptr_t offset = GVOffset[GV];
696
697 assert(MOSPtr && "Trying to relocate unknown global!");
698
699 TargetSection = MOSPtr->Index;
700 MR.setResultPointer((void*)offset);
701 }
702
703 GetTargetRelocation(MR, MOS, *SectionList[TargetSection-1]);
Nate Begeman019f8512006-09-10 23:03:44 +0000704 }
Nate Begeman019f8512006-09-10 23:03:44 +0000705}
706
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000707// InitMem - Write the value of a Constant to the specified memory location,
708// converting it into bytes and relocations.
709void MachOWriter::InitMem(const Constant *C, void *Addr, intptr_t Offset,
710 const TargetData *TD,
711 std::vector<MachineRelocation> &MRs) {
712 typedef std::pair<const Constant*, intptr_t> CPair;
713 std::vector<CPair> WorkList;
714
715 WorkList.push_back(CPair(C,(intptr_t)Addr + Offset));
716
717 while (!WorkList.empty()) {
718 const Constant *PC = WorkList.back().first;
719 intptr_t PA = WorkList.back().second;
720 WorkList.pop_back();
721
722 if (isa<UndefValue>(PC)) {
723 continue;
724 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(PC)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000725 unsigned ElementSize = TD->getTypeSize(CP->getType()->getElementType());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000726 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
727 WorkList.push_back(CPair(CP->getOperand(i), PA+i*ElementSize));
728 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(PC)) {
729 //
730 // FIXME: Handle ConstantExpression. See EE::getConstantValue()
731 //
732 switch (CE->getOpcode()) {
733 case Instruction::GetElementPtr:
734 case Instruction::Add:
735 default:
736 cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
737 abort();
738 break;
739 }
740 } else if (PC->getType()->isFirstClassType()) {
741 unsigned char *ptr = (unsigned char *)PA;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000742 switch (PC->getType()->getTypeID()) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000743 case Type::IntegerTyID: {
744 unsigned NumBits = cast<IntegerType>(PC->getType())->getBitWidth();
745 uint64_t val = cast<ConstantInt>(PC)->getZExtValue();
746 if (NumBits <= 8)
747 ptr[0] = val;
748 else if (NumBits <= 16) {
749 if (TD->isBigEndian())
750 val = ByteSwap_16(val);
751 ptr[0] = val;
752 ptr[1] = val >> 8;
753 } else if (NumBits <= 32) {
754 if (TD->isBigEndian())
755 val = ByteSwap_32(val);
756 ptr[0] = val;
757 ptr[1] = val >> 8;
758 ptr[2] = val >> 16;
759 ptr[3] = val >> 24;
760 } else if (NumBits <= 64) {
761 if (TD->isBigEndian())
762 val = ByteSwap_64(val);
763 ptr[0] = val;
764 ptr[1] = val >> 8;
765 ptr[2] = val >> 16;
766 ptr[3] = val >> 24;
767 ptr[4] = val >> 32;
768 ptr[5] = val >> 40;
769 ptr[6] = val >> 48;
770 ptr[7] = val >> 56;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000771 } else {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000772 assert(0 && "Not implemented: bit widths > 64");
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000773 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000774 break;
775 }
776 case Type::FloatTyID: {
777 uint64_t val = FloatToBits(cast<ConstantFP>(PC)->getValue());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000778 if (TD->isBigEndian())
779 val = ByteSwap_32(val);
780 ptr[0] = val;
781 ptr[1] = val >> 8;
782 ptr[2] = val >> 16;
783 ptr[3] = val >> 24;
784 break;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000785 }
786 case Type::DoubleTyID: {
787 uint64_t val = DoubleToBits(cast<ConstantFP>(PC)->getValue());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000788 if (TD->isBigEndian())
789 val = ByteSwap_64(val);
790 ptr[0] = val;
791 ptr[1] = val >> 8;
792 ptr[2] = val >> 16;
793 ptr[3] = val >> 24;
794 ptr[4] = val >> 32;
795 ptr[5] = val >> 40;
796 ptr[6] = val >> 48;
797 ptr[7] = val >> 56;
798 break;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000799 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000800 case Type::PointerTyID:
801 if (isa<ConstantPointerNull>(C))
802 memset(ptr, 0, TD->getPointerSize());
803 else if (const GlobalValue* GV = dyn_cast<GlobalValue>(C))
804 // FIXME: what about function stubs?
805 MRs.push_back(MachineRelocation::getGV(PA-(intptr_t)Addr,
806 MachineRelocation::VANILLA,
807 const_cast<GlobalValue*>(GV)));
808 else
809 assert(0 && "Unknown constant pointer type!");
810 break;
811 default:
812 cerr << "ERROR: Constant unimp for type: " << *PC->getType() << "\n";
813 abort();
814 }
815 } else if (isa<ConstantAggregateZero>(PC)) {
816 memset((void*)PA, 0, (size_t)TD->getTypeSize(PC->getType()));
817 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(PC)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000818 unsigned ElementSize = TD->getTypeSize(CPA->getType()->getElementType());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000819 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
820 WorkList.push_back(CPair(CPA->getOperand(i), PA+i*ElementSize));
821 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(PC)) {
822 const StructLayout *SL =
823 TD->getStructLayout(cast<StructType>(CPS->getType()));
824 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
825 WorkList.push_back(CPair(CPS->getOperand(i), PA+SL->MemberOffsets[i]));
826 } else {
827 cerr << "Bad Type: " << *PC->getType() << "\n";
828 assert(0 && "Unknown constant type to initialize memory with!");
829 }
830 }
831}
832
833MachOSym::MachOSym(const GlobalValue *gv, std::string name, uint8_t sect,
834 TargetMachine &TM) :
835 GV(gv), n_strx(0), n_type(sect == NO_SECT ? N_UNDF : N_SECT), n_sect(sect),
836 n_desc(0), n_value(0) {
837
838 const TargetAsmInfo *TAI = TM.getTargetAsmInfo();
839
Nate Begeman94be2482006-09-08 22:42:09 +0000840 switch (GV->getLinkage()) {
841 default:
842 assert(0 && "Unexpected linkage type!");
843 break;
844 case GlobalValue::WeakLinkage:
845 case GlobalValue::LinkOnceLinkage:
846 assert(!isa<Function>(gv) && "Unexpected linkage type for Function!");
847 case GlobalValue::ExternalLinkage:
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000848 GVName = TAI->getGlobalPrefix() + name;
Nate Begeman94be2482006-09-08 22:42:09 +0000849 n_type |= N_EXT;
850 break;
851 case GlobalValue::InternalLinkage:
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000852 GVName = TAI->getPrivateGlobalPrefix() + name;
Nate Begeman94be2482006-09-08 22:42:09 +0000853 break;
854 }
855}