blob: 2726f706d7f04cea6bdfdf11f3c0f9849056716b [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!
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000144 virtual void startFunctionStub(const GlobalValue* F, unsigned StubSize,
145 unsigned Alignment = 1) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000146 assert(0 && "JIT specific function called!");
147 abort();
148 }
Nicolas Geoffray51cc3c12008-04-16 20:46:05 +0000149 virtual void *finishFunctionStub(const GlobalValue* F) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000150 assert(0 && "JIT specific function called!");
151 abort();
152 return 0;
153 }
154 };
155}
156
157/// startFunction - This callback is invoked when a new machine function is
158/// about to be emitted.
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000159void MachOCodeEmitter::startFunction(MachineFunction &MF) {
160 const TargetData *TD = TM.getTargetData();
161 const Function *F = MF.getFunction();
162
Nate Begemaneb883af2006-08-23 21:08:52 +0000163 // Align the output buffer to the appropriate alignment, power of 2.
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000164 unsigned FnAlign = F->getAlignment();
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000165 unsigned TDAlign = TD->getPrefTypeAlignment(F->getType());
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000166 unsigned Align = Log2_32(std::max(FnAlign, TDAlign));
167 assert(!(Align & (Align-1)) && "Alignment is not a power of two!");
Nate Begemaneb883af2006-08-23 21:08:52 +0000168
169 // Get the Mach-O Section that this function belongs in.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000170 MachOWriter::MachOSection *MOS = MOW.getTextSection();
Nate Begemaneb883af2006-08-23 21:08:52 +0000171
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000172 // FIXME: better memory management
Nate Begemaneb883af2006-08-23 21:08:52 +0000173 MOS->SectionData.reserve(4096);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000174 BufferBegin = &MOS->SectionData[0];
Nate Begemaneb883af2006-08-23 21:08:52 +0000175 BufferEnd = BufferBegin + MOS->SectionData.capacity();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000176
Nate Begeman6635f352007-01-26 22:39:48 +0000177 // Upgrade the section alignment if required.
178 if (MOS->align < Align) MOS->align = Align;
179
180 // Round the size up to the correct alignment for starting the new function.
181 if ((MOS->size & ((1 << Align) - 1)) != 0) {
182 MOS->size += (1 << Align);
183 MOS->size &= ~((1 << Align) - 1);
184 }
185
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000186 // FIXME: Using MOS->size directly here instead of calculating it from the
187 // output buffer size (impossible because the code emitter deals only in raw
188 // bytes) forces us to manually synchronize size and write padding zero bytes
189 // to the output buffer for all non-text sections. For text sections, we do
190 // not synchonize the output buffer, and we just blow up if anyone tries to
191 // write non-code to it. An assert should probably be added to
192 // AddSymbolToSection to prevent calling it on the text section.
Nate Begemaneb883af2006-08-23 21:08:52 +0000193 CurBufferPtr = BufferBegin + MOS->size;
194
Nate Begeman019f8512006-09-10 23:03:44 +0000195 // Clear per-function data structures.
196 CPLocations.clear();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000197 CPSections.clear();
Nate Begeman019f8512006-09-10 23:03:44 +0000198 JTLocations.clear();
Nate Begemaneb883af2006-08-23 21:08:52 +0000199 MBBLocations.clear();
200}
201
202/// finishFunction - This callback is invoked after the function is completely
203/// finished.
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000204bool MachOCodeEmitter::finishFunction(MachineFunction &MF) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000205 // Get the Mach-O Section that this function belongs in.
206 MachOWriter::MachOSection *MOS = MOW.getTextSection();
207
Nate Begemaneb883af2006-08-23 21:08:52 +0000208 // Get a symbol for the function to add to the symbol table
Nate Begeman6635f352007-01-26 22:39:48 +0000209 // FIXME: it seems like we should call something like AddSymbolToSection
210 // in startFunction rather than changing the section size and symbol n_value
211 // here.
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000212 const GlobalValue *FuncV = MF.getFunction();
Bill Wendling203d3e42007-01-17 22:22:31 +0000213 MachOSym FnSym(FuncV, MOW.Mang->getValueName(FuncV), MOS->Index, TM);
Nate Begeman6635f352007-01-26 22:39:48 +0000214 FnSym.n_value = MOS->size;
215 MOS->size = CurBufferPtr - BufferBegin;
216
Nate Begeman019f8512006-09-10 23:03:44 +0000217 // Emit constant pool to appropriate section(s)
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000218 emitConstantPool(MF.getConstantPool());
Nate Begeman019f8512006-09-10 23:03:44 +0000219
220 // Emit jump tables to appropriate section
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000221 emitJumpTables(MF.getJumpTableInfo());
Nate Begemaneb883af2006-08-23 21:08:52 +0000222
Nate Begeman019f8512006-09-10 23:03:44 +0000223 // If we have emitted any relocations to function-specific objects such as
224 // basic blocks, constant pools entries, or jump tables, record their
225 // addresses now so that we can rewrite them with the correct addresses
226 // later.
Nate Begemaneb883af2006-08-23 21:08:52 +0000227 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
228 MachineRelocation &MR = Relocations[i];
Nate Begeman019f8512006-09-10 23:03:44 +0000229 intptr_t Addr;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000230
Nate Begemaneb883af2006-08-23 21:08:52 +0000231 if (MR.isBasicBlock()) {
Nate Begeman019f8512006-09-10 23:03:44 +0000232 Addr = getMachineBasicBlockAddress(MR.getBasicBlock());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000233 MR.setConstantVal(MOS->Index);
234 MR.setResultPointer((void*)Addr);
235 } else if (MR.isJumpTableIndex()) {
236 Addr = getJumpTableEntryAddress(MR.getJumpTableIndex());
237 MR.setConstantVal(MOW.getJumpTableSection()->Index);
238 MR.setResultPointer((void*)Addr);
Nate Begeman019f8512006-09-10 23:03:44 +0000239 } else if (MR.isConstantPoolIndex()) {
240 Addr = getConstantPoolEntryAddress(MR.getConstantPoolIndex());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000241 MR.setConstantVal(CPSections[MR.getConstantPoolIndex()]);
242 MR.setResultPointer((void*)Addr);
Nate Begemanfec910c2007-02-28 07:40:50 +0000243 } else if (MR.isGlobalValue()) {
244 // FIXME: This should be a set or something that uniques
245 MOW.PendingGlobals.push_back(MR.getGlobalValue());
246 } else {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000247 assert(0 && "Unhandled relocation type");
Nate Begemaneb883af2006-08-23 21:08:52 +0000248 }
Nate Begeman019f8512006-09-10 23:03:44 +0000249 MOS->Relocations.push_back(MR);
Nate Begemaneb883af2006-08-23 21:08:52 +0000250 }
251 Relocations.clear();
252
253 // Finally, add it to the symtab.
254 MOW.SymbolTable.push_back(FnSym);
255 return false;
256}
257
Nate Begeman019f8512006-09-10 23:03:44 +0000258/// emitConstantPool - For each constant pool entry, figure out which section
259/// the constant should live in, allocate space for it, and emit it to the
260/// Section data buffer.
261void MachOCodeEmitter::emitConstantPool(MachineConstantPool *MCP) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000262 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
263 if (CP.empty()) return;
264
265 // FIXME: handle PIC codegen
Bill Wendling203d3e42007-01-17 22:22:31 +0000266 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000267 assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
268
269 // Although there is no strict necessity that I am aware of, we will do what
270 // gcc for OS X does and put each constant pool entry in a section of constant
271 // objects of a certain size. That means that float constants go in the
272 // literal4 section, and double objects go in literal8, etc.
273 //
274 // FIXME: revisit this decision if we ever do the "stick everything into one
275 // "giant object for PIC" optimization.
276 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
277 const Type *Ty = CP[i].getType();
Duncan Sandsca0ed742007-11-05 00:04:43 +0000278 unsigned Size = TM.getTargetData()->getABITypeSize(Ty);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000279
Nate Begeman1257c852007-01-29 21:20:42 +0000280 MachOWriter::MachOSection *Sec = MOW.getConstSection(CP[i].Val.ConstVal);
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000281 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000282
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000283 CPLocations.push_back(Sec->SectionData.size());
284 CPSections.push_back(Sec->Index);
285
286 // FIXME: remove when we have unified size + output buffer
287 Sec->size += Size;
288
289 // Allocate space in the section for the global.
290 // FIXME: need alignment?
291 // FIXME: share between here and AddSymbolToSection?
292 for (unsigned j = 0; j < Size; ++j)
Bill Wendling203d3e42007-01-17 22:22:31 +0000293 SecDataOut.outbyte(0);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000294
295 MOW.InitMem(CP[i].Val.ConstVal, &Sec->SectionData[0], CPLocations[i],
Bill Wendling203d3e42007-01-17 22:22:31 +0000296 TM.getTargetData(), Sec->Relocations);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000297 }
Nate Begeman019f8512006-09-10 23:03:44 +0000298}
299
300/// emitJumpTables - Emit all the jump tables for a given jump table info
301/// record to the appropriate section.
302void MachOCodeEmitter::emitJumpTables(MachineJumpTableInfo *MJTI) {
303 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
304 if (JT.empty()) return;
305
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000306 // FIXME: handle PIC codegen
Bill Wendling203d3e42007-01-17 22:22:31 +0000307 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
Nate Begeman019f8512006-09-10 23:03:44 +0000308 assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
309
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000310 MachOWriter::MachOSection *Sec = MOW.getJumpTableSection();
311 unsigned TextSecIndex = MOW.getTextSection()->Index;
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000312 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
Nate Begeman019f8512006-09-10 23:03:44 +0000313
314 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
315 // For each jump table, record its offset from the start of the section,
316 // reserve space for the relocations to the MBBs, and add the relocations.
317 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000318 JTLocations.push_back(Sec->SectionData.size());
Nate Begeman019f8512006-09-10 23:03:44 +0000319 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000320 MachineRelocation MR(MOW.GetJTRelocation(Sec->SectionData.size(),
Nate Begeman019f8512006-09-10 23:03:44 +0000321 MBBs[mi]));
322 MR.setResultPointer((void *)JTLocations[i]);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000323 MR.setConstantVal(TextSecIndex);
324 Sec->Relocations.push_back(MR);
Bill Wendling203d3e42007-01-17 22:22:31 +0000325 SecDataOut.outaddr(0);
Nate Begeman019f8512006-09-10 23:03:44 +0000326 }
327 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000328 // FIXME: remove when we have unified size + output buffer
329 Sec->size = Sec->SectionData.size();
Nate Begeman019f8512006-09-10 23:03:44 +0000330}
331
Nate Begemaneb883af2006-08-23 21:08:52 +0000332//===----------------------------------------------------------------------===//
333// MachOWriter Implementation
334//===----------------------------------------------------------------------===//
335
Devang Patel19974732007-05-03 01:11:54 +0000336char MachOWriter::ID = 0;
Devang Patel794fd752007-05-01 21:15:47 +0000337MachOWriter::MachOWriter(std::ostream &o, TargetMachine &tm)
338 : MachineFunctionPass((intptr_t)&ID), O(o), TM(tm) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000339 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
340 isLittleEndian = TM.getTargetData()->isLittleEndian();
341
342 // Create the machine code emitter object for this target.
Bill Wendlinge9116152007-01-17 09:06:13 +0000343 MCE = new MachOCodeEmitter(*this);
Nate Begemaneb883af2006-08-23 21:08:52 +0000344}
345
346MachOWriter::~MachOWriter() {
347 delete MCE;
348}
349
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000350void MachOWriter::AddSymbolToSection(MachOSection *Sec, GlobalVariable *GV) {
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000351 const Type *Ty = GV->getType()->getElementType();
Duncan Sandsca0ed742007-11-05 00:04:43 +0000352 unsigned Size = TM.getTargetData()->getABITypeSize(Ty);
Duncan Sandsd1025932008-01-29 06:23:44 +0000353 unsigned Align = TM.getTargetData()->getPreferredAlignment(GV);
354
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000355 // Reserve space in the .bss section for this symbol while maintaining the
356 // desired section alignment, which must be at least as much as required by
357 // this symbol.
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000358 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000359
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000360 if (Align) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000361 uint64_t OrigSize = Sec->size;
362 Align = Log2_32(Align);
363 Sec->align = std::max(unsigned(Sec->align), Align);
364 Sec->size = (Sec->size + Align - 1) & ~(Align-1);
365
366 // Add alignment padding to buffer as well.
367 // FIXME: remove when we have unified size + output buffer
368 unsigned AlignedSize = Sec->size - OrigSize;
369 for (unsigned i = 0; i < AlignedSize; ++i)
Bill Wendling203d3e42007-01-17 22:22:31 +0000370 SecDataOut.outbyte(0);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000371 }
Nate Begemanfec910c2007-02-28 07:40:50 +0000372 // Globals without external linkage apparently do not go in the symbol table.
373 if (GV->getLinkage() != GlobalValue::InternalLinkage) {
374 MachOSym Sym(GV, Mang->getValueName(GV), Sec->Index, TM);
375 Sym.n_value = Sec->size;
376 SymbolTable.push_back(Sym);
377 }
378
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000379 // Record the offset of the symbol, and then allocate space for it.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000380 // FIXME: remove when we have unified size + output buffer
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000381 Sec->size += Size;
Nate Begemanfec910c2007-02-28 07:40:50 +0000382
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000383 // Now that we know what section the GlovalVariable is going to be emitted
384 // into, update our mappings.
385 // FIXME: We may also need to update this when outputting non-GlobalVariable
386 // GlobalValues such as functions.
387 GVSection[GV] = Sec;
388 GVOffset[GV] = Sec->SectionData.size();
389
390 // Allocate space in the section for the global.
391 for (unsigned i = 0; i < Size; ++i)
Bill Wendling203d3e42007-01-17 22:22:31 +0000392 SecDataOut.outbyte(0);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000393}
394
Nate Begemaneb883af2006-08-23 21:08:52 +0000395void MachOWriter::EmitGlobal(GlobalVariable *GV) {
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000396 const Type *Ty = GV->getType()->getElementType();
Duncan Sandsca0ed742007-11-05 00:04:43 +0000397 unsigned Size = TM.getTargetData()->getABITypeSize(Ty);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000398 bool NoInit = !GV->hasInitializer();
Nate Begemand2030e62006-08-26 15:46:34 +0000399
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000400 // If this global has a zero initializer, it is part of the .bss or common
401 // section.
402 if (NoInit || GV->getInitializer()->isNullValue()) {
403 // If this global is part of the common block, add it now. Variables are
404 // part of the common block if they are zero initialized and allowed to be
405 // merged with other symbols.
406 if (NoInit || GV->hasLinkOnceLinkage() || GV->hasWeakLinkage()) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000407 MachOSym ExtOrCommonSym(GV, Mang->getValueName(GV), MachOSym::NO_SECT,TM);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000408 // For undefined (N_UNDF) external (N_EXT) types, n_value is the size in
409 // bytes of the symbol.
410 ExtOrCommonSym.n_value = Size;
Nate Begemanfec910c2007-02-28 07:40:50 +0000411 SymbolTable.push_back(ExtOrCommonSym);
412 // Remember that we've seen this symbol
413 GVOffset[GV] = Size;
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000414 return;
415 }
416 // Otherwise, this symbol is part of the .bss section.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000417 MachOSection *BSS = getBSSSection();
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000418 AddSymbolToSection(BSS, GV);
419 return;
420 }
421
422 // Scalar read-only data goes in a literal section if the scalar is 4, 8, or
423 // 16 bytes, or a cstring. Other read only data goes into a regular const
424 // section. Read-write data goes in the data section.
Nate Begeman1257c852007-01-29 21:20:42 +0000425 MachOSection *Sec = GV->isConstant() ? getConstSection(GV->getInitializer()) :
426 getDataSection();
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000427 AddSymbolToSection(Sec, GV);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000428 InitMem(GV->getInitializer(), &Sec->SectionData[0], GVOffset[GV],
429 TM.getTargetData(), Sec->Relocations);
Nate Begemaneb883af2006-08-23 21:08:52 +0000430}
431
432
433bool MachOWriter::runOnMachineFunction(MachineFunction &MF) {
434 // Nothing to do here, this is all done through the MCE object.
435 return false;
436}
437
438bool MachOWriter::doInitialization(Module &M) {
439 // Set the magic value, now that we know the pointer size and endianness
440 Header.setMagic(isLittleEndian, is64Bit);
441
442 // Set the file type
443 // FIXME: this only works for object files, we do not support the creation
444 // of dynamic libraries or executables at this time.
445 Header.filetype = MachOHeader::MH_OBJECT;
446
447 Mang = new Mangler(M);
448 return false;
449}
450
451/// doFinalization - Now that the module has been completely processed, emit
452/// the Mach-O file to 'O'.
453bool MachOWriter::doFinalization(Module &M) {
Nate Begemand2030e62006-08-26 15:46:34 +0000454 // FIXME: we don't handle debug info yet, we should probably do that.
455
Nate Begemaneb883af2006-08-23 21:08:52 +0000456 // Okay, the.text section has been completed, build the .data, .bss, and
457 // "common" sections next.
458 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
459 I != E; ++I)
460 EmitGlobal(I);
461
462 // Emit the header and load commands.
463 EmitHeaderAndLoadCommands();
464
Nate Begeman019f8512006-09-10 23:03:44 +0000465 // Emit the various sections and their relocation info.
Nate Begemaneb883af2006-08-23 21:08:52 +0000466 EmitSections();
467
Nate Begemand2030e62006-08-26 15:46:34 +0000468 // Write the symbol table and the string table to the end of the file.
469 O.write((char*)&SymT[0], SymT.size());
470 O.write((char*)&StrT[0], StrT.size());
Nate Begemaneb883af2006-08-23 21:08:52 +0000471
472 // We are done with the abstract symbols.
473 SectionList.clear();
474 SymbolTable.clear();
475 DynamicSymbolTable.clear();
476
477 // Release the name mangler object.
478 delete Mang; Mang = 0;
479 return false;
480}
481
482void MachOWriter::EmitHeaderAndLoadCommands() {
483 // Step #0: Fill in the segment load command size, since we need it to figure
484 // out the rest of the header fields
485 MachOSegment SEG("", is64Bit);
486 SEG.nsects = SectionList.size();
487 SEG.cmdsize = SEG.cmdSize(is64Bit) +
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000488 SEG.nsects * SectionList[0]->cmdSize(is64Bit);
Nate Begemaneb883af2006-08-23 21:08:52 +0000489
490 // Step #1: calculate the number of load commands. We always have at least
491 // one, for the LC_SEGMENT load command, plus two for the normal
492 // and dynamic symbol tables, if there are any symbols.
493 Header.ncmds = SymbolTable.empty() ? 1 : 3;
494
495 // Step #2: calculate the size of the load commands
496 Header.sizeofcmds = SEG.cmdsize;
497 if (!SymbolTable.empty())
498 Header.sizeofcmds += SymTab.cmdsize + DySymTab.cmdsize;
499
500 // Step #3: write the header to the file
501 // Local alias to shortenify coming code.
502 DataBuffer &FH = Header.HeaderData;
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000503 OutputBuffer FHOut(FH, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000504
505 FHOut.outword(Header.magic);
Bill Wendling2b721822007-01-24 07:13:56 +0000506 FHOut.outword(TM.getMachOWriterInfo()->getCPUType());
507 FHOut.outword(TM.getMachOWriterInfo()->getCPUSubType());
Bill Wendling203d3e42007-01-17 22:22:31 +0000508 FHOut.outword(Header.filetype);
509 FHOut.outword(Header.ncmds);
510 FHOut.outword(Header.sizeofcmds);
511 FHOut.outword(Header.flags);
Nate Begemaneb883af2006-08-23 21:08:52 +0000512 if (is64Bit)
Bill Wendling203d3e42007-01-17 22:22:31 +0000513 FHOut.outword(Header.reserved);
Nate Begemaneb883af2006-08-23 21:08:52 +0000514
515 // Step #4: Finish filling in the segment load command and write it out
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000516 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begemaneb883af2006-08-23 21:08:52 +0000517 E = SectionList.end(); I != E; ++I)
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000518 SEG.filesize += (*I)->size;
519
Nate Begemaneb883af2006-08-23 21:08:52 +0000520 SEG.vmsize = SEG.filesize;
521 SEG.fileoff = Header.cmdSize(is64Bit) + Header.sizeofcmds;
522
Bill Wendling203d3e42007-01-17 22:22:31 +0000523 FHOut.outword(SEG.cmd);
524 FHOut.outword(SEG.cmdsize);
525 FHOut.outstring(SEG.segname, 16);
526 FHOut.outaddr(SEG.vmaddr);
527 FHOut.outaddr(SEG.vmsize);
528 FHOut.outaddr(SEG.fileoff);
529 FHOut.outaddr(SEG.filesize);
530 FHOut.outword(SEG.maxprot);
531 FHOut.outword(SEG.initprot);
532 FHOut.outword(SEG.nsects);
533 FHOut.outword(SEG.flags);
Nate Begemaneb883af2006-08-23 21:08:52 +0000534
Nate Begeman94be2482006-09-08 22:42:09 +0000535 // Step #5: Finish filling in the fields of the MachOSections
536 uint64_t currentAddr = 0;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000537 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begemaneb883af2006-08-23 21:08:52 +0000538 E = SectionList.end(); I != E; ++I) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000539 MachOSection *MOS = *I;
540 MOS->addr = currentAddr;
541 MOS->offset = currentAddr + SEG.fileoff;
Nate Begeman019f8512006-09-10 23:03:44 +0000542
Nate Begeman94be2482006-09-08 22:42:09 +0000543 // FIXME: do we need to do something with alignment here?
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000544 currentAddr += MOS->size;
Nate Begeman94be2482006-09-08 22:42:09 +0000545 }
546
Nate Begemanfec910c2007-02-28 07:40:50 +0000547 // Step #6: Emit the symbol table to temporary buffers, so that we know the
548 // size of the string table when we write the next load command. This also
549 // sorts and assigns indices to each of the symbols, which is necessary for
550 // emitting relocations to externally-defined objects.
551 BufferSymbolAndStringTable();
552
553 // Step #7: Calculate the number of relocations for each section and write out
Nate Begeman94be2482006-09-08 22:42:09 +0000554 // the section commands for each section
555 currentAddr += SEG.fileoff;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000556 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman94be2482006-09-08 22:42:09 +0000557 E = SectionList.end(); I != E; ++I) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000558 MachOSection *MOS = *I;
559 // Convert the relocations to target-specific relocations, and fill in the
560 // relocation offset for this section.
561 CalculateRelocations(*MOS);
562 MOS->reloff = MOS->nreloc ? currentAddr : 0;
563 currentAddr += MOS->nreloc * 8;
Nate Begeman94be2482006-09-08 22:42:09 +0000564
565 // write the finalized section command to the output buffer
Bill Wendling203d3e42007-01-17 22:22:31 +0000566 FHOut.outstring(MOS->sectname, 16);
567 FHOut.outstring(MOS->segname, 16);
568 FHOut.outaddr(MOS->addr);
569 FHOut.outaddr(MOS->size);
570 FHOut.outword(MOS->offset);
571 FHOut.outword(MOS->align);
572 FHOut.outword(MOS->reloff);
573 FHOut.outword(MOS->nreloc);
574 FHOut.outword(MOS->flags);
575 FHOut.outword(MOS->reserved1);
576 FHOut.outword(MOS->reserved2);
Nate Begemaneb883af2006-08-23 21:08:52 +0000577 if (is64Bit)
Bill Wendling203d3e42007-01-17 22:22:31 +0000578 FHOut.outword(MOS->reserved3);
Nate Begemaneb883af2006-08-23 21:08:52 +0000579 }
580
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000581 // Step #8: Emit LC_SYMTAB/LC_DYSYMTAB load commands
Nate Begeman94be2482006-09-08 22:42:09 +0000582 SymTab.symoff = currentAddr;
Nate Begemaneb883af2006-08-23 21:08:52 +0000583 SymTab.nsyms = SymbolTable.size();
Nate Begemand2030e62006-08-26 15:46:34 +0000584 SymTab.stroff = SymTab.symoff + SymT.size();
585 SymTab.strsize = StrT.size();
Bill Wendling203d3e42007-01-17 22:22:31 +0000586 FHOut.outword(SymTab.cmd);
587 FHOut.outword(SymTab.cmdsize);
588 FHOut.outword(SymTab.symoff);
589 FHOut.outword(SymTab.nsyms);
590 FHOut.outword(SymTab.stroff);
591 FHOut.outword(SymTab.strsize);
Nate Begemaneb883af2006-08-23 21:08:52 +0000592
593 // FIXME: set DySymTab fields appropriately
Nate Begemand2030e62006-08-26 15:46:34 +0000594 // We should probably just update these in BufferSymbolAndStringTable since
595 // thats where we're partitioning up the different kinds of symbols.
Bill Wendling203d3e42007-01-17 22:22:31 +0000596 FHOut.outword(DySymTab.cmd);
597 FHOut.outword(DySymTab.cmdsize);
598 FHOut.outword(DySymTab.ilocalsym);
599 FHOut.outword(DySymTab.nlocalsym);
600 FHOut.outword(DySymTab.iextdefsym);
601 FHOut.outword(DySymTab.nextdefsym);
602 FHOut.outword(DySymTab.iundefsym);
603 FHOut.outword(DySymTab.nundefsym);
604 FHOut.outword(DySymTab.tocoff);
605 FHOut.outword(DySymTab.ntoc);
606 FHOut.outword(DySymTab.modtaboff);
607 FHOut.outword(DySymTab.nmodtab);
608 FHOut.outword(DySymTab.extrefsymoff);
609 FHOut.outword(DySymTab.nextrefsyms);
610 FHOut.outword(DySymTab.indirectsymoff);
611 FHOut.outword(DySymTab.nindirectsyms);
612 FHOut.outword(DySymTab.extreloff);
613 FHOut.outword(DySymTab.nextrel);
614 FHOut.outword(DySymTab.locreloff);
615 FHOut.outword(DySymTab.nlocrel);
Nate Begemaneb883af2006-08-23 21:08:52 +0000616
617 O.write((char*)&FH[0], FH.size());
618}
619
620/// EmitSections - Now that we have constructed the file header and load
621/// commands, emit the data for each section to the file.
622void MachOWriter::EmitSections() {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000623 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman019f8512006-09-10 23:03:44 +0000624 E = SectionList.end(); I != E; ++I)
625 // Emit the contents of each section
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000626 O.write((char*)&(*I)->SectionData[0], (*I)->size);
627 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman019f8512006-09-10 23:03:44 +0000628 E = SectionList.end(); I != E; ++I)
629 // Emit the relocation entry data for each section.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000630 O.write((char*)&(*I)->RelocBuffer[0], (*I)->RelocBuffer.size());
Nate Begemaneb883af2006-08-23 21:08:52 +0000631}
632
Nate Begemand2030e62006-08-26 15:46:34 +0000633/// PartitionByLocal - Simple boolean predicate that returns true if Sym is
634/// a local symbol rather than an external symbol.
635bool MachOWriter::PartitionByLocal(const MachOSym &Sym) {
Nate Begemand2030e62006-08-26 15:46:34 +0000636 return (Sym.n_type & (MachOSym::N_EXT | MachOSym::N_PEXT)) == 0;
Nate Begemaneb883af2006-08-23 21:08:52 +0000637}
638
Nate Begemand2030e62006-08-26 15:46:34 +0000639/// PartitionByDefined - Simple boolean predicate that returns true if Sym is
640/// defined in this module.
641bool MachOWriter::PartitionByDefined(const MachOSym &Sym) {
642 // FIXME: Do N_ABS or N_INDR count as defined?
643 return (Sym.n_type & MachOSym::N_SECT) == MachOSym::N_SECT;
644}
Nate Begemaneb883af2006-08-23 21:08:52 +0000645
Nate Begemand2030e62006-08-26 15:46:34 +0000646/// BufferSymbolAndStringTable - Sort the symbols we encountered and assign them
647/// each a string table index so that they appear in the correct order in the
648/// output file.
649void MachOWriter::BufferSymbolAndStringTable() {
650 // The order of the symbol table is:
651 // 1. local symbols
652 // 2. defined external symbols (sorted by name)
653 // 3. undefined external symbols (sorted by name)
654
Nate Begemanfec910c2007-02-28 07:40:50 +0000655 // Before sorting the symbols, check the PendingGlobals for any undefined
656 // globals that need to be put in the symbol table.
657 for (std::vector<GlobalValue*>::iterator I = PendingGlobals.begin(),
658 E = PendingGlobals.end(); I != E; ++I) {
659 if (GVOffset[*I] == 0 && GVSection[*I] == 0) {
660 MachOSym UndfSym(*I, Mang->getValueName(*I), MachOSym::NO_SECT, TM);
661 SymbolTable.push_back(UndfSym);
662 GVOffset[*I] = -1;
663 }
664 }
665
Nate Begemand2030e62006-08-26 15:46:34 +0000666 // Sort the symbols by name, so that when we partition the symbols by scope
667 // of definition, we won't have to sort by name within each partition.
668 std::sort(SymbolTable.begin(), SymbolTable.end(), MachOSymCmp());
669
670 // Parition the symbol table entries so that all local symbols come before
671 // all symbols with external linkage. { 1 | 2 3 }
672 std::partition(SymbolTable.begin(), SymbolTable.end(), PartitionByLocal);
673
674 // Advance iterator to beginning of external symbols and partition so that
675 // all external symbols defined in this module come before all external
676 // symbols defined elsewhere. { 1 | 2 | 3 }
677 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
678 E = SymbolTable.end(); I != E; ++I) {
679 if (!PartitionByLocal(*I)) {
680 std::partition(I, E, PartitionByDefined);
681 break;
682 }
683 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000684
685 // Calculate the starting index for each of the local, extern defined, and
686 // undefined symbols, as well as the number of each to put in the LC_DYSYMTAB
687 // load command.
688 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
689 E = SymbolTable.end(); I != E; ++I) {
690 if (PartitionByLocal(*I)) {
691 ++DySymTab.nlocalsym;
692 ++DySymTab.iextdefsym;
Nate Begeman6635f352007-01-26 22:39:48 +0000693 ++DySymTab.iundefsym;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000694 } else if (PartitionByDefined(*I)) {
695 ++DySymTab.nextdefsym;
696 ++DySymTab.iundefsym;
697 } else {
698 ++DySymTab.nundefsym;
699 }
700 }
Nate Begemand2030e62006-08-26 15:46:34 +0000701
Nate Begemaneb883af2006-08-23 21:08:52 +0000702 // Write out a leading zero byte when emitting string table, for n_strx == 0
703 // which means an empty string.
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000704 OutputBuffer StrTOut(StrT, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000705 StrTOut.outbyte(0);
Nate Begemaneb883af2006-08-23 21:08:52 +0000706
Nate Begemand2030e62006-08-26 15:46:34 +0000707 // The order of the string table is:
708 // 1. strings for external symbols
709 // 2. strings for local symbols
710 // Since this is the opposite order from the symbol table, which we have just
711 // sorted, we can walk the symbol table backwards to output the string table.
712 for (std::vector<MachOSym>::reverse_iterator I = SymbolTable.rbegin(),
713 E = SymbolTable.rend(); I != E; ++I) {
714 if (I->GVName == "") {
715 I->n_strx = 0;
716 } else {
717 I->n_strx = StrT.size();
Bill Wendling203d3e42007-01-17 22:22:31 +0000718 StrTOut.outstring(I->GVName, I->GVName.length()+1);
Nate Begemand2030e62006-08-26 15:46:34 +0000719 }
Nate Begemaneb883af2006-08-23 21:08:52 +0000720 }
Nate Begemand2030e62006-08-26 15:46:34 +0000721
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000722 OutputBuffer SymTOut(SymT, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000723
Nate Begemanfec910c2007-02-28 07:40:50 +0000724 unsigned index = 0;
Nate Begemand2030e62006-08-26 15:46:34 +0000725 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
Nate Begemanfec910c2007-02-28 07:40:50 +0000726 E = SymbolTable.end(); I != E; ++I, ++index) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000727 // Add the section base address to the section offset in the n_value field
728 // to calculate the full address.
729 // FIXME: handle symbols where the n_value field is not the address
730 GlobalValue *GV = const_cast<GlobalValue*>(I->GV);
731 if (GV && GVSection[GV])
732 I->n_value += GVSection[GV]->addr;
Nate Begemanfec910c2007-02-28 07:40:50 +0000733 if (GV && (GVOffset[GV] == -1))
734 GVOffset[GV] = index;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000735
Nate Begemand2030e62006-08-26 15:46:34 +0000736 // Emit nlist to buffer
Bill Wendling203d3e42007-01-17 22:22:31 +0000737 SymTOut.outword(I->n_strx);
738 SymTOut.outbyte(I->n_type);
739 SymTOut.outbyte(I->n_sect);
740 SymTOut.outhalf(I->n_desc);
741 SymTOut.outaddr(I->n_value);
Nate Begemand2030e62006-08-26 15:46:34 +0000742 }
Nate Begemaneb883af2006-08-23 21:08:52 +0000743}
Nate Begeman94be2482006-09-08 22:42:09 +0000744
Nate Begeman019f8512006-09-10 23:03:44 +0000745/// CalculateRelocations - For each MachineRelocation in the current section,
746/// calculate the index of the section containing the object to be relocated,
747/// and the offset into that section. From this information, create the
748/// appropriate target-specific MachORelocation type and add buffer it to be
749/// written out after we are finished writing out sections.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000750void MachOWriter::CalculateRelocations(MachOSection &MOS) {
Nate Begeman019f8512006-09-10 23:03:44 +0000751 for (unsigned i = 0, e = MOS.Relocations.size(); i != e; ++i) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000752 MachineRelocation &MR = MOS.Relocations[i];
753 unsigned TargetSection = MR.getConstantVal();
Nate Begemanaf806382007-03-03 06:18:18 +0000754 unsigned TargetAddr = 0;
755 unsigned TargetIndex = 0;
Nate Begeman6635f352007-01-26 22:39:48 +0000756
757 // This is a scattered relocation entry if it points to a global value with
758 // a non-zero offset.
759 bool Scattered = false;
Nate Begemanfec910c2007-02-28 07:40:50 +0000760 bool Extern = false;
Nate Begemanaf806382007-03-03 06:18:18 +0000761
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000762 // Since we may not have seen the GlobalValue we were interested in yet at
763 // the time we emitted the relocation for it, fix it up now so that it
764 // points to the offset into the correct section.
765 if (MR.isGlobalValue()) {
766 GlobalValue *GV = MR.getGlobalValue();
767 MachOSection *MOSPtr = GVSection[GV];
Nate Begeman6635f352007-01-26 22:39:48 +0000768 intptr_t Offset = GVOffset[GV];
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000769
Nate Begemanfec910c2007-02-28 07:40:50 +0000770 // If we have never seen the global before, it must be to a symbol
771 // defined in another module (N_UNDF).
Nate Begeman1257c852007-01-29 21:20:42 +0000772 if (!MOSPtr) {
Nate Begemanfec910c2007-02-28 07:40:50 +0000773 // FIXME: need to append stub suffix
774 Extern = true;
775 TargetAddr = 0;
776 TargetIndex = GVOffset[GV];
777 } else {
778 Scattered = TargetSection != 0;
779 TargetSection = MOSPtr->Index;
Nate Begemanaf806382007-03-03 06:18:18 +0000780 }
781 MR.setResultPointer((void*)Offset);
782 }
783
784 // If the symbol is locally defined, pass in the address of the section and
785 // the section index to the code which will generate the target relocation.
786 if (!Extern) {
Nate Begemanfec910c2007-02-28 07:40:50 +0000787 MachOSection &To = *SectionList[TargetSection - 1];
788 TargetAddr = To.addr;
789 TargetIndex = To.Index;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000790 }
Bill Wendling886b4122007-02-03 02:39:40 +0000791
792 OutputBuffer RelocOut(MOS.RelocBuffer, is64Bit, isLittleEndian);
793 OutputBuffer SecOut(MOS.SectionData, is64Bit, isLittleEndian);
Nate Begemanfec910c2007-02-28 07:40:50 +0000794
795 MOS.nreloc += GetTargetRelocation(MR, MOS.Index, TargetAddr, TargetIndex,
796 RelocOut, SecOut, Scattered, Extern);
Nate Begeman019f8512006-09-10 23:03:44 +0000797 }
Nate Begeman019f8512006-09-10 23:03:44 +0000798}
799
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000800// InitMem - Write the value of a Constant to the specified memory location,
801// converting it into bytes and relocations.
802void MachOWriter::InitMem(const Constant *C, void *Addr, intptr_t Offset,
803 const TargetData *TD,
804 std::vector<MachineRelocation> &MRs) {
805 typedef std::pair<const Constant*, intptr_t> CPair;
806 std::vector<CPair> WorkList;
807
808 WorkList.push_back(CPair(C,(intptr_t)Addr + Offset));
809
Nate Begeman6635f352007-01-26 22:39:48 +0000810 intptr_t ScatteredOffset = 0;
811
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000812 while (!WorkList.empty()) {
813 const Constant *PC = WorkList.back().first;
814 intptr_t PA = WorkList.back().second;
815 WorkList.pop_back();
816
817 if (isa<UndefValue>(PC)) {
818 continue;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000819 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(PC)) {
Duncan Sandsca0ed742007-11-05 00:04:43 +0000820 unsigned ElementSize =
821 TD->getABITypeSize(CP->getType()->getElementType());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000822 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
823 WorkList.push_back(CPair(CP->getOperand(i), PA+i*ElementSize));
824 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(PC)) {
825 //
826 // FIXME: Handle ConstantExpression. See EE::getConstantValue()
827 //
828 switch (CE->getOpcode()) {
Nate Begeman6635f352007-01-26 22:39:48 +0000829 case Instruction::GetElementPtr: {
Chris Lattner7f6b9d22007-02-10 20:31:59 +0000830 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Nate Begeman6635f352007-01-26 22:39:48 +0000831 ScatteredOffset = TD->getIndexedOffset(CE->getOperand(0)->getType(),
Chris Lattner7f6b9d22007-02-10 20:31:59 +0000832 &Indices[0], Indices.size());
Nate Begeman6635f352007-01-26 22:39:48 +0000833 WorkList.push_back(CPair(CE->getOperand(0), PA));
834 break;
835 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000836 case Instruction::Add:
837 default:
838 cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
839 abort();
840 break;
841 }
842 } else if (PC->getType()->isFirstClassType()) {
843 unsigned char *ptr = (unsigned char *)PA;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000844 switch (PC->getType()->getTypeID()) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000845 case Type::IntegerTyID: {
846 unsigned NumBits = cast<IntegerType>(PC->getType())->getBitWidth();
847 uint64_t val = cast<ConstantInt>(PC)->getZExtValue();
848 if (NumBits <= 8)
849 ptr[0] = val;
850 else if (NumBits <= 16) {
851 if (TD->isBigEndian())
852 val = ByteSwap_16(val);
853 ptr[0] = val;
854 ptr[1] = val >> 8;
855 } else if (NumBits <= 32) {
856 if (TD->isBigEndian())
857 val = ByteSwap_32(val);
858 ptr[0] = val;
859 ptr[1] = val >> 8;
860 ptr[2] = val >> 16;
861 ptr[3] = val >> 24;
862 } else if (NumBits <= 64) {
863 if (TD->isBigEndian())
864 val = ByteSwap_64(val);
865 ptr[0] = val;
866 ptr[1] = val >> 8;
867 ptr[2] = val >> 16;
868 ptr[3] = val >> 24;
869 ptr[4] = val >> 32;
870 ptr[5] = val >> 40;
871 ptr[6] = val >> 48;
872 ptr[7] = val >> 56;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000873 } else {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000874 assert(0 && "Not implemented: bit widths > 64");
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000875 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000876 break;
877 }
878 case Type::FloatTyID: {
Dale Johannesen9d5f4562007-09-12 03:30:33 +0000879 uint32_t val = cast<ConstantFP>(PC)->getValueAPF().convertToAPInt().
880 getZExtValue();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000881 if (TD->isBigEndian())
882 val = ByteSwap_32(val);
883 ptr[0] = val;
884 ptr[1] = val >> 8;
885 ptr[2] = val >> 16;
886 ptr[3] = val >> 24;
887 break;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000888 }
889 case Type::DoubleTyID: {
Dale Johannesen9d5f4562007-09-12 03:30:33 +0000890 uint64_t val = cast<ConstantFP>(PC)->getValueAPF().convertToAPInt().
891 getZExtValue();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000892 if (TD->isBigEndian())
893 val = ByteSwap_64(val);
894 ptr[0] = val;
895 ptr[1] = val >> 8;
896 ptr[2] = val >> 16;
897 ptr[3] = val >> 24;
898 ptr[4] = val >> 32;
899 ptr[5] = val >> 40;
900 ptr[6] = val >> 48;
901 ptr[7] = val >> 56;
902 break;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000903 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000904 case Type::PointerTyID:
Nate Begeman6635f352007-01-26 22:39:48 +0000905 if (isa<ConstantPointerNull>(PC))
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000906 memset(ptr, 0, TD->getPointerSize());
Nate Begeman6635f352007-01-26 22:39:48 +0000907 else if (const GlobalValue* GV = dyn_cast<GlobalValue>(PC)) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000908 // FIXME: what about function stubs?
909 MRs.push_back(MachineRelocation::getGV(PA-(intptr_t)Addr,
910 MachineRelocation::VANILLA,
Nate Begeman6635f352007-01-26 22:39:48 +0000911 const_cast<GlobalValue*>(GV),
912 ScatteredOffset));
913 ScatteredOffset = 0;
914 } else
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000915 assert(0 && "Unknown constant pointer type!");
916 break;
917 default:
918 cerr << "ERROR: Constant unimp for type: " << *PC->getType() << "\n";
919 abort();
920 }
921 } else if (isa<ConstantAggregateZero>(PC)) {
Duncan Sandsca0ed742007-11-05 00:04:43 +0000922 memset((void*)PA, 0, (size_t)TD->getABITypeSize(PC->getType()));
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000923 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(PC)) {
Duncan Sandsca0ed742007-11-05 00:04:43 +0000924 unsigned ElementSize =
925 TD->getABITypeSize(CPA->getType()->getElementType());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000926 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
927 WorkList.push_back(CPair(CPA->getOperand(i), PA+i*ElementSize));
928 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(PC)) {
929 const StructLayout *SL =
930 TD->getStructLayout(cast<StructType>(CPS->getType()));
931 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
Chris Lattnerb1919e22007-02-10 19:55:17 +0000932 WorkList.push_back(CPair(CPS->getOperand(i),
933 PA+SL->getElementOffset(i)));
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000934 } else {
935 cerr << "Bad Type: " << *PC->getType() << "\n";
936 assert(0 && "Unknown constant type to initialize memory with!");
937 }
938 }
939}
940
941MachOSym::MachOSym(const GlobalValue *gv, std::string name, uint8_t sect,
942 TargetMachine &TM) :
943 GV(gv), n_strx(0), n_type(sect == NO_SECT ? N_UNDF : N_SECT), n_sect(sect),
944 n_desc(0), n_value(0) {
945
946 const TargetAsmInfo *TAI = TM.getTargetAsmInfo();
947
Nate Begeman94be2482006-09-08 22:42:09 +0000948 switch (GV->getLinkage()) {
949 default:
950 assert(0 && "Unexpected linkage type!");
951 break;
952 case GlobalValue::WeakLinkage:
953 case GlobalValue::LinkOnceLinkage:
954 assert(!isa<Function>(gv) && "Unexpected linkage type for Function!");
955 case GlobalValue::ExternalLinkage:
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000956 GVName = TAI->getGlobalPrefix() + name;
Nate Begeman6635f352007-01-26 22:39:48 +0000957 n_type |= GV->hasHiddenVisibility() ? N_PEXT : N_EXT;
Nate Begeman94be2482006-09-08 22:42:09 +0000958 break;
959 case GlobalValue::InternalLinkage:
Nate Begeman6635f352007-01-26 22:39:48 +0000960 GVName = TAI->getGlobalPrefix() + name;
Nate Begeman94be2482006-09-08 22:42:09 +0000961 break;
962 }
963}