blob: 5164103d273f991296c5db90ddb771fbaf4c186e [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
Bill Wendling8f84f1f2007-02-08 01:35:27 +000025#include "MachOWriter.h"
Nate Begemanbfaaaa62006-12-11 02:20:45 +000026#include "llvm/Constants.h"
27#include "llvm/DerivedTypes.h"
Nate Begemaneb883af2006-08-23 21:08:52 +000028#include "llvm/Module.h"
Bill Wendling8f84f1f2007-02-08 01:35:27 +000029#include "llvm/PassManager.h"
30#include "llvm/CodeGen/FileWriters.h"
Nate Begemaneb883af2006-08-23 21:08:52 +000031#include "llvm/CodeGen/MachineCodeEmitter.h"
32#include "llvm/CodeGen/MachineConstantPool.h"
Nate Begeman019f8512006-09-10 23:03:44 +000033#include "llvm/CodeGen/MachineJumpTableInfo.h"
Nate Begemanbfaaaa62006-12-11 02:20:45 +000034#include "llvm/Target/TargetAsmInfo.h"
Nate Begemaneb883af2006-08-23 21:08:52 +000035#include "llvm/Target/TargetJITInfo.h"
Nate Begemaneb883af2006-08-23 21:08:52 +000036#include "llvm/Support/Mangler.h"
Nate Begemanf8f2c5a2006-08-25 06:36:58 +000037#include "llvm/Support/MathExtras.h"
Bill Wendling203d3e42007-01-17 22:22:31 +000038#include "llvm/Support/OutputBuffer.h"
Nate Begemanbfaaaa62006-12-11 02:20:45 +000039#include "llvm/Support/Streams.h"
Nate Begemand2030e62006-08-26 15:46:34 +000040#include <algorithm>
Nate Begemaneb883af2006-08-23 21:08:52 +000041using namespace llvm;
42
Bill Wendling8f84f1f2007-02-08 01:35:27 +000043/// AddMachOWriter - Concrete function to add the Mach-O writer to the function
44/// pass manager.
45MachineCodeEmitter *llvm::AddMachOWriter(FunctionPassManager &FPM,
46 std::ostream &O,
47 TargetMachine &TM) {
48 MachOWriter *MOW = new MachOWriter(O, TM);
49 FPM.add(MOW);
50 return &MOW->getMachineCodeEmitter();
51}
52
Nate Begemaneb883af2006-08-23 21:08:52 +000053//===----------------------------------------------------------------------===//
54// MachOCodeEmitter Implementation
55//===----------------------------------------------------------------------===//
56
57namespace llvm {
58 /// MachOCodeEmitter - This class is used by the MachOWriter to emit the code
59 /// for functions to the Mach-O file.
60 class MachOCodeEmitter : public MachineCodeEmitter {
61 MachOWriter &MOW;
Nate Begemaneb883af2006-08-23 21:08:52 +000062
Bill Wendling203d3e42007-01-17 22:22:31 +000063 /// Target machine description.
64 TargetMachine &TM;
65
Bill Wendlingc904a5b2007-01-18 01:23:11 +000066 /// is64Bit/isLittleEndian - This information is inferred from the target
67 /// machine directly, indicating what header values and flags to set.
68 bool is64Bit, isLittleEndian;
69
Nate Begemaneb883af2006-08-23 21:08:52 +000070 /// Relocations - These are the relocations that the function needs, as
71 /// emitted.
72 std::vector<MachineRelocation> Relocations;
Nate Begeman019f8512006-09-10 23:03:44 +000073
74 /// CPLocations - This is a map of constant pool indices to offsets from the
75 /// start of the section for that constant pool index.
76 std::vector<intptr_t> CPLocations;
77
Nate Begemanbfaaaa62006-12-11 02:20:45 +000078 /// CPSections - This is a map of constant pool indices to the MachOSection
79 /// containing the constant pool entry for that index.
80 std::vector<unsigned> CPSections;
81
Nate Begeman019f8512006-09-10 23:03:44 +000082 /// JTLocations - This is a map of jump table indices to offsets from the
83 /// start of the section for that jump table index.
84 std::vector<intptr_t> JTLocations;
Nate Begemaneb883af2006-08-23 21:08:52 +000085
86 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
87 /// It is filled in by the StartMachineBasicBlock callback and queried by
88 /// the getMachineBasicBlockAddress callback.
89 std::vector<intptr_t> MBBLocations;
90
91 public:
Bill Wendlingc904a5b2007-01-18 01:23:11 +000092 MachOCodeEmitter(MachOWriter &mow) : MOW(mow), TM(MOW.TM) {
93 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
94 isLittleEndian = TM.getTargetData()->isLittleEndian();
95 }
Nate Begemaneb883af2006-08-23 21:08:52 +000096
Nate Begemanc2b2d6a2007-02-07 05:47:16 +000097 virtual void startFunction(MachineFunction &MF);
98 virtual bool finishFunction(MachineFunction &MF);
Nate Begemaneb883af2006-08-23 21:08:52 +000099
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000100 virtual void addRelocation(const MachineRelocation &MR) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000101 Relocations.push_back(MR);
102 }
103
Nate Begeman019f8512006-09-10 23:03:44 +0000104 void emitConstantPool(MachineConstantPool *MCP);
105 void emitJumpTables(MachineJumpTableInfo *MJTI);
106
Nate Begemaneb883af2006-08-23 21:08:52 +0000107 virtual intptr_t getConstantPoolEntryAddress(unsigned Index) const {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000108 assert(CPLocations.size() > Index && "CP not emitted!");
Nate Begemana0a62782007-02-28 09:16:38 +0000109 return CPLocations[Index];
Nate Begemaneb883af2006-08-23 21:08:52 +0000110 }
111 virtual intptr_t getJumpTableEntryAddress(unsigned Index) const {
Nate Begeman019f8512006-09-10 23:03:44 +0000112 assert(JTLocations.size() > Index && "JT not emitted!");
113 return JTLocations[Index];
114 }
115
116 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
117 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
118 MBBLocations.resize((MBB->getNumber()+1)*2);
119 MBBLocations[MBB->getNumber()] = getCurrentPCOffset();
Nate Begemaneb883af2006-08-23 21:08:52 +0000120 }
121
122 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
123 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
124 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
125 return MBBLocations[MBB->getNumber()];
126 }
127
128 /// JIT SPECIFIC FUNCTIONS - DO NOT IMPLEMENT THESE HERE!
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000129 virtual void startFunctionStub(unsigned StubSize, unsigned Alignment = 1) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000130 assert(0 && "JIT specific function called!");
131 abort();
132 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000133 virtual void *finishFunctionStub(const Function *F) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000134 assert(0 && "JIT specific function called!");
135 abort();
136 return 0;
137 }
138 };
139}
140
141/// startFunction - This callback is invoked when a new machine function is
142/// about to be emitted.
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000143void MachOCodeEmitter::startFunction(MachineFunction &MF) {
144 const TargetData *TD = TM.getTargetData();
145 const Function *F = MF.getFunction();
146
Nate Begemaneb883af2006-08-23 21:08:52 +0000147 // Align the output buffer to the appropriate alignment, power of 2.
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000148 unsigned FnAlign = F->getAlignment();
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000149 unsigned TDAlign = TD->getPrefTypeAlignment(F->getType());
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000150 unsigned Align = Log2_32(std::max(FnAlign, TDAlign));
151 assert(!(Align & (Align-1)) && "Alignment is not a power of two!");
Nate Begemaneb883af2006-08-23 21:08:52 +0000152
153 // Get the Mach-O Section that this function belongs in.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000154 MachOWriter::MachOSection *MOS = MOW.getTextSection();
Nate Begemaneb883af2006-08-23 21:08:52 +0000155
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000156 // FIXME: better memory management
Nate Begemaneb883af2006-08-23 21:08:52 +0000157 MOS->SectionData.reserve(4096);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000158 BufferBegin = &MOS->SectionData[0];
Nate Begemaneb883af2006-08-23 21:08:52 +0000159 BufferEnd = BufferBegin + MOS->SectionData.capacity();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000160
Nate Begeman6635f352007-01-26 22:39:48 +0000161 // Upgrade the section alignment if required.
162 if (MOS->align < Align) MOS->align = Align;
163
164 // Round the size up to the correct alignment for starting the new function.
165 if ((MOS->size & ((1 << Align) - 1)) != 0) {
166 MOS->size += (1 << Align);
167 MOS->size &= ~((1 << Align) - 1);
168 }
169
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000170 // FIXME: Using MOS->size directly here instead of calculating it from the
171 // output buffer size (impossible because the code emitter deals only in raw
172 // bytes) forces us to manually synchronize size and write padding zero bytes
173 // to the output buffer for all non-text sections. For text sections, we do
174 // not synchonize the output buffer, and we just blow up if anyone tries to
175 // write non-code to it. An assert should probably be added to
176 // AddSymbolToSection to prevent calling it on the text section.
Nate Begemaneb883af2006-08-23 21:08:52 +0000177 CurBufferPtr = BufferBegin + MOS->size;
178
Nate Begeman019f8512006-09-10 23:03:44 +0000179 // Clear per-function data structures.
180 CPLocations.clear();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000181 CPSections.clear();
Nate Begeman019f8512006-09-10 23:03:44 +0000182 JTLocations.clear();
Nate Begemaneb883af2006-08-23 21:08:52 +0000183 MBBLocations.clear();
184}
185
186/// finishFunction - This callback is invoked after the function is completely
187/// finished.
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000188bool MachOCodeEmitter::finishFunction(MachineFunction &MF) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000189 // Get the Mach-O Section that this function belongs in.
190 MachOWriter::MachOSection *MOS = MOW.getTextSection();
191
Nate Begemaneb883af2006-08-23 21:08:52 +0000192 // Get a symbol for the function to add to the symbol table
Nate Begeman6635f352007-01-26 22:39:48 +0000193 // FIXME: it seems like we should call something like AddSymbolToSection
194 // in startFunction rather than changing the section size and symbol n_value
195 // here.
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000196 const GlobalValue *FuncV = MF.getFunction();
Bill Wendling203d3e42007-01-17 22:22:31 +0000197 MachOSym FnSym(FuncV, MOW.Mang->getValueName(FuncV), MOS->Index, TM);
Nate Begeman6635f352007-01-26 22:39:48 +0000198 FnSym.n_value = MOS->size;
199 MOS->size = CurBufferPtr - BufferBegin;
200
Nate Begeman019f8512006-09-10 23:03:44 +0000201 // Emit constant pool to appropriate section(s)
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000202 emitConstantPool(MF.getConstantPool());
Nate Begeman019f8512006-09-10 23:03:44 +0000203
204 // Emit jump tables to appropriate section
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000205 emitJumpTables(MF.getJumpTableInfo());
Nate Begemaneb883af2006-08-23 21:08:52 +0000206
Nate Begeman019f8512006-09-10 23:03:44 +0000207 // If we have emitted any relocations to function-specific objects such as
208 // basic blocks, constant pools entries, or jump tables, record their
209 // addresses now so that we can rewrite them with the correct addresses
210 // later.
Nate Begemaneb883af2006-08-23 21:08:52 +0000211 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
212 MachineRelocation &MR = Relocations[i];
Nate Begeman019f8512006-09-10 23:03:44 +0000213 intptr_t Addr;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000214
Nate Begemaneb883af2006-08-23 21:08:52 +0000215 if (MR.isBasicBlock()) {
Nate Begeman019f8512006-09-10 23:03:44 +0000216 Addr = getMachineBasicBlockAddress(MR.getBasicBlock());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000217 MR.setConstantVal(MOS->Index);
218 MR.setResultPointer((void*)Addr);
219 } else if (MR.isJumpTableIndex()) {
220 Addr = getJumpTableEntryAddress(MR.getJumpTableIndex());
221 MR.setConstantVal(MOW.getJumpTableSection()->Index);
222 MR.setResultPointer((void*)Addr);
Nate Begeman019f8512006-09-10 23:03:44 +0000223 } else if (MR.isConstantPoolIndex()) {
224 Addr = getConstantPoolEntryAddress(MR.getConstantPoolIndex());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000225 MR.setConstantVal(CPSections[MR.getConstantPoolIndex()]);
226 MR.setResultPointer((void*)Addr);
Nate Begemanfec910c2007-02-28 07:40:50 +0000227 } else if (MR.isGlobalValue()) {
228 // FIXME: This should be a set or something that uniques
229 MOW.PendingGlobals.push_back(MR.getGlobalValue());
230 } else {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000231 assert(0 && "Unhandled relocation type");
Nate Begemaneb883af2006-08-23 21:08:52 +0000232 }
Nate Begeman019f8512006-09-10 23:03:44 +0000233 MOS->Relocations.push_back(MR);
Nate Begemaneb883af2006-08-23 21:08:52 +0000234 }
235 Relocations.clear();
236
237 // Finally, add it to the symtab.
238 MOW.SymbolTable.push_back(FnSym);
239 return false;
240}
241
Nate Begeman019f8512006-09-10 23:03:44 +0000242/// emitConstantPool - For each constant pool entry, figure out which section
243/// the constant should live in, allocate space for it, and emit it to the
244/// Section data buffer.
245void MachOCodeEmitter::emitConstantPool(MachineConstantPool *MCP) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000246 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
247 if (CP.empty()) return;
248
249 // FIXME: handle PIC codegen
Bill Wendling203d3e42007-01-17 22:22:31 +0000250 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000251 assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
252
253 // Although there is no strict necessity that I am aware of, we will do what
254 // gcc for OS X does and put each constant pool entry in a section of constant
255 // objects of a certain size. That means that float constants go in the
256 // literal4 section, and double objects go in literal8, etc.
257 //
258 // FIXME: revisit this decision if we ever do the "stick everything into one
259 // "giant object for PIC" optimization.
260 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
261 const Type *Ty = CP[i].getType();
Bill Wendling203d3e42007-01-17 22:22:31 +0000262 unsigned Size = TM.getTargetData()->getTypeSize(Ty);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000263
Nate Begeman1257c852007-01-29 21:20:42 +0000264 MachOWriter::MachOSection *Sec = MOW.getConstSection(CP[i].Val.ConstVal);
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000265 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000266
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000267 CPLocations.push_back(Sec->SectionData.size());
268 CPSections.push_back(Sec->Index);
269
270 // FIXME: remove when we have unified size + output buffer
271 Sec->size += Size;
272
273 // Allocate space in the section for the global.
274 // FIXME: need alignment?
275 // FIXME: share between here and AddSymbolToSection?
276 for (unsigned j = 0; j < Size; ++j)
Bill Wendling203d3e42007-01-17 22:22:31 +0000277 SecDataOut.outbyte(0);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000278
279 MOW.InitMem(CP[i].Val.ConstVal, &Sec->SectionData[0], CPLocations[i],
Bill Wendling203d3e42007-01-17 22:22:31 +0000280 TM.getTargetData(), Sec->Relocations);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000281 }
Nate Begeman019f8512006-09-10 23:03:44 +0000282}
283
284/// emitJumpTables - Emit all the jump tables for a given jump table info
285/// record to the appropriate section.
286void MachOCodeEmitter::emitJumpTables(MachineJumpTableInfo *MJTI) {
287 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
288 if (JT.empty()) return;
289
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000290 // FIXME: handle PIC codegen
Bill Wendling203d3e42007-01-17 22:22:31 +0000291 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
Nate Begeman019f8512006-09-10 23:03:44 +0000292 assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
293
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000294 MachOWriter::MachOSection *Sec = MOW.getJumpTableSection();
295 unsigned TextSecIndex = MOW.getTextSection()->Index;
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000296 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
Nate Begeman019f8512006-09-10 23:03:44 +0000297
298 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
299 // For each jump table, record its offset from the start of the section,
300 // reserve space for the relocations to the MBBs, and add the relocations.
301 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000302 JTLocations.push_back(Sec->SectionData.size());
Nate Begeman019f8512006-09-10 23:03:44 +0000303 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000304 MachineRelocation MR(MOW.GetJTRelocation(Sec->SectionData.size(),
Nate Begeman019f8512006-09-10 23:03:44 +0000305 MBBs[mi]));
306 MR.setResultPointer((void *)JTLocations[i]);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000307 MR.setConstantVal(TextSecIndex);
308 Sec->Relocations.push_back(MR);
Bill Wendling203d3e42007-01-17 22:22:31 +0000309 SecDataOut.outaddr(0);
Nate Begeman019f8512006-09-10 23:03:44 +0000310 }
311 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000312 // FIXME: remove when we have unified size + output buffer
313 Sec->size = Sec->SectionData.size();
Nate Begeman019f8512006-09-10 23:03:44 +0000314}
315
Nate Begemaneb883af2006-08-23 21:08:52 +0000316//===----------------------------------------------------------------------===//
317// MachOWriter Implementation
318//===----------------------------------------------------------------------===//
319
320MachOWriter::MachOWriter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000321 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
322 isLittleEndian = TM.getTargetData()->isLittleEndian();
323
324 // Create the machine code emitter object for this target.
Bill Wendlinge9116152007-01-17 09:06:13 +0000325 MCE = new MachOCodeEmitter(*this);
Nate Begemaneb883af2006-08-23 21:08:52 +0000326}
327
328MachOWriter::~MachOWriter() {
329 delete MCE;
330}
331
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000332void MachOWriter::AddSymbolToSection(MachOSection *Sec, GlobalVariable *GV) {
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000333 const Type *Ty = GV->getType()->getElementType();
334 unsigned Size = TM.getTargetData()->getTypeSize(Ty);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000335 unsigned Align = GV->getAlignment();
336 if (Align == 0)
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000337 Align = TM.getTargetData()->getPrefTypeAlignment(Ty);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000338
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000339 // Reserve space in the .bss section for this symbol while maintaining the
340 // desired section alignment, which must be at least as much as required by
341 // this symbol.
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000342 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000343
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000344 if (Align) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000345 uint64_t OrigSize = Sec->size;
346 Align = Log2_32(Align);
347 Sec->align = std::max(unsigned(Sec->align), Align);
348 Sec->size = (Sec->size + Align - 1) & ~(Align-1);
349
350 // Add alignment padding to buffer as well.
351 // FIXME: remove when we have unified size + output buffer
352 unsigned AlignedSize = Sec->size - OrigSize;
353 for (unsigned i = 0; i < AlignedSize; ++i)
Bill Wendling203d3e42007-01-17 22:22:31 +0000354 SecDataOut.outbyte(0);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000355 }
Nate Begemanfec910c2007-02-28 07:40:50 +0000356 // Globals without external linkage apparently do not go in the symbol table.
357 if (GV->getLinkage() != GlobalValue::InternalLinkage) {
358 MachOSym Sym(GV, Mang->getValueName(GV), Sec->Index, TM);
359 Sym.n_value = Sec->size;
360 SymbolTable.push_back(Sym);
361 }
362
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000363 // Record the offset of the symbol, and then allocate space for it.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000364 // FIXME: remove when we have unified size + output buffer
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000365 Sec->size += Size;
Nate Begemanfec910c2007-02-28 07:40:50 +0000366
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000367 // Now that we know what section the GlovalVariable is going to be emitted
368 // into, update our mappings.
369 // FIXME: We may also need to update this when outputting non-GlobalVariable
370 // GlobalValues such as functions.
371 GVSection[GV] = Sec;
372 GVOffset[GV] = Sec->SectionData.size();
373
374 // Allocate space in the section for the global.
375 for (unsigned i = 0; i < Size; ++i)
Bill Wendling203d3e42007-01-17 22:22:31 +0000376 SecDataOut.outbyte(0);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000377}
378
Nate Begemaneb883af2006-08-23 21:08:52 +0000379void MachOWriter::EmitGlobal(GlobalVariable *GV) {
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000380 const Type *Ty = GV->getType()->getElementType();
381 unsigned Size = TM.getTargetData()->getTypeSize(Ty);
382 bool NoInit = !GV->hasInitializer();
Nate Begemand2030e62006-08-26 15:46:34 +0000383
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000384 // If this global has a zero initializer, it is part of the .bss or common
385 // section.
386 if (NoInit || GV->getInitializer()->isNullValue()) {
387 // If this global is part of the common block, add it now. Variables are
388 // part of the common block if they are zero initialized and allowed to be
389 // merged with other symbols.
390 if (NoInit || GV->hasLinkOnceLinkage() || GV->hasWeakLinkage()) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000391 MachOSym ExtOrCommonSym(GV, Mang->getValueName(GV), MachOSym::NO_SECT,TM);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000392 // For undefined (N_UNDF) external (N_EXT) types, n_value is the size in
393 // bytes of the symbol.
394 ExtOrCommonSym.n_value = Size;
Nate Begemanfec910c2007-02-28 07:40:50 +0000395 SymbolTable.push_back(ExtOrCommonSym);
396 // Remember that we've seen this symbol
397 GVOffset[GV] = Size;
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000398 return;
399 }
400 // Otherwise, this symbol is part of the .bss section.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000401 MachOSection *BSS = getBSSSection();
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000402 AddSymbolToSection(BSS, GV);
403 return;
404 }
405
406 // Scalar read-only data goes in a literal section if the scalar is 4, 8, or
407 // 16 bytes, or a cstring. Other read only data goes into a regular const
408 // section. Read-write data goes in the data section.
Nate Begeman1257c852007-01-29 21:20:42 +0000409 MachOSection *Sec = GV->isConstant() ? getConstSection(GV->getInitializer()) :
410 getDataSection();
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000411 AddSymbolToSection(Sec, GV);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000412 InitMem(GV->getInitializer(), &Sec->SectionData[0], GVOffset[GV],
413 TM.getTargetData(), Sec->Relocations);
Nate Begemaneb883af2006-08-23 21:08:52 +0000414}
415
416
417bool MachOWriter::runOnMachineFunction(MachineFunction &MF) {
418 // Nothing to do here, this is all done through the MCE object.
419 return false;
420}
421
422bool MachOWriter::doInitialization(Module &M) {
423 // Set the magic value, now that we know the pointer size and endianness
424 Header.setMagic(isLittleEndian, is64Bit);
425
426 // Set the file type
427 // FIXME: this only works for object files, we do not support the creation
428 // of dynamic libraries or executables at this time.
429 Header.filetype = MachOHeader::MH_OBJECT;
430
431 Mang = new Mangler(M);
432 return false;
433}
434
435/// doFinalization - Now that the module has been completely processed, emit
436/// the Mach-O file to 'O'.
437bool MachOWriter::doFinalization(Module &M) {
Nate Begemand2030e62006-08-26 15:46:34 +0000438 // FIXME: we don't handle debug info yet, we should probably do that.
439
Nate Begemaneb883af2006-08-23 21:08:52 +0000440 // Okay, the.text section has been completed, build the .data, .bss, and
441 // "common" sections next.
442 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
443 I != E; ++I)
444 EmitGlobal(I);
445
446 // Emit the header and load commands.
447 EmitHeaderAndLoadCommands();
448
Nate Begeman019f8512006-09-10 23:03:44 +0000449 // Emit the various sections and their relocation info.
Nate Begemaneb883af2006-08-23 21:08:52 +0000450 EmitSections();
451
Nate Begemand2030e62006-08-26 15:46:34 +0000452 // Write the symbol table and the string table to the end of the file.
453 O.write((char*)&SymT[0], SymT.size());
454 O.write((char*)&StrT[0], StrT.size());
Nate Begemaneb883af2006-08-23 21:08:52 +0000455
456 // We are done with the abstract symbols.
457 SectionList.clear();
458 SymbolTable.clear();
459 DynamicSymbolTable.clear();
460
461 // Release the name mangler object.
462 delete Mang; Mang = 0;
463 return false;
464}
465
466void MachOWriter::EmitHeaderAndLoadCommands() {
467 // Step #0: Fill in the segment load command size, since we need it to figure
468 // out the rest of the header fields
469 MachOSegment SEG("", is64Bit);
470 SEG.nsects = SectionList.size();
471 SEG.cmdsize = SEG.cmdSize(is64Bit) +
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000472 SEG.nsects * SectionList[0]->cmdSize(is64Bit);
Nate Begemaneb883af2006-08-23 21:08:52 +0000473
474 // Step #1: calculate the number of load commands. We always have at least
475 // one, for the LC_SEGMENT load command, plus two for the normal
476 // and dynamic symbol tables, if there are any symbols.
477 Header.ncmds = SymbolTable.empty() ? 1 : 3;
478
479 // Step #2: calculate the size of the load commands
480 Header.sizeofcmds = SEG.cmdsize;
481 if (!SymbolTable.empty())
482 Header.sizeofcmds += SymTab.cmdsize + DySymTab.cmdsize;
483
484 // Step #3: write the header to the file
485 // Local alias to shortenify coming code.
486 DataBuffer &FH = Header.HeaderData;
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000487 OutputBuffer FHOut(FH, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000488
489 FHOut.outword(Header.magic);
Bill Wendling2b721822007-01-24 07:13:56 +0000490 FHOut.outword(TM.getMachOWriterInfo()->getCPUType());
491 FHOut.outword(TM.getMachOWriterInfo()->getCPUSubType());
Bill Wendling203d3e42007-01-17 22:22:31 +0000492 FHOut.outword(Header.filetype);
493 FHOut.outword(Header.ncmds);
494 FHOut.outword(Header.sizeofcmds);
495 FHOut.outword(Header.flags);
Nate Begemaneb883af2006-08-23 21:08:52 +0000496 if (is64Bit)
Bill Wendling203d3e42007-01-17 22:22:31 +0000497 FHOut.outword(Header.reserved);
Nate Begemaneb883af2006-08-23 21:08:52 +0000498
499 // Step #4: Finish filling in the segment load command and write it out
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000500 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begemaneb883af2006-08-23 21:08:52 +0000501 E = SectionList.end(); I != E; ++I)
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000502 SEG.filesize += (*I)->size;
503
Nate Begemaneb883af2006-08-23 21:08:52 +0000504 SEG.vmsize = SEG.filesize;
505 SEG.fileoff = Header.cmdSize(is64Bit) + Header.sizeofcmds;
506
Bill Wendling203d3e42007-01-17 22:22:31 +0000507 FHOut.outword(SEG.cmd);
508 FHOut.outword(SEG.cmdsize);
509 FHOut.outstring(SEG.segname, 16);
510 FHOut.outaddr(SEG.vmaddr);
511 FHOut.outaddr(SEG.vmsize);
512 FHOut.outaddr(SEG.fileoff);
513 FHOut.outaddr(SEG.filesize);
514 FHOut.outword(SEG.maxprot);
515 FHOut.outword(SEG.initprot);
516 FHOut.outword(SEG.nsects);
517 FHOut.outword(SEG.flags);
Nate Begemaneb883af2006-08-23 21:08:52 +0000518
Nate Begeman94be2482006-09-08 22:42:09 +0000519 // Step #5: Finish filling in the fields of the MachOSections
520 uint64_t currentAddr = 0;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000521 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begemaneb883af2006-08-23 21:08:52 +0000522 E = SectionList.end(); I != E; ++I) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000523 MachOSection *MOS = *I;
524 MOS->addr = currentAddr;
525 MOS->offset = currentAddr + SEG.fileoff;
Nate Begeman019f8512006-09-10 23:03:44 +0000526
Nate Begeman94be2482006-09-08 22:42:09 +0000527 // FIXME: do we need to do something with alignment here?
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000528 currentAddr += MOS->size;
Nate Begeman94be2482006-09-08 22:42:09 +0000529 }
530
Nate Begemanfec910c2007-02-28 07:40:50 +0000531 // Step #6: Emit the symbol table to temporary buffers, so that we know the
532 // size of the string table when we write the next load command. This also
533 // sorts and assigns indices to each of the symbols, which is necessary for
534 // emitting relocations to externally-defined objects.
535 BufferSymbolAndStringTable();
536
537 // Step #7: Calculate the number of relocations for each section and write out
Nate Begeman94be2482006-09-08 22:42:09 +0000538 // the section commands for each section
539 currentAddr += SEG.fileoff;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000540 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman94be2482006-09-08 22:42:09 +0000541 E = SectionList.end(); I != E; ++I) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000542 MachOSection *MOS = *I;
543 // Convert the relocations to target-specific relocations, and fill in the
544 // relocation offset for this section.
545 CalculateRelocations(*MOS);
546 MOS->reloff = MOS->nreloc ? currentAddr : 0;
547 currentAddr += MOS->nreloc * 8;
Nate Begeman94be2482006-09-08 22:42:09 +0000548
549 // write the finalized section command to the output buffer
Bill Wendling203d3e42007-01-17 22:22:31 +0000550 FHOut.outstring(MOS->sectname, 16);
551 FHOut.outstring(MOS->segname, 16);
552 FHOut.outaddr(MOS->addr);
553 FHOut.outaddr(MOS->size);
554 FHOut.outword(MOS->offset);
555 FHOut.outword(MOS->align);
556 FHOut.outword(MOS->reloff);
557 FHOut.outword(MOS->nreloc);
558 FHOut.outword(MOS->flags);
559 FHOut.outword(MOS->reserved1);
560 FHOut.outword(MOS->reserved2);
Nate Begemaneb883af2006-08-23 21:08:52 +0000561 if (is64Bit)
Bill Wendling203d3e42007-01-17 22:22:31 +0000562 FHOut.outword(MOS->reserved3);
Nate Begemaneb883af2006-08-23 21:08:52 +0000563 }
564
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000565 // Step #8: Emit LC_SYMTAB/LC_DYSYMTAB load commands
Nate Begeman94be2482006-09-08 22:42:09 +0000566 SymTab.symoff = currentAddr;
Nate Begemaneb883af2006-08-23 21:08:52 +0000567 SymTab.nsyms = SymbolTable.size();
Nate Begemand2030e62006-08-26 15:46:34 +0000568 SymTab.stroff = SymTab.symoff + SymT.size();
569 SymTab.strsize = StrT.size();
Bill Wendling203d3e42007-01-17 22:22:31 +0000570 FHOut.outword(SymTab.cmd);
571 FHOut.outword(SymTab.cmdsize);
572 FHOut.outword(SymTab.symoff);
573 FHOut.outword(SymTab.nsyms);
574 FHOut.outword(SymTab.stroff);
575 FHOut.outword(SymTab.strsize);
Nate Begemaneb883af2006-08-23 21:08:52 +0000576
577 // FIXME: set DySymTab fields appropriately
Nate Begemand2030e62006-08-26 15:46:34 +0000578 // We should probably just update these in BufferSymbolAndStringTable since
579 // thats where we're partitioning up the different kinds of symbols.
Bill Wendling203d3e42007-01-17 22:22:31 +0000580 FHOut.outword(DySymTab.cmd);
581 FHOut.outword(DySymTab.cmdsize);
582 FHOut.outword(DySymTab.ilocalsym);
583 FHOut.outword(DySymTab.nlocalsym);
584 FHOut.outword(DySymTab.iextdefsym);
585 FHOut.outword(DySymTab.nextdefsym);
586 FHOut.outword(DySymTab.iundefsym);
587 FHOut.outword(DySymTab.nundefsym);
588 FHOut.outword(DySymTab.tocoff);
589 FHOut.outword(DySymTab.ntoc);
590 FHOut.outword(DySymTab.modtaboff);
591 FHOut.outword(DySymTab.nmodtab);
592 FHOut.outword(DySymTab.extrefsymoff);
593 FHOut.outword(DySymTab.nextrefsyms);
594 FHOut.outword(DySymTab.indirectsymoff);
595 FHOut.outword(DySymTab.nindirectsyms);
596 FHOut.outword(DySymTab.extreloff);
597 FHOut.outword(DySymTab.nextrel);
598 FHOut.outword(DySymTab.locreloff);
599 FHOut.outword(DySymTab.nlocrel);
Nate Begemaneb883af2006-08-23 21:08:52 +0000600
601 O.write((char*)&FH[0], FH.size());
602}
603
604/// EmitSections - Now that we have constructed the file header and load
605/// commands, emit the data for each section to the file.
606void MachOWriter::EmitSections() {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000607 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman019f8512006-09-10 23:03:44 +0000608 E = SectionList.end(); I != E; ++I)
609 // Emit the contents of each section
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000610 O.write((char*)&(*I)->SectionData[0], (*I)->size);
611 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman019f8512006-09-10 23:03:44 +0000612 E = SectionList.end(); I != E; ++I)
613 // Emit the relocation entry data for each section.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000614 O.write((char*)&(*I)->RelocBuffer[0], (*I)->RelocBuffer.size());
Nate Begemaneb883af2006-08-23 21:08:52 +0000615}
616
Nate Begemand2030e62006-08-26 15:46:34 +0000617/// PartitionByLocal - Simple boolean predicate that returns true if Sym is
618/// a local symbol rather than an external symbol.
619bool MachOWriter::PartitionByLocal(const MachOSym &Sym) {
Nate Begemand2030e62006-08-26 15:46:34 +0000620 return (Sym.n_type & (MachOSym::N_EXT | MachOSym::N_PEXT)) == 0;
Nate Begemaneb883af2006-08-23 21:08:52 +0000621}
622
Nate Begemand2030e62006-08-26 15:46:34 +0000623/// PartitionByDefined - Simple boolean predicate that returns true if Sym is
624/// defined in this module.
625bool MachOWriter::PartitionByDefined(const MachOSym &Sym) {
626 // FIXME: Do N_ABS or N_INDR count as defined?
627 return (Sym.n_type & MachOSym::N_SECT) == MachOSym::N_SECT;
628}
Nate Begemaneb883af2006-08-23 21:08:52 +0000629
Nate Begemand2030e62006-08-26 15:46:34 +0000630/// BufferSymbolAndStringTable - Sort the symbols we encountered and assign them
631/// each a string table index so that they appear in the correct order in the
632/// output file.
633void MachOWriter::BufferSymbolAndStringTable() {
634 // The order of the symbol table is:
635 // 1. local symbols
636 // 2. defined external symbols (sorted by name)
637 // 3. undefined external symbols (sorted by name)
638
Nate Begemanfec910c2007-02-28 07:40:50 +0000639 // Before sorting the symbols, check the PendingGlobals for any undefined
640 // globals that need to be put in the symbol table.
641 for (std::vector<GlobalValue*>::iterator I = PendingGlobals.begin(),
642 E = PendingGlobals.end(); I != E; ++I) {
643 if (GVOffset[*I] == 0 && GVSection[*I] == 0) {
644 MachOSym UndfSym(*I, Mang->getValueName(*I), MachOSym::NO_SECT, TM);
645 SymbolTable.push_back(UndfSym);
646 GVOffset[*I] = -1;
647 }
648 }
649
Nate Begemand2030e62006-08-26 15:46:34 +0000650 // Sort the symbols by name, so that when we partition the symbols by scope
651 // of definition, we won't have to sort by name within each partition.
652 std::sort(SymbolTable.begin(), SymbolTable.end(), MachOSymCmp());
653
654 // Parition the symbol table entries so that all local symbols come before
655 // all symbols with external linkage. { 1 | 2 3 }
656 std::partition(SymbolTable.begin(), SymbolTable.end(), PartitionByLocal);
657
658 // Advance iterator to beginning of external symbols and partition so that
659 // all external symbols defined in this module come before all external
660 // symbols defined elsewhere. { 1 | 2 | 3 }
661 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
662 E = SymbolTable.end(); I != E; ++I) {
663 if (!PartitionByLocal(*I)) {
664 std::partition(I, E, PartitionByDefined);
665 break;
666 }
667 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000668
669 // Calculate the starting index for each of the local, extern defined, and
670 // undefined symbols, as well as the number of each to put in the LC_DYSYMTAB
671 // load command.
672 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
673 E = SymbolTable.end(); I != E; ++I) {
674 if (PartitionByLocal(*I)) {
675 ++DySymTab.nlocalsym;
676 ++DySymTab.iextdefsym;
Nate Begeman6635f352007-01-26 22:39:48 +0000677 ++DySymTab.iundefsym;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000678 } else if (PartitionByDefined(*I)) {
679 ++DySymTab.nextdefsym;
680 ++DySymTab.iundefsym;
681 } else {
682 ++DySymTab.nundefsym;
683 }
684 }
Nate Begemand2030e62006-08-26 15:46:34 +0000685
Nate Begemaneb883af2006-08-23 21:08:52 +0000686 // Write out a leading zero byte when emitting string table, for n_strx == 0
687 // which means an empty string.
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000688 OutputBuffer StrTOut(StrT, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000689 StrTOut.outbyte(0);
Nate Begemaneb883af2006-08-23 21:08:52 +0000690
Nate Begemand2030e62006-08-26 15:46:34 +0000691 // The order of the string table is:
692 // 1. strings for external symbols
693 // 2. strings for local symbols
694 // Since this is the opposite order from the symbol table, which we have just
695 // sorted, we can walk the symbol table backwards to output the string table.
696 for (std::vector<MachOSym>::reverse_iterator I = SymbolTable.rbegin(),
697 E = SymbolTable.rend(); I != E; ++I) {
698 if (I->GVName == "") {
699 I->n_strx = 0;
700 } else {
701 I->n_strx = StrT.size();
Bill Wendling203d3e42007-01-17 22:22:31 +0000702 StrTOut.outstring(I->GVName, I->GVName.length()+1);
Nate Begemand2030e62006-08-26 15:46:34 +0000703 }
Nate Begemaneb883af2006-08-23 21:08:52 +0000704 }
Nate Begemand2030e62006-08-26 15:46:34 +0000705
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000706 OutputBuffer SymTOut(SymT, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000707
Nate Begemanfec910c2007-02-28 07:40:50 +0000708 unsigned index = 0;
Nate Begemand2030e62006-08-26 15:46:34 +0000709 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
Nate Begemanfec910c2007-02-28 07:40:50 +0000710 E = SymbolTable.end(); I != E; ++I, ++index) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000711 // Add the section base address to the section offset in the n_value field
712 // to calculate the full address.
713 // FIXME: handle symbols where the n_value field is not the address
714 GlobalValue *GV = const_cast<GlobalValue*>(I->GV);
715 if (GV && GVSection[GV])
716 I->n_value += GVSection[GV]->addr;
Nate Begemanfec910c2007-02-28 07:40:50 +0000717 if (GV && (GVOffset[GV] == -1))
718 GVOffset[GV] = index;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000719
Nate Begemand2030e62006-08-26 15:46:34 +0000720 // Emit nlist to buffer
Bill Wendling203d3e42007-01-17 22:22:31 +0000721 SymTOut.outword(I->n_strx);
722 SymTOut.outbyte(I->n_type);
723 SymTOut.outbyte(I->n_sect);
724 SymTOut.outhalf(I->n_desc);
725 SymTOut.outaddr(I->n_value);
Nate Begemand2030e62006-08-26 15:46:34 +0000726 }
Nate Begemaneb883af2006-08-23 21:08:52 +0000727}
Nate Begeman94be2482006-09-08 22:42:09 +0000728
Nate Begeman019f8512006-09-10 23:03:44 +0000729/// CalculateRelocations - For each MachineRelocation in the current section,
730/// calculate the index of the section containing the object to be relocated,
731/// and the offset into that section. From this information, create the
732/// appropriate target-specific MachORelocation type and add buffer it to be
733/// written out after we are finished writing out sections.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000734void MachOWriter::CalculateRelocations(MachOSection &MOS) {
Nate Begeman019f8512006-09-10 23:03:44 +0000735 for (unsigned i = 0, e = MOS.Relocations.size(); i != e; ++i) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000736 MachineRelocation &MR = MOS.Relocations[i];
737 unsigned TargetSection = MR.getConstantVal();
Nate Begemanaf806382007-03-03 06:18:18 +0000738 unsigned TargetAddr = 0;
739 unsigned TargetIndex = 0;
Nate Begeman6635f352007-01-26 22:39:48 +0000740
741 // This is a scattered relocation entry if it points to a global value with
742 // a non-zero offset.
743 bool Scattered = false;
Nate Begemanfec910c2007-02-28 07:40:50 +0000744 bool Extern = false;
Nate Begemanaf806382007-03-03 06:18:18 +0000745
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000746 // Since we may not have seen the GlobalValue we were interested in yet at
747 // the time we emitted the relocation for it, fix it up now so that it
748 // points to the offset into the correct section.
749 if (MR.isGlobalValue()) {
750 GlobalValue *GV = MR.getGlobalValue();
751 MachOSection *MOSPtr = GVSection[GV];
Nate Begeman6635f352007-01-26 22:39:48 +0000752 intptr_t Offset = GVOffset[GV];
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000753
Nate Begemanfec910c2007-02-28 07:40:50 +0000754 // If we have never seen the global before, it must be to a symbol
755 // defined in another module (N_UNDF).
Nate Begeman1257c852007-01-29 21:20:42 +0000756 if (!MOSPtr) {
Nate Begemanfec910c2007-02-28 07:40:50 +0000757 // FIXME: need to append stub suffix
758 Extern = true;
759 TargetAddr = 0;
760 TargetIndex = GVOffset[GV];
761 } else {
762 Scattered = TargetSection != 0;
763 TargetSection = MOSPtr->Index;
Nate Begemanaf806382007-03-03 06:18:18 +0000764 }
765 MR.setResultPointer((void*)Offset);
766 }
767
768 // If the symbol is locally defined, pass in the address of the section and
769 // the section index to the code which will generate the target relocation.
770 if (!Extern) {
Nate Begemanfec910c2007-02-28 07:40:50 +0000771 MachOSection &To = *SectionList[TargetSection - 1];
772 TargetAddr = To.addr;
773 TargetIndex = To.Index;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000774 }
Bill Wendling886b4122007-02-03 02:39:40 +0000775
776 OutputBuffer RelocOut(MOS.RelocBuffer, is64Bit, isLittleEndian);
777 OutputBuffer SecOut(MOS.SectionData, is64Bit, isLittleEndian);
Nate Begemanfec910c2007-02-28 07:40:50 +0000778
779 MOS.nreloc += GetTargetRelocation(MR, MOS.Index, TargetAddr, TargetIndex,
780 RelocOut, SecOut, Scattered, Extern);
Nate Begeman019f8512006-09-10 23:03:44 +0000781 }
Nate Begeman019f8512006-09-10 23:03:44 +0000782}
783
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000784// InitMem - Write the value of a Constant to the specified memory location,
785// converting it into bytes and relocations.
786void MachOWriter::InitMem(const Constant *C, void *Addr, intptr_t Offset,
787 const TargetData *TD,
788 std::vector<MachineRelocation> &MRs) {
789 typedef std::pair<const Constant*, intptr_t> CPair;
790 std::vector<CPair> WorkList;
791
792 WorkList.push_back(CPair(C,(intptr_t)Addr + Offset));
793
Nate Begeman6635f352007-01-26 22:39:48 +0000794 intptr_t ScatteredOffset = 0;
795
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000796 while (!WorkList.empty()) {
797 const Constant *PC = WorkList.back().first;
798 intptr_t PA = WorkList.back().second;
799 WorkList.pop_back();
800
801 if (isa<UndefValue>(PC)) {
802 continue;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000803 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(PC)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000804 unsigned ElementSize = TD->getTypeSize(CP->getType()->getElementType());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000805 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
806 WorkList.push_back(CPair(CP->getOperand(i), PA+i*ElementSize));
807 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(PC)) {
808 //
809 // FIXME: Handle ConstantExpression. See EE::getConstantValue()
810 //
811 switch (CE->getOpcode()) {
Nate Begeman6635f352007-01-26 22:39:48 +0000812 case Instruction::GetElementPtr: {
Chris Lattner7f6b9d22007-02-10 20:31:59 +0000813 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Nate Begeman6635f352007-01-26 22:39:48 +0000814 ScatteredOffset = TD->getIndexedOffset(CE->getOperand(0)->getType(),
Chris Lattner7f6b9d22007-02-10 20:31:59 +0000815 &Indices[0], Indices.size());
Nate Begeman6635f352007-01-26 22:39:48 +0000816 WorkList.push_back(CPair(CE->getOperand(0), PA));
817 break;
818 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000819 case Instruction::Add:
820 default:
821 cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
822 abort();
823 break;
824 }
825 } else if (PC->getType()->isFirstClassType()) {
826 unsigned char *ptr = (unsigned char *)PA;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000827 switch (PC->getType()->getTypeID()) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000828 case Type::IntegerTyID: {
829 unsigned NumBits = cast<IntegerType>(PC->getType())->getBitWidth();
830 uint64_t val = cast<ConstantInt>(PC)->getZExtValue();
831 if (NumBits <= 8)
832 ptr[0] = val;
833 else if (NumBits <= 16) {
834 if (TD->isBigEndian())
835 val = ByteSwap_16(val);
836 ptr[0] = val;
837 ptr[1] = val >> 8;
838 } else if (NumBits <= 32) {
839 if (TD->isBigEndian())
840 val = ByteSwap_32(val);
841 ptr[0] = val;
842 ptr[1] = val >> 8;
843 ptr[2] = val >> 16;
844 ptr[3] = val >> 24;
845 } else if (NumBits <= 64) {
846 if (TD->isBigEndian())
847 val = ByteSwap_64(val);
848 ptr[0] = val;
849 ptr[1] = val >> 8;
850 ptr[2] = val >> 16;
851 ptr[3] = val >> 24;
852 ptr[4] = val >> 32;
853 ptr[5] = val >> 40;
854 ptr[6] = val >> 48;
855 ptr[7] = val >> 56;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000856 } else {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000857 assert(0 && "Not implemented: bit widths > 64");
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000858 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000859 break;
860 }
861 case Type::FloatTyID: {
862 uint64_t val = FloatToBits(cast<ConstantFP>(PC)->getValue());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000863 if (TD->isBigEndian())
864 val = ByteSwap_32(val);
865 ptr[0] = val;
866 ptr[1] = val >> 8;
867 ptr[2] = val >> 16;
868 ptr[3] = val >> 24;
869 break;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000870 }
871 case Type::DoubleTyID: {
872 uint64_t val = DoubleToBits(cast<ConstantFP>(PC)->getValue());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000873 if (TD->isBigEndian())
874 val = ByteSwap_64(val);
875 ptr[0] = val;
876 ptr[1] = val >> 8;
877 ptr[2] = val >> 16;
878 ptr[3] = val >> 24;
879 ptr[4] = val >> 32;
880 ptr[5] = val >> 40;
881 ptr[6] = val >> 48;
882 ptr[7] = val >> 56;
883 break;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000884 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000885 case Type::PointerTyID:
Nate Begeman6635f352007-01-26 22:39:48 +0000886 if (isa<ConstantPointerNull>(PC))
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000887 memset(ptr, 0, TD->getPointerSize());
Nate Begeman6635f352007-01-26 22:39:48 +0000888 else if (const GlobalValue* GV = dyn_cast<GlobalValue>(PC)) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000889 // FIXME: what about function stubs?
890 MRs.push_back(MachineRelocation::getGV(PA-(intptr_t)Addr,
891 MachineRelocation::VANILLA,
Nate Begeman6635f352007-01-26 22:39:48 +0000892 const_cast<GlobalValue*>(GV),
893 ScatteredOffset));
894 ScatteredOffset = 0;
895 } else
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000896 assert(0 && "Unknown constant pointer type!");
897 break;
898 default:
899 cerr << "ERROR: Constant unimp for type: " << *PC->getType() << "\n";
900 abort();
901 }
902 } else if (isa<ConstantAggregateZero>(PC)) {
903 memset((void*)PA, 0, (size_t)TD->getTypeSize(PC->getType()));
904 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(PC)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000905 unsigned ElementSize = TD->getTypeSize(CPA->getType()->getElementType());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000906 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
907 WorkList.push_back(CPair(CPA->getOperand(i), PA+i*ElementSize));
908 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(PC)) {
909 const StructLayout *SL =
910 TD->getStructLayout(cast<StructType>(CPS->getType()));
911 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
Chris Lattnerb1919e22007-02-10 19:55:17 +0000912 WorkList.push_back(CPair(CPS->getOperand(i),
913 PA+SL->getElementOffset(i)));
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000914 } else {
915 cerr << "Bad Type: " << *PC->getType() << "\n";
916 assert(0 && "Unknown constant type to initialize memory with!");
917 }
918 }
919}
920
921MachOSym::MachOSym(const GlobalValue *gv, std::string name, uint8_t sect,
922 TargetMachine &TM) :
923 GV(gv), n_strx(0), n_type(sect == NO_SECT ? N_UNDF : N_SECT), n_sect(sect),
924 n_desc(0), n_value(0) {
925
926 const TargetAsmInfo *TAI = TM.getTargetAsmInfo();
927
Nate Begeman94be2482006-09-08 22:42:09 +0000928 switch (GV->getLinkage()) {
929 default:
930 assert(0 && "Unexpected linkage type!");
931 break;
932 case GlobalValue::WeakLinkage:
933 case GlobalValue::LinkOnceLinkage:
934 assert(!isa<Function>(gv) && "Unexpected linkage type for Function!");
935 case GlobalValue::ExternalLinkage:
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000936 GVName = TAI->getGlobalPrefix() + name;
Nate Begeman6635f352007-01-26 22:39:48 +0000937 n_type |= GV->hasHiddenVisibility() ? N_PEXT : N_EXT;
Nate Begeman94be2482006-09-08 22:42:09 +0000938 break;
939 case GlobalValue::InternalLinkage:
Nate Begeman6635f352007-01-26 22:39:48 +0000940 GVName = TAI->getGlobalPrefix() + name;
Nate Begeman94be2482006-09-08 22:42:09 +0000941 break;
942 }
943}