blob: f77f85e98d51f0b9eeaa6296a7eafe37a93a4b49 [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//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Nate Begemaneb883af2006-08-23 21:08:52 +00007//
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>
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +000041#include <cstring>
Nate Begemaneb883af2006-08-23 21:08:52 +000042using namespace llvm;
43
Bill Wendling8f84f1f2007-02-08 01:35:27 +000044/// AddMachOWriter - Concrete function to add the Mach-O writer to the function
45/// pass manager.
Dan Gohmanbfae8312008-03-11 22:29:46 +000046MachineCodeEmitter *llvm::AddMachOWriter(PassManagerBase &PM,
Bill Wendling8f84f1f2007-02-08 01:35:27 +000047 std::ostream &O,
48 TargetMachine &TM) {
49 MachOWriter *MOW = new MachOWriter(O, TM);
Dan Gohmanbfae8312008-03-11 22:29:46 +000050 PM.add(MOW);
Bill Wendling8f84f1f2007-02-08 01:35:27 +000051 return &MOW->getMachineCodeEmitter();
52}
53
Nate Begemaneb883af2006-08-23 21:08:52 +000054//===----------------------------------------------------------------------===//
55// MachOCodeEmitter Implementation
56//===----------------------------------------------------------------------===//
57
58namespace llvm {
59 /// MachOCodeEmitter - This class is used by the MachOWriter to emit the code
60 /// for functions to the Mach-O file.
61 class MachOCodeEmitter : public MachineCodeEmitter {
62 MachOWriter &MOW;
Nate Begemaneb883af2006-08-23 21:08:52 +000063
Bill Wendling203d3e42007-01-17 22:22:31 +000064 /// Target machine description.
65 TargetMachine &TM;
66
Bill Wendlingc904a5b2007-01-18 01:23:11 +000067 /// is64Bit/isLittleEndian - This information is inferred from the target
68 /// machine directly, indicating what header values and flags to set.
69 bool is64Bit, isLittleEndian;
70
Nate Begemaneb883af2006-08-23 21:08:52 +000071 /// Relocations - These are the relocations that the function needs, as
72 /// emitted.
73 std::vector<MachineRelocation> Relocations;
Nate Begeman019f8512006-09-10 23:03:44 +000074
75 /// CPLocations - This is a map of constant pool indices to offsets from the
76 /// start of the section for that constant pool index.
77 std::vector<intptr_t> CPLocations;
78
Nate Begemanbfaaaa62006-12-11 02:20:45 +000079 /// CPSections - This is a map of constant pool indices to the MachOSection
80 /// containing the constant pool entry for that index.
81 std::vector<unsigned> CPSections;
82
Nate Begeman019f8512006-09-10 23:03:44 +000083 /// JTLocations - This is a map of jump table indices to offsets from the
84 /// start of the section for that jump table index.
85 std::vector<intptr_t> JTLocations;
Nate Begemaneb883af2006-08-23 21:08:52 +000086
87 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
88 /// It is filled in by the StartMachineBasicBlock callback and queried by
89 /// the getMachineBasicBlockAddress callback.
90 std::vector<intptr_t> MBBLocations;
91
92 public:
Bill Wendlingc904a5b2007-01-18 01:23:11 +000093 MachOCodeEmitter(MachOWriter &mow) : MOW(mow), TM(MOW.TM) {
94 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
95 isLittleEndian = TM.getTargetData()->isLittleEndian();
96 }
Nate Begemaneb883af2006-08-23 21:08:52 +000097
Nate Begemanc2b2d6a2007-02-07 05:47:16 +000098 virtual void startFunction(MachineFunction &MF);
99 virtual bool finishFunction(MachineFunction &MF);
Nate Begemaneb883af2006-08-23 21:08:52 +0000100
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000101 virtual void addRelocation(const MachineRelocation &MR) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000102 Relocations.push_back(MR);
103 }
104
Nate Begeman019f8512006-09-10 23:03:44 +0000105 void emitConstantPool(MachineConstantPool *MCP);
106 void emitJumpTables(MachineJumpTableInfo *MJTI);
107
Nate Begemaneb883af2006-08-23 21:08:52 +0000108 virtual intptr_t getConstantPoolEntryAddress(unsigned Index) const {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000109 assert(CPLocations.size() > Index && "CP not emitted!");
Nate Begemana0a62782007-02-28 09:16:38 +0000110 return CPLocations[Index];
Nate Begemaneb883af2006-08-23 21:08:52 +0000111 }
112 virtual intptr_t getJumpTableEntryAddress(unsigned Index) const {
Nate Begeman019f8512006-09-10 23:03:44 +0000113 assert(JTLocations.size() > Index && "JT not emitted!");
114 return JTLocations[Index];
115 }
116
117 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
118 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
119 MBBLocations.resize((MBB->getNumber()+1)*2);
120 MBBLocations[MBB->getNumber()] = getCurrentPCOffset();
Nate Begemaneb883af2006-08-23 21:08:52 +0000121 }
122
123 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
124 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
125 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
126 return MBBLocations[MBB->getNumber()];
127 }
128
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000129 virtual intptr_t getLabelAddress(uint64_t Label) const {
130 assert(0 && "get Label not implemented");
131 abort();
132 return 0;
133 }
134
135 virtual void emitLabel(uint64_t LabelID) {
136 assert(0 && "emit Label not implemented");
137 abort();
138 }
139
140
141 virtual void setModuleInfo(llvm::MachineModuleInfo* MMI) { }
142
Nate Begemaneb883af2006-08-23 21:08:52 +0000143 /// JIT SPECIFIC FUNCTIONS - DO NOT IMPLEMENT THESE HERE!
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000144 virtual void startFunctionStub(unsigned StubSize, unsigned Alignment = 1) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000145 assert(0 && "JIT specific function called!");
146 abort();
147 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000148 virtual void *finishFunctionStub(const Function *F) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000149 assert(0 && "JIT specific function called!");
150 abort();
151 return 0;
152 }
153 };
154}
155
156/// startFunction - This callback is invoked when a new machine function is
157/// about to be emitted.
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000158void MachOCodeEmitter::startFunction(MachineFunction &MF) {
159 const TargetData *TD = TM.getTargetData();
160 const Function *F = MF.getFunction();
161
Nate Begemaneb883af2006-08-23 21:08:52 +0000162 // Align the output buffer to the appropriate alignment, power of 2.
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000163 unsigned FnAlign = F->getAlignment();
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000164 unsigned TDAlign = TD->getPrefTypeAlignment(F->getType());
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000165 unsigned Align = Log2_32(std::max(FnAlign, TDAlign));
166 assert(!(Align & (Align-1)) && "Alignment is not a power of two!");
Nate Begemaneb883af2006-08-23 21:08:52 +0000167
168 // Get the Mach-O Section that this function belongs in.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000169 MachOWriter::MachOSection *MOS = MOW.getTextSection();
Nate Begemaneb883af2006-08-23 21:08:52 +0000170
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000171 // FIXME: better memory management
Nate Begemaneb883af2006-08-23 21:08:52 +0000172 MOS->SectionData.reserve(4096);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000173 BufferBegin = &MOS->SectionData[0];
Nate Begemaneb883af2006-08-23 21:08:52 +0000174 BufferEnd = BufferBegin + MOS->SectionData.capacity();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000175
Nate Begeman6635f352007-01-26 22:39:48 +0000176 // Upgrade the section alignment if required.
177 if (MOS->align < Align) MOS->align = Align;
178
179 // Round the size up to the correct alignment for starting the new function.
180 if ((MOS->size & ((1 << Align) - 1)) != 0) {
181 MOS->size += (1 << Align);
182 MOS->size &= ~((1 << Align) - 1);
183 }
184
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000185 // FIXME: Using MOS->size directly here instead of calculating it from the
186 // output buffer size (impossible because the code emitter deals only in raw
187 // bytes) forces us to manually synchronize size and write padding zero bytes
188 // to the output buffer for all non-text sections. For text sections, we do
189 // not synchonize the output buffer, and we just blow up if anyone tries to
190 // write non-code to it. An assert should probably be added to
191 // AddSymbolToSection to prevent calling it on the text section.
Nate Begemaneb883af2006-08-23 21:08:52 +0000192 CurBufferPtr = BufferBegin + MOS->size;
193
Nate Begeman019f8512006-09-10 23:03:44 +0000194 // Clear per-function data structures.
195 CPLocations.clear();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000196 CPSections.clear();
Nate Begeman019f8512006-09-10 23:03:44 +0000197 JTLocations.clear();
Nate Begemaneb883af2006-08-23 21:08:52 +0000198 MBBLocations.clear();
199}
200
201/// finishFunction - This callback is invoked after the function is completely
202/// finished.
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000203bool MachOCodeEmitter::finishFunction(MachineFunction &MF) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000204 // Get the Mach-O Section that this function belongs in.
205 MachOWriter::MachOSection *MOS = MOW.getTextSection();
206
Nate Begemaneb883af2006-08-23 21:08:52 +0000207 // Get a symbol for the function to add to the symbol table
Nate Begeman6635f352007-01-26 22:39:48 +0000208 // FIXME: it seems like we should call something like AddSymbolToSection
209 // in startFunction rather than changing the section size and symbol n_value
210 // here.
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000211 const GlobalValue *FuncV = MF.getFunction();
Bill Wendling203d3e42007-01-17 22:22:31 +0000212 MachOSym FnSym(FuncV, MOW.Mang->getValueName(FuncV), MOS->Index, TM);
Nate Begeman6635f352007-01-26 22:39:48 +0000213 FnSym.n_value = MOS->size;
214 MOS->size = CurBufferPtr - BufferBegin;
215
Nate Begeman019f8512006-09-10 23:03:44 +0000216 // Emit constant pool to appropriate section(s)
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000217 emitConstantPool(MF.getConstantPool());
Nate Begeman019f8512006-09-10 23:03:44 +0000218
219 // Emit jump tables to appropriate section
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000220 emitJumpTables(MF.getJumpTableInfo());
Nate Begemaneb883af2006-08-23 21:08:52 +0000221
Nate Begeman019f8512006-09-10 23:03:44 +0000222 // If we have emitted any relocations to function-specific objects such as
223 // basic blocks, constant pools entries, or jump tables, record their
224 // addresses now so that we can rewrite them with the correct addresses
225 // later.
Nate Begemaneb883af2006-08-23 21:08:52 +0000226 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
227 MachineRelocation &MR = Relocations[i];
Nate Begeman019f8512006-09-10 23:03:44 +0000228 intptr_t Addr;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000229
Nate Begemaneb883af2006-08-23 21:08:52 +0000230 if (MR.isBasicBlock()) {
Nate Begeman019f8512006-09-10 23:03:44 +0000231 Addr = getMachineBasicBlockAddress(MR.getBasicBlock());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000232 MR.setConstantVal(MOS->Index);
233 MR.setResultPointer((void*)Addr);
234 } else if (MR.isJumpTableIndex()) {
235 Addr = getJumpTableEntryAddress(MR.getJumpTableIndex());
236 MR.setConstantVal(MOW.getJumpTableSection()->Index);
237 MR.setResultPointer((void*)Addr);
Nate Begeman019f8512006-09-10 23:03:44 +0000238 } else if (MR.isConstantPoolIndex()) {
239 Addr = getConstantPoolEntryAddress(MR.getConstantPoolIndex());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000240 MR.setConstantVal(CPSections[MR.getConstantPoolIndex()]);
241 MR.setResultPointer((void*)Addr);
Nate Begemanfec910c2007-02-28 07:40:50 +0000242 } else if (MR.isGlobalValue()) {
243 // FIXME: This should be a set or something that uniques
244 MOW.PendingGlobals.push_back(MR.getGlobalValue());
245 } else {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000246 assert(0 && "Unhandled relocation type");
Nate Begemaneb883af2006-08-23 21:08:52 +0000247 }
Nate Begeman019f8512006-09-10 23:03:44 +0000248 MOS->Relocations.push_back(MR);
Nate Begemaneb883af2006-08-23 21:08:52 +0000249 }
250 Relocations.clear();
251
252 // Finally, add it to the symtab.
253 MOW.SymbolTable.push_back(FnSym);
254 return false;
255}
256
Nate Begeman019f8512006-09-10 23:03:44 +0000257/// emitConstantPool - For each constant pool entry, figure out which section
258/// the constant should live in, allocate space for it, and emit it to the
259/// Section data buffer.
260void MachOCodeEmitter::emitConstantPool(MachineConstantPool *MCP) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000261 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
262 if (CP.empty()) return;
263
264 // FIXME: handle PIC codegen
Bill Wendling203d3e42007-01-17 22:22:31 +0000265 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000266 assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
267
268 // Although there is no strict necessity that I am aware of, we will do what
269 // gcc for OS X does and put each constant pool entry in a section of constant
270 // objects of a certain size. That means that float constants go in the
271 // literal4 section, and double objects go in literal8, etc.
272 //
273 // FIXME: revisit this decision if we ever do the "stick everything into one
274 // "giant object for PIC" optimization.
275 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
276 const Type *Ty = CP[i].getType();
Duncan Sandsca0ed742007-11-05 00:04:43 +0000277 unsigned Size = TM.getTargetData()->getABITypeSize(Ty);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000278
Nate Begeman1257c852007-01-29 21:20:42 +0000279 MachOWriter::MachOSection *Sec = MOW.getConstSection(CP[i].Val.ConstVal);
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000280 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000281
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000282 CPLocations.push_back(Sec->SectionData.size());
283 CPSections.push_back(Sec->Index);
284
285 // FIXME: remove when we have unified size + output buffer
286 Sec->size += Size;
287
288 // Allocate space in the section for the global.
289 // FIXME: need alignment?
290 // FIXME: share between here and AddSymbolToSection?
291 for (unsigned j = 0; j < Size; ++j)
Bill Wendling203d3e42007-01-17 22:22:31 +0000292 SecDataOut.outbyte(0);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000293
294 MOW.InitMem(CP[i].Val.ConstVal, &Sec->SectionData[0], CPLocations[i],
Bill Wendling203d3e42007-01-17 22:22:31 +0000295 TM.getTargetData(), Sec->Relocations);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000296 }
Nate Begeman019f8512006-09-10 23:03:44 +0000297}
298
299/// emitJumpTables - Emit all the jump tables for a given jump table info
300/// record to the appropriate section.
301void MachOCodeEmitter::emitJumpTables(MachineJumpTableInfo *MJTI) {
302 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
303 if (JT.empty()) return;
304
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000305 // FIXME: handle PIC codegen
Bill Wendling203d3e42007-01-17 22:22:31 +0000306 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
Nate Begeman019f8512006-09-10 23:03:44 +0000307 assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
308
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000309 MachOWriter::MachOSection *Sec = MOW.getJumpTableSection();
310 unsigned TextSecIndex = MOW.getTextSection()->Index;
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000311 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
Nate Begeman019f8512006-09-10 23:03:44 +0000312
313 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
314 // For each jump table, record its offset from the start of the section,
315 // reserve space for the relocations to the MBBs, and add the relocations.
316 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000317 JTLocations.push_back(Sec->SectionData.size());
Nate Begeman019f8512006-09-10 23:03:44 +0000318 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000319 MachineRelocation MR(MOW.GetJTRelocation(Sec->SectionData.size(),
Nate Begeman019f8512006-09-10 23:03:44 +0000320 MBBs[mi]));
321 MR.setResultPointer((void *)JTLocations[i]);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000322 MR.setConstantVal(TextSecIndex);
323 Sec->Relocations.push_back(MR);
Bill Wendling203d3e42007-01-17 22:22:31 +0000324 SecDataOut.outaddr(0);
Nate Begeman019f8512006-09-10 23:03:44 +0000325 }
326 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000327 // FIXME: remove when we have unified size + output buffer
328 Sec->size = Sec->SectionData.size();
Nate Begeman019f8512006-09-10 23:03:44 +0000329}
330
Nate Begemaneb883af2006-08-23 21:08:52 +0000331//===----------------------------------------------------------------------===//
332// MachOWriter Implementation
333//===----------------------------------------------------------------------===//
334
Devang Patel19974732007-05-03 01:11:54 +0000335char MachOWriter::ID = 0;
Devang Patel794fd752007-05-01 21:15:47 +0000336MachOWriter::MachOWriter(std::ostream &o, TargetMachine &tm)
337 : MachineFunctionPass((intptr_t)&ID), O(o), TM(tm) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000338 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
339 isLittleEndian = TM.getTargetData()->isLittleEndian();
340
341 // Create the machine code emitter object for this target.
Bill Wendlinge9116152007-01-17 09:06:13 +0000342 MCE = new MachOCodeEmitter(*this);
Nate Begemaneb883af2006-08-23 21:08:52 +0000343}
344
345MachOWriter::~MachOWriter() {
346 delete MCE;
347}
348
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000349void MachOWriter::AddSymbolToSection(MachOSection *Sec, GlobalVariable *GV) {
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000350 const Type *Ty = GV->getType()->getElementType();
Duncan Sandsca0ed742007-11-05 00:04:43 +0000351 unsigned Size = TM.getTargetData()->getABITypeSize(Ty);
Duncan Sandsd1025932008-01-29 06:23:44 +0000352 unsigned Align = TM.getTargetData()->getPreferredAlignment(GV);
353
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000354 // Reserve space in the .bss section for this symbol while maintaining the
355 // desired section alignment, which must be at least as much as required by
356 // this symbol.
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000357 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000358
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000359 if (Align) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000360 uint64_t OrigSize = Sec->size;
361 Align = Log2_32(Align);
362 Sec->align = std::max(unsigned(Sec->align), Align);
363 Sec->size = (Sec->size + Align - 1) & ~(Align-1);
364
365 // Add alignment padding to buffer as well.
366 // FIXME: remove when we have unified size + output buffer
367 unsigned AlignedSize = Sec->size - OrigSize;
368 for (unsigned i = 0; i < AlignedSize; ++i)
Bill Wendling203d3e42007-01-17 22:22:31 +0000369 SecDataOut.outbyte(0);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000370 }
Nate Begemanfec910c2007-02-28 07:40:50 +0000371 // Globals without external linkage apparently do not go in the symbol table.
372 if (GV->getLinkage() != GlobalValue::InternalLinkage) {
373 MachOSym Sym(GV, Mang->getValueName(GV), Sec->Index, TM);
374 Sym.n_value = Sec->size;
375 SymbolTable.push_back(Sym);
376 }
377
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000378 // Record the offset of the symbol, and then allocate space for it.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000379 // FIXME: remove when we have unified size + output buffer
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000380 Sec->size += Size;
Nate Begemanfec910c2007-02-28 07:40:50 +0000381
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000382 // Now that we know what section the GlovalVariable is going to be emitted
383 // into, update our mappings.
384 // FIXME: We may also need to update this when outputting non-GlobalVariable
385 // GlobalValues such as functions.
386 GVSection[GV] = Sec;
387 GVOffset[GV] = Sec->SectionData.size();
388
389 // Allocate space in the section for the global.
390 for (unsigned i = 0; i < Size; ++i)
Bill Wendling203d3e42007-01-17 22:22:31 +0000391 SecDataOut.outbyte(0);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000392}
393
Nate Begemaneb883af2006-08-23 21:08:52 +0000394void MachOWriter::EmitGlobal(GlobalVariable *GV) {
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000395 const Type *Ty = GV->getType()->getElementType();
Duncan Sandsca0ed742007-11-05 00:04:43 +0000396 unsigned Size = TM.getTargetData()->getABITypeSize(Ty);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000397 bool NoInit = !GV->hasInitializer();
Nate Begemand2030e62006-08-26 15:46:34 +0000398
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000399 // If this global has a zero initializer, it is part of the .bss or common
400 // section.
401 if (NoInit || GV->getInitializer()->isNullValue()) {
402 // If this global is part of the common block, add it now. Variables are
403 // part of the common block if they are zero initialized and allowed to be
404 // merged with other symbols.
405 if (NoInit || GV->hasLinkOnceLinkage() || GV->hasWeakLinkage()) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000406 MachOSym ExtOrCommonSym(GV, Mang->getValueName(GV), MachOSym::NO_SECT,TM);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000407 // For undefined (N_UNDF) external (N_EXT) types, n_value is the size in
408 // bytes of the symbol.
409 ExtOrCommonSym.n_value = Size;
Nate Begemanfec910c2007-02-28 07:40:50 +0000410 SymbolTable.push_back(ExtOrCommonSym);
411 // Remember that we've seen this symbol
412 GVOffset[GV] = Size;
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000413 return;
414 }
415 // Otherwise, this symbol is part of the .bss section.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000416 MachOSection *BSS = getBSSSection();
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000417 AddSymbolToSection(BSS, GV);
418 return;
419 }
420
421 // Scalar read-only data goes in a literal section if the scalar is 4, 8, or
422 // 16 bytes, or a cstring. Other read only data goes into a regular const
423 // section. Read-write data goes in the data section.
Nate Begeman1257c852007-01-29 21:20:42 +0000424 MachOSection *Sec = GV->isConstant() ? getConstSection(GV->getInitializer()) :
425 getDataSection();
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000426 AddSymbolToSection(Sec, GV);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000427 InitMem(GV->getInitializer(), &Sec->SectionData[0], GVOffset[GV],
428 TM.getTargetData(), Sec->Relocations);
Nate Begemaneb883af2006-08-23 21:08:52 +0000429}
430
431
432bool MachOWriter::runOnMachineFunction(MachineFunction &MF) {
433 // Nothing to do here, this is all done through the MCE object.
434 return false;
435}
436
437bool MachOWriter::doInitialization(Module &M) {
438 // Set the magic value, now that we know the pointer size and endianness
439 Header.setMagic(isLittleEndian, is64Bit);
440
441 // Set the file type
442 // FIXME: this only works for object files, we do not support the creation
443 // of dynamic libraries or executables at this time.
444 Header.filetype = MachOHeader::MH_OBJECT;
445
446 Mang = new Mangler(M);
447 return false;
448}
449
450/// doFinalization - Now that the module has been completely processed, emit
451/// the Mach-O file to 'O'.
452bool MachOWriter::doFinalization(Module &M) {
Nate Begemand2030e62006-08-26 15:46:34 +0000453 // FIXME: we don't handle debug info yet, we should probably do that.
454
Nate Begemaneb883af2006-08-23 21:08:52 +0000455 // Okay, the.text section has been completed, build the .data, .bss, and
456 // "common" sections next.
457 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
458 I != E; ++I)
459 EmitGlobal(I);
460
461 // Emit the header and load commands.
462 EmitHeaderAndLoadCommands();
463
Nate Begeman019f8512006-09-10 23:03:44 +0000464 // Emit the various sections and their relocation info.
Nate Begemaneb883af2006-08-23 21:08:52 +0000465 EmitSections();
466
Nate Begemand2030e62006-08-26 15:46:34 +0000467 // Write the symbol table and the string table to the end of the file.
468 O.write((char*)&SymT[0], SymT.size());
469 O.write((char*)&StrT[0], StrT.size());
Nate Begemaneb883af2006-08-23 21:08:52 +0000470
471 // We are done with the abstract symbols.
472 SectionList.clear();
473 SymbolTable.clear();
474 DynamicSymbolTable.clear();
475
476 // Release the name mangler object.
477 delete Mang; Mang = 0;
478 return false;
479}
480
481void MachOWriter::EmitHeaderAndLoadCommands() {
482 // Step #0: Fill in the segment load command size, since we need it to figure
483 // out the rest of the header fields
484 MachOSegment SEG("", is64Bit);
485 SEG.nsects = SectionList.size();
486 SEG.cmdsize = SEG.cmdSize(is64Bit) +
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000487 SEG.nsects * SectionList[0]->cmdSize(is64Bit);
Nate Begemaneb883af2006-08-23 21:08:52 +0000488
489 // Step #1: calculate the number of load commands. We always have at least
490 // one, for the LC_SEGMENT load command, plus two for the normal
491 // and dynamic symbol tables, if there are any symbols.
492 Header.ncmds = SymbolTable.empty() ? 1 : 3;
493
494 // Step #2: calculate the size of the load commands
495 Header.sizeofcmds = SEG.cmdsize;
496 if (!SymbolTable.empty())
497 Header.sizeofcmds += SymTab.cmdsize + DySymTab.cmdsize;
498
499 // Step #3: write the header to the file
500 // Local alias to shortenify coming code.
501 DataBuffer &FH = Header.HeaderData;
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000502 OutputBuffer FHOut(FH, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000503
504 FHOut.outword(Header.magic);
Bill Wendling2b721822007-01-24 07:13:56 +0000505 FHOut.outword(TM.getMachOWriterInfo()->getCPUType());
506 FHOut.outword(TM.getMachOWriterInfo()->getCPUSubType());
Bill Wendling203d3e42007-01-17 22:22:31 +0000507 FHOut.outword(Header.filetype);
508 FHOut.outword(Header.ncmds);
509 FHOut.outword(Header.sizeofcmds);
510 FHOut.outword(Header.flags);
Nate Begemaneb883af2006-08-23 21:08:52 +0000511 if (is64Bit)
Bill Wendling203d3e42007-01-17 22:22:31 +0000512 FHOut.outword(Header.reserved);
Nate Begemaneb883af2006-08-23 21:08:52 +0000513
514 // Step #4: Finish filling in the segment load command and write it out
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000515 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begemaneb883af2006-08-23 21:08:52 +0000516 E = SectionList.end(); I != E; ++I)
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000517 SEG.filesize += (*I)->size;
518
Nate Begemaneb883af2006-08-23 21:08:52 +0000519 SEG.vmsize = SEG.filesize;
520 SEG.fileoff = Header.cmdSize(is64Bit) + Header.sizeofcmds;
521
Bill Wendling203d3e42007-01-17 22:22:31 +0000522 FHOut.outword(SEG.cmd);
523 FHOut.outword(SEG.cmdsize);
524 FHOut.outstring(SEG.segname, 16);
525 FHOut.outaddr(SEG.vmaddr);
526 FHOut.outaddr(SEG.vmsize);
527 FHOut.outaddr(SEG.fileoff);
528 FHOut.outaddr(SEG.filesize);
529 FHOut.outword(SEG.maxprot);
530 FHOut.outword(SEG.initprot);
531 FHOut.outword(SEG.nsects);
532 FHOut.outword(SEG.flags);
Nate Begemaneb883af2006-08-23 21:08:52 +0000533
Nate Begeman94be2482006-09-08 22:42:09 +0000534 // Step #5: Finish filling in the fields of the MachOSections
535 uint64_t currentAddr = 0;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000536 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begemaneb883af2006-08-23 21:08:52 +0000537 E = SectionList.end(); I != E; ++I) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000538 MachOSection *MOS = *I;
539 MOS->addr = currentAddr;
540 MOS->offset = currentAddr + SEG.fileoff;
Nate Begeman019f8512006-09-10 23:03:44 +0000541
Nate Begeman94be2482006-09-08 22:42:09 +0000542 // FIXME: do we need to do something with alignment here?
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000543 currentAddr += MOS->size;
Nate Begeman94be2482006-09-08 22:42:09 +0000544 }
545
Nate Begemanfec910c2007-02-28 07:40:50 +0000546 // Step #6: Emit the symbol table to temporary buffers, so that we know the
547 // size of the string table when we write the next load command. This also
548 // sorts and assigns indices to each of the symbols, which is necessary for
549 // emitting relocations to externally-defined objects.
550 BufferSymbolAndStringTable();
551
552 // Step #7: Calculate the number of relocations for each section and write out
Nate Begeman94be2482006-09-08 22:42:09 +0000553 // the section commands for each section
554 currentAddr += SEG.fileoff;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000555 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman94be2482006-09-08 22:42:09 +0000556 E = SectionList.end(); I != E; ++I) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000557 MachOSection *MOS = *I;
558 // Convert the relocations to target-specific relocations, and fill in the
559 // relocation offset for this section.
560 CalculateRelocations(*MOS);
561 MOS->reloff = MOS->nreloc ? currentAddr : 0;
562 currentAddr += MOS->nreloc * 8;
Nate Begeman94be2482006-09-08 22:42:09 +0000563
564 // write the finalized section command to the output buffer
Bill Wendling203d3e42007-01-17 22:22:31 +0000565 FHOut.outstring(MOS->sectname, 16);
566 FHOut.outstring(MOS->segname, 16);
567 FHOut.outaddr(MOS->addr);
568 FHOut.outaddr(MOS->size);
569 FHOut.outword(MOS->offset);
570 FHOut.outword(MOS->align);
571 FHOut.outword(MOS->reloff);
572 FHOut.outword(MOS->nreloc);
573 FHOut.outword(MOS->flags);
574 FHOut.outword(MOS->reserved1);
575 FHOut.outword(MOS->reserved2);
Nate Begemaneb883af2006-08-23 21:08:52 +0000576 if (is64Bit)
Bill Wendling203d3e42007-01-17 22:22:31 +0000577 FHOut.outword(MOS->reserved3);
Nate Begemaneb883af2006-08-23 21:08:52 +0000578 }
579
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000580 // Step #8: Emit LC_SYMTAB/LC_DYSYMTAB load commands
Nate Begeman94be2482006-09-08 22:42:09 +0000581 SymTab.symoff = currentAddr;
Nate Begemaneb883af2006-08-23 21:08:52 +0000582 SymTab.nsyms = SymbolTable.size();
Nate Begemand2030e62006-08-26 15:46:34 +0000583 SymTab.stroff = SymTab.symoff + SymT.size();
584 SymTab.strsize = StrT.size();
Bill Wendling203d3e42007-01-17 22:22:31 +0000585 FHOut.outword(SymTab.cmd);
586 FHOut.outword(SymTab.cmdsize);
587 FHOut.outword(SymTab.symoff);
588 FHOut.outword(SymTab.nsyms);
589 FHOut.outword(SymTab.stroff);
590 FHOut.outword(SymTab.strsize);
Nate Begemaneb883af2006-08-23 21:08:52 +0000591
592 // FIXME: set DySymTab fields appropriately
Nate Begemand2030e62006-08-26 15:46:34 +0000593 // We should probably just update these in BufferSymbolAndStringTable since
594 // thats where we're partitioning up the different kinds of symbols.
Bill Wendling203d3e42007-01-17 22:22:31 +0000595 FHOut.outword(DySymTab.cmd);
596 FHOut.outword(DySymTab.cmdsize);
597 FHOut.outword(DySymTab.ilocalsym);
598 FHOut.outword(DySymTab.nlocalsym);
599 FHOut.outword(DySymTab.iextdefsym);
600 FHOut.outword(DySymTab.nextdefsym);
601 FHOut.outword(DySymTab.iundefsym);
602 FHOut.outword(DySymTab.nundefsym);
603 FHOut.outword(DySymTab.tocoff);
604 FHOut.outword(DySymTab.ntoc);
605 FHOut.outword(DySymTab.modtaboff);
606 FHOut.outword(DySymTab.nmodtab);
607 FHOut.outword(DySymTab.extrefsymoff);
608 FHOut.outword(DySymTab.nextrefsyms);
609 FHOut.outword(DySymTab.indirectsymoff);
610 FHOut.outword(DySymTab.nindirectsyms);
611 FHOut.outword(DySymTab.extreloff);
612 FHOut.outword(DySymTab.nextrel);
613 FHOut.outword(DySymTab.locreloff);
614 FHOut.outword(DySymTab.nlocrel);
Nate Begemaneb883af2006-08-23 21:08:52 +0000615
616 O.write((char*)&FH[0], FH.size());
617}
618
619/// EmitSections - Now that we have constructed the file header and load
620/// commands, emit the data for each section to the file.
621void MachOWriter::EmitSections() {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000622 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman019f8512006-09-10 23:03:44 +0000623 E = SectionList.end(); I != E; ++I)
624 // Emit the contents of each section
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000625 O.write((char*)&(*I)->SectionData[0], (*I)->size);
626 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman019f8512006-09-10 23:03:44 +0000627 E = SectionList.end(); I != E; ++I)
628 // Emit the relocation entry data for each section.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000629 O.write((char*)&(*I)->RelocBuffer[0], (*I)->RelocBuffer.size());
Nate Begemaneb883af2006-08-23 21:08:52 +0000630}
631
Nate Begemand2030e62006-08-26 15:46:34 +0000632/// PartitionByLocal - Simple boolean predicate that returns true if Sym is
633/// a local symbol rather than an external symbol.
634bool MachOWriter::PartitionByLocal(const MachOSym &Sym) {
Nate Begemand2030e62006-08-26 15:46:34 +0000635 return (Sym.n_type & (MachOSym::N_EXT | MachOSym::N_PEXT)) == 0;
Nate Begemaneb883af2006-08-23 21:08:52 +0000636}
637
Nate Begemand2030e62006-08-26 15:46:34 +0000638/// PartitionByDefined - Simple boolean predicate that returns true if Sym is
639/// defined in this module.
640bool MachOWriter::PartitionByDefined(const MachOSym &Sym) {
641 // FIXME: Do N_ABS or N_INDR count as defined?
642 return (Sym.n_type & MachOSym::N_SECT) == MachOSym::N_SECT;
643}
Nate Begemaneb883af2006-08-23 21:08:52 +0000644
Nate Begemand2030e62006-08-26 15:46:34 +0000645/// BufferSymbolAndStringTable - Sort the symbols we encountered and assign them
646/// each a string table index so that they appear in the correct order in the
647/// output file.
648void MachOWriter::BufferSymbolAndStringTable() {
649 // The order of the symbol table is:
650 // 1. local symbols
651 // 2. defined external symbols (sorted by name)
652 // 3. undefined external symbols (sorted by name)
653
Nate Begemanfec910c2007-02-28 07:40:50 +0000654 // Before sorting the symbols, check the PendingGlobals for any undefined
655 // globals that need to be put in the symbol table.
656 for (std::vector<GlobalValue*>::iterator I = PendingGlobals.begin(),
657 E = PendingGlobals.end(); I != E; ++I) {
658 if (GVOffset[*I] == 0 && GVSection[*I] == 0) {
659 MachOSym UndfSym(*I, Mang->getValueName(*I), MachOSym::NO_SECT, TM);
660 SymbolTable.push_back(UndfSym);
661 GVOffset[*I] = -1;
662 }
663 }
664
Nate Begemand2030e62006-08-26 15:46:34 +0000665 // Sort the symbols by name, so that when we partition the symbols by scope
666 // of definition, we won't have to sort by name within each partition.
667 std::sort(SymbolTable.begin(), SymbolTable.end(), MachOSymCmp());
668
669 // Parition the symbol table entries so that all local symbols come before
670 // all symbols with external linkage. { 1 | 2 3 }
671 std::partition(SymbolTable.begin(), SymbolTable.end(), PartitionByLocal);
672
673 // Advance iterator to beginning of external symbols and partition so that
674 // all external symbols defined in this module come before all external
675 // symbols defined elsewhere. { 1 | 2 | 3 }
676 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
677 E = SymbolTable.end(); I != E; ++I) {
678 if (!PartitionByLocal(*I)) {
679 std::partition(I, E, PartitionByDefined);
680 break;
681 }
682 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000683
684 // Calculate the starting index for each of the local, extern defined, and
685 // undefined symbols, as well as the number of each to put in the LC_DYSYMTAB
686 // load command.
687 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
688 E = SymbolTable.end(); I != E; ++I) {
689 if (PartitionByLocal(*I)) {
690 ++DySymTab.nlocalsym;
691 ++DySymTab.iextdefsym;
Nate Begeman6635f352007-01-26 22:39:48 +0000692 ++DySymTab.iundefsym;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000693 } else if (PartitionByDefined(*I)) {
694 ++DySymTab.nextdefsym;
695 ++DySymTab.iundefsym;
696 } else {
697 ++DySymTab.nundefsym;
698 }
699 }
Nate Begemand2030e62006-08-26 15:46:34 +0000700
Nate Begemaneb883af2006-08-23 21:08:52 +0000701 // Write out a leading zero byte when emitting string table, for n_strx == 0
702 // which means an empty string.
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000703 OutputBuffer StrTOut(StrT, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000704 StrTOut.outbyte(0);
Nate Begemaneb883af2006-08-23 21:08:52 +0000705
Nate Begemand2030e62006-08-26 15:46:34 +0000706 // The order of the string table is:
707 // 1. strings for external symbols
708 // 2. strings for local symbols
709 // Since this is the opposite order from the symbol table, which we have just
710 // sorted, we can walk the symbol table backwards to output the string table.
711 for (std::vector<MachOSym>::reverse_iterator I = SymbolTable.rbegin(),
712 E = SymbolTable.rend(); I != E; ++I) {
713 if (I->GVName == "") {
714 I->n_strx = 0;
715 } else {
716 I->n_strx = StrT.size();
Bill Wendling203d3e42007-01-17 22:22:31 +0000717 StrTOut.outstring(I->GVName, I->GVName.length()+1);
Nate Begemand2030e62006-08-26 15:46:34 +0000718 }
Nate Begemaneb883af2006-08-23 21:08:52 +0000719 }
Nate Begemand2030e62006-08-26 15:46:34 +0000720
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000721 OutputBuffer SymTOut(SymT, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000722
Nate Begemanfec910c2007-02-28 07:40:50 +0000723 unsigned index = 0;
Nate Begemand2030e62006-08-26 15:46:34 +0000724 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
Nate Begemanfec910c2007-02-28 07:40:50 +0000725 E = SymbolTable.end(); I != E; ++I, ++index) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000726 // Add the section base address to the section offset in the n_value field
727 // to calculate the full address.
728 // FIXME: handle symbols where the n_value field is not the address
729 GlobalValue *GV = const_cast<GlobalValue*>(I->GV);
730 if (GV && GVSection[GV])
731 I->n_value += GVSection[GV]->addr;
Nate Begemanfec910c2007-02-28 07:40:50 +0000732 if (GV && (GVOffset[GV] == -1))
733 GVOffset[GV] = index;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000734
Nate Begemand2030e62006-08-26 15:46:34 +0000735 // Emit nlist to buffer
Bill Wendling203d3e42007-01-17 22:22:31 +0000736 SymTOut.outword(I->n_strx);
737 SymTOut.outbyte(I->n_type);
738 SymTOut.outbyte(I->n_sect);
739 SymTOut.outhalf(I->n_desc);
740 SymTOut.outaddr(I->n_value);
Nate Begemand2030e62006-08-26 15:46:34 +0000741 }
Nate Begemaneb883af2006-08-23 21:08:52 +0000742}
Nate Begeman94be2482006-09-08 22:42:09 +0000743
Nate Begeman019f8512006-09-10 23:03:44 +0000744/// CalculateRelocations - For each MachineRelocation in the current section,
745/// calculate the index of the section containing the object to be relocated,
746/// and the offset into that section. From this information, create the
747/// appropriate target-specific MachORelocation type and add buffer it to be
748/// written out after we are finished writing out sections.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000749void MachOWriter::CalculateRelocations(MachOSection &MOS) {
Nate Begeman019f8512006-09-10 23:03:44 +0000750 for (unsigned i = 0, e = MOS.Relocations.size(); i != e; ++i) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000751 MachineRelocation &MR = MOS.Relocations[i];
752 unsigned TargetSection = MR.getConstantVal();
Nate Begemanaf806382007-03-03 06:18:18 +0000753 unsigned TargetAddr = 0;
754 unsigned TargetIndex = 0;
Nate Begeman6635f352007-01-26 22:39:48 +0000755
756 // This is a scattered relocation entry if it points to a global value with
757 // a non-zero offset.
758 bool Scattered = false;
Nate Begemanfec910c2007-02-28 07:40:50 +0000759 bool Extern = false;
Nate Begemanaf806382007-03-03 06:18:18 +0000760
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000761 // Since we may not have seen the GlobalValue we were interested in yet at
762 // the time we emitted the relocation for it, fix it up now so that it
763 // points to the offset into the correct section.
764 if (MR.isGlobalValue()) {
765 GlobalValue *GV = MR.getGlobalValue();
766 MachOSection *MOSPtr = GVSection[GV];
Nate Begeman6635f352007-01-26 22:39:48 +0000767 intptr_t Offset = GVOffset[GV];
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000768
Nate Begemanfec910c2007-02-28 07:40:50 +0000769 // If we have never seen the global before, it must be to a symbol
770 // defined in another module (N_UNDF).
Nate Begeman1257c852007-01-29 21:20:42 +0000771 if (!MOSPtr) {
Nate Begemanfec910c2007-02-28 07:40:50 +0000772 // FIXME: need to append stub suffix
773 Extern = true;
774 TargetAddr = 0;
775 TargetIndex = GVOffset[GV];
776 } else {
777 Scattered = TargetSection != 0;
778 TargetSection = MOSPtr->Index;
Nate Begemanaf806382007-03-03 06:18:18 +0000779 }
780 MR.setResultPointer((void*)Offset);
781 }
782
783 // If the symbol is locally defined, pass in the address of the section and
784 // the section index to the code which will generate the target relocation.
785 if (!Extern) {
Nate Begemanfec910c2007-02-28 07:40:50 +0000786 MachOSection &To = *SectionList[TargetSection - 1];
787 TargetAddr = To.addr;
788 TargetIndex = To.Index;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000789 }
Bill Wendling886b4122007-02-03 02:39:40 +0000790
791 OutputBuffer RelocOut(MOS.RelocBuffer, is64Bit, isLittleEndian);
792 OutputBuffer SecOut(MOS.SectionData, is64Bit, isLittleEndian);
Nate Begemanfec910c2007-02-28 07:40:50 +0000793
794 MOS.nreloc += GetTargetRelocation(MR, MOS.Index, TargetAddr, TargetIndex,
795 RelocOut, SecOut, Scattered, Extern);
Nate Begeman019f8512006-09-10 23:03:44 +0000796 }
Nate Begeman019f8512006-09-10 23:03:44 +0000797}
798
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000799// InitMem - Write the value of a Constant to the specified memory location,
800// converting it into bytes and relocations.
801void MachOWriter::InitMem(const Constant *C, void *Addr, intptr_t Offset,
802 const TargetData *TD,
803 std::vector<MachineRelocation> &MRs) {
804 typedef std::pair<const Constant*, intptr_t> CPair;
805 std::vector<CPair> WorkList;
806
807 WorkList.push_back(CPair(C,(intptr_t)Addr + Offset));
808
Nate Begeman6635f352007-01-26 22:39:48 +0000809 intptr_t ScatteredOffset = 0;
810
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000811 while (!WorkList.empty()) {
812 const Constant *PC = WorkList.back().first;
813 intptr_t PA = WorkList.back().second;
814 WorkList.pop_back();
815
816 if (isa<UndefValue>(PC)) {
817 continue;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000818 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(PC)) {
Duncan Sandsca0ed742007-11-05 00:04:43 +0000819 unsigned ElementSize =
820 TD->getABITypeSize(CP->getType()->getElementType());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000821 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
822 WorkList.push_back(CPair(CP->getOperand(i), PA+i*ElementSize));
823 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(PC)) {
824 //
825 // FIXME: Handle ConstantExpression. See EE::getConstantValue()
826 //
827 switch (CE->getOpcode()) {
Nate Begeman6635f352007-01-26 22:39:48 +0000828 case Instruction::GetElementPtr: {
Chris Lattner7f6b9d22007-02-10 20:31:59 +0000829 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Nate Begeman6635f352007-01-26 22:39:48 +0000830 ScatteredOffset = TD->getIndexedOffset(CE->getOperand(0)->getType(),
Chris Lattner7f6b9d22007-02-10 20:31:59 +0000831 &Indices[0], Indices.size());
Nate Begeman6635f352007-01-26 22:39:48 +0000832 WorkList.push_back(CPair(CE->getOperand(0), PA));
833 break;
834 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000835 case Instruction::Add:
836 default:
837 cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
838 abort();
839 break;
840 }
841 } else if (PC->getType()->isFirstClassType()) {
842 unsigned char *ptr = (unsigned char *)PA;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000843 switch (PC->getType()->getTypeID()) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000844 case Type::IntegerTyID: {
845 unsigned NumBits = cast<IntegerType>(PC->getType())->getBitWidth();
846 uint64_t val = cast<ConstantInt>(PC)->getZExtValue();
847 if (NumBits <= 8)
848 ptr[0] = val;
849 else if (NumBits <= 16) {
850 if (TD->isBigEndian())
851 val = ByteSwap_16(val);
852 ptr[0] = val;
853 ptr[1] = val >> 8;
854 } else if (NumBits <= 32) {
855 if (TD->isBigEndian())
856 val = ByteSwap_32(val);
857 ptr[0] = val;
858 ptr[1] = val >> 8;
859 ptr[2] = val >> 16;
860 ptr[3] = val >> 24;
861 } else if (NumBits <= 64) {
862 if (TD->isBigEndian())
863 val = ByteSwap_64(val);
864 ptr[0] = val;
865 ptr[1] = val >> 8;
866 ptr[2] = val >> 16;
867 ptr[3] = val >> 24;
868 ptr[4] = val >> 32;
869 ptr[5] = val >> 40;
870 ptr[6] = val >> 48;
871 ptr[7] = val >> 56;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000872 } else {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000873 assert(0 && "Not implemented: bit widths > 64");
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000874 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000875 break;
876 }
877 case Type::FloatTyID: {
Dale Johannesen9d5f4562007-09-12 03:30:33 +0000878 uint32_t val = cast<ConstantFP>(PC)->getValueAPF().convertToAPInt().
879 getZExtValue();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000880 if (TD->isBigEndian())
881 val = ByteSwap_32(val);
882 ptr[0] = val;
883 ptr[1] = val >> 8;
884 ptr[2] = val >> 16;
885 ptr[3] = val >> 24;
886 break;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000887 }
888 case Type::DoubleTyID: {
Dale Johannesen9d5f4562007-09-12 03:30:33 +0000889 uint64_t val = cast<ConstantFP>(PC)->getValueAPF().convertToAPInt().
890 getZExtValue();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000891 if (TD->isBigEndian())
892 val = ByteSwap_64(val);
893 ptr[0] = val;
894 ptr[1] = val >> 8;
895 ptr[2] = val >> 16;
896 ptr[3] = val >> 24;
897 ptr[4] = val >> 32;
898 ptr[5] = val >> 40;
899 ptr[6] = val >> 48;
900 ptr[7] = val >> 56;
901 break;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000902 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000903 case Type::PointerTyID:
Nate Begeman6635f352007-01-26 22:39:48 +0000904 if (isa<ConstantPointerNull>(PC))
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000905 memset(ptr, 0, TD->getPointerSize());
Nate Begeman6635f352007-01-26 22:39:48 +0000906 else if (const GlobalValue* GV = dyn_cast<GlobalValue>(PC)) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000907 // FIXME: what about function stubs?
908 MRs.push_back(MachineRelocation::getGV(PA-(intptr_t)Addr,
909 MachineRelocation::VANILLA,
Nate Begeman6635f352007-01-26 22:39:48 +0000910 const_cast<GlobalValue*>(GV),
911 ScatteredOffset));
912 ScatteredOffset = 0;
913 } else
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000914 assert(0 && "Unknown constant pointer type!");
915 break;
916 default:
917 cerr << "ERROR: Constant unimp for type: " << *PC->getType() << "\n";
918 abort();
919 }
920 } else if (isa<ConstantAggregateZero>(PC)) {
Duncan Sandsca0ed742007-11-05 00:04:43 +0000921 memset((void*)PA, 0, (size_t)TD->getABITypeSize(PC->getType()));
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000922 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(PC)) {
Duncan Sandsca0ed742007-11-05 00:04:43 +0000923 unsigned ElementSize =
924 TD->getABITypeSize(CPA->getType()->getElementType());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000925 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
926 WorkList.push_back(CPair(CPA->getOperand(i), PA+i*ElementSize));
927 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(PC)) {
928 const StructLayout *SL =
929 TD->getStructLayout(cast<StructType>(CPS->getType()));
930 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
Chris Lattnerb1919e22007-02-10 19:55:17 +0000931 WorkList.push_back(CPair(CPS->getOperand(i),
932 PA+SL->getElementOffset(i)));
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000933 } else {
934 cerr << "Bad Type: " << *PC->getType() << "\n";
935 assert(0 && "Unknown constant type to initialize memory with!");
936 }
937 }
938}
939
940MachOSym::MachOSym(const GlobalValue *gv, std::string name, uint8_t sect,
941 TargetMachine &TM) :
942 GV(gv), n_strx(0), n_type(sect == NO_SECT ? N_UNDF : N_SECT), n_sect(sect),
943 n_desc(0), n_value(0) {
944
945 const TargetAsmInfo *TAI = TM.getTargetAsmInfo();
946
Nate Begeman94be2482006-09-08 22:42:09 +0000947 switch (GV->getLinkage()) {
948 default:
949 assert(0 && "Unexpected linkage type!");
950 break;
951 case GlobalValue::WeakLinkage:
952 case GlobalValue::LinkOnceLinkage:
953 assert(!isa<Function>(gv) && "Unexpected linkage type for Function!");
954 case GlobalValue::ExternalLinkage:
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000955 GVName = TAI->getGlobalPrefix() + name;
Nate Begeman6635f352007-01-26 22:39:48 +0000956 n_type |= GV->hasHiddenVisibility() ? N_PEXT : N_EXT;
Nate Begeman94be2482006-09-08 22:42:09 +0000957 break;
958 case GlobalValue::InternalLinkage:
Nate Begeman6635f352007-01-26 22:39:48 +0000959 GVName = TAI->getGlobalPrefix() + name;
Nate Begeman94be2482006-09-08 22:42:09 +0000960 break;
961 }
962}