blob: d2e87917afb84725e8c2629c978b833975f1ed7a [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"
Owen Andersoncb371882008-08-21 00:14:44 +000040#include "llvm/Support/raw_ostream.h"
Nate Begemand2030e62006-08-26 15:46:34 +000041#include <algorithm>
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +000042#include <cstring>
Nate Begemaneb883af2006-08-23 21:08:52 +000043using namespace llvm;
44
Bill Wendling8f84f1f2007-02-08 01:35:27 +000045/// AddMachOWriter - Concrete function to add the Mach-O writer to the function
46/// pass manager.
Dan Gohmanbfae8312008-03-11 22:29:46 +000047MachineCodeEmitter *llvm::AddMachOWriter(PassManagerBase &PM,
Owen Andersoncb371882008-08-21 00:14:44 +000048 raw_ostream &O,
Bill Wendling8f84f1f2007-02-08 01:35:27 +000049 TargetMachine &TM) {
50 MachOWriter *MOW = new MachOWriter(O, TM);
Dan Gohmanbfae8312008-03-11 22:29:46 +000051 PM.add(MOW);
Bill Wendling8f84f1f2007-02-08 01:35:27 +000052 return &MOW->getMachineCodeEmitter();
53}
54
Nate Begemaneb883af2006-08-23 21:08:52 +000055//===----------------------------------------------------------------------===//
56// MachOCodeEmitter Implementation
57//===----------------------------------------------------------------------===//
58
59namespace llvm {
60 /// MachOCodeEmitter - This class is used by the MachOWriter to emit the code
61 /// for functions to the Mach-O file.
62 class MachOCodeEmitter : public MachineCodeEmitter {
63 MachOWriter &MOW;
Nate Begemaneb883af2006-08-23 21:08:52 +000064
Bill Wendling203d3e42007-01-17 22:22:31 +000065 /// Target machine description.
66 TargetMachine &TM;
67
Bill Wendlingc904a5b2007-01-18 01:23:11 +000068 /// is64Bit/isLittleEndian - This information is inferred from the target
69 /// machine directly, indicating what header values and flags to set.
70 bool is64Bit, isLittleEndian;
71
Nate Begemaneb883af2006-08-23 21:08:52 +000072 /// Relocations - These are the relocations that the function needs, as
73 /// emitted.
74 std::vector<MachineRelocation> Relocations;
Nate Begeman019f8512006-09-10 23:03:44 +000075
76 /// CPLocations - This is a map of constant pool indices to offsets from the
77 /// start of the section for that constant pool index.
Evan Cheng5788d1a2008-12-10 02:32:19 +000078 std::vector<uintptr_t> CPLocations;
Nate Begeman019f8512006-09-10 23:03:44 +000079
Nate Begemanbfaaaa62006-12-11 02:20:45 +000080 /// CPSections - This is a map of constant pool indices to the MachOSection
81 /// containing the constant pool entry for that index.
82 std::vector<unsigned> CPSections;
83
Nate Begeman019f8512006-09-10 23:03:44 +000084 /// JTLocations - This is a map of jump table indices to offsets from the
85 /// start of the section for that jump table index.
Evan Cheng5788d1a2008-12-10 02:32:19 +000086 std::vector<uintptr_t> JTLocations;
Nate Begemaneb883af2006-08-23 21:08:52 +000087
88 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
89 /// It is filled in by the StartMachineBasicBlock callback and queried by
90 /// the getMachineBasicBlockAddress callback.
Evan Cheng5788d1a2008-12-10 02:32:19 +000091 std::vector<uintptr_t> MBBLocations;
Nate Begemaneb883af2006-08-23 21:08:52 +000092
93 public:
Bill Wendlingc904a5b2007-01-18 01:23:11 +000094 MachOCodeEmitter(MachOWriter &mow) : MOW(mow), TM(MOW.TM) {
95 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
96 isLittleEndian = TM.getTargetData()->isLittleEndian();
97 }
Nate Begemaneb883af2006-08-23 21:08:52 +000098
Nate Begemanc2b2d6a2007-02-07 05:47:16 +000099 virtual void startFunction(MachineFunction &MF);
100 virtual bool finishFunction(MachineFunction &MF);
Nate Begemaneb883af2006-08-23 21:08:52 +0000101
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000102 virtual void addRelocation(const MachineRelocation &MR) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000103 Relocations.push_back(MR);
104 }
105
Nate Begeman019f8512006-09-10 23:03:44 +0000106 void emitConstantPool(MachineConstantPool *MCP);
107 void emitJumpTables(MachineJumpTableInfo *MJTI);
108
Evan Cheng5788d1a2008-12-10 02:32:19 +0000109 virtual uintptr_t getConstantPoolEntryAddress(unsigned Index) const {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000110 assert(CPLocations.size() > Index && "CP not emitted!");
Nate Begemana0a62782007-02-28 09:16:38 +0000111 return CPLocations[Index];
Nate Begemaneb883af2006-08-23 21:08:52 +0000112 }
Evan Cheng5788d1a2008-12-10 02:32:19 +0000113 virtual uintptr_t getJumpTableEntryAddress(unsigned Index) const {
Nate Begeman019f8512006-09-10 23:03:44 +0000114 assert(JTLocations.size() > Index && "JT not emitted!");
115 return JTLocations[Index];
116 }
117
118 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
119 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
120 MBBLocations.resize((MBB->getNumber()+1)*2);
121 MBBLocations[MBB->getNumber()] = getCurrentPCOffset();
Nate Begemaneb883af2006-08-23 21:08:52 +0000122 }
123
Evan Cheng5788d1a2008-12-10 02:32:19 +0000124 virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
Nate Begemaneb883af2006-08-23 21:08:52 +0000125 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
126 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
127 return MBBLocations[MBB->getNumber()];
128 }
129
Evan Cheng5788d1a2008-12-10 02:32:19 +0000130 virtual uintptr_t getLabelAddress(uint64_t Label) const {
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000131 assert(0 && "get Label not implemented");
132 abort();
133 return 0;
134 }
135
136 virtual void emitLabel(uint64_t LabelID) {
137 assert(0 && "emit Label not implemented");
138 abort();
139 }
140
141
142 virtual void setModuleInfo(llvm::MachineModuleInfo* MMI) { }
143
Nate Begemaneb883af2006-08-23 21:08:52 +0000144 /// JIT SPECIFIC FUNCTIONS - DO NOT IMPLEMENT THESE HERE!
Evan Chengce4a70b2008-11-08 08:02:53 +0000145 virtual void startGVStub(const GlobalValue* F, unsigned StubSize,
146 unsigned Alignment = 1) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000147 assert(0 && "JIT specific function called!");
148 abort();
149 }
Nate Begemand6b7a242009-02-18 08:31:02 +0000150 virtual void startGVStub(const GlobalValue* F, void *Buffer,
151 unsigned StubSize) {
152 assert(0 && "JIT specific function called!");
153 abort();
154 }
Evan Chengce4a70b2008-11-08 08:02:53 +0000155 virtual void *finishGVStub(const GlobalValue* F) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000156 assert(0 && "JIT specific function called!");
157 abort();
158 return 0;
159 }
160 };
161}
162
163/// startFunction - This callback is invoked when a new machine function is
164/// about to be emitted.
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000165void MachOCodeEmitter::startFunction(MachineFunction &MF) {
166 const TargetData *TD = TM.getTargetData();
167 const Function *F = MF.getFunction();
168
Nate Begemaneb883af2006-08-23 21:08:52 +0000169 // Align the output buffer to the appropriate alignment, power of 2.
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000170 unsigned FnAlign = F->getAlignment();
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000171 unsigned TDAlign = TD->getPrefTypeAlignment(F->getType());
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000172 unsigned Align = Log2_32(std::max(FnAlign, TDAlign));
173 assert(!(Align & (Align-1)) && "Alignment is not a power of two!");
Nate Begemaneb883af2006-08-23 21:08:52 +0000174
175 // Get the Mach-O Section that this function belongs in.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000176 MachOWriter::MachOSection *MOS = MOW.getTextSection();
Nate Begemaneb883af2006-08-23 21:08:52 +0000177
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000178 // FIXME: better memory management
Nate Begemaneb883af2006-08-23 21:08:52 +0000179 MOS->SectionData.reserve(4096);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000180 BufferBegin = &MOS->SectionData[0];
Nate Begemaneb883af2006-08-23 21:08:52 +0000181 BufferEnd = BufferBegin + MOS->SectionData.capacity();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000182
Nate Begeman6635f352007-01-26 22:39:48 +0000183 // Upgrade the section alignment if required.
184 if (MOS->align < Align) MOS->align = Align;
185
186 // Round the size up to the correct alignment for starting the new function.
187 if ((MOS->size & ((1 << Align) - 1)) != 0) {
188 MOS->size += (1 << Align);
189 MOS->size &= ~((1 << Align) - 1);
190 }
191
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000192 // FIXME: Using MOS->size directly here instead of calculating it from the
193 // output buffer size (impossible because the code emitter deals only in raw
194 // bytes) forces us to manually synchronize size and write padding zero bytes
195 // to the output buffer for all non-text sections. For text sections, we do
196 // not synchonize the output buffer, and we just blow up if anyone tries to
197 // write non-code to it. An assert should probably be added to
198 // AddSymbolToSection to prevent calling it on the text section.
Nate Begemaneb883af2006-08-23 21:08:52 +0000199 CurBufferPtr = BufferBegin + MOS->size;
200
Nate Begeman019f8512006-09-10 23:03:44 +0000201 // Clear per-function data structures.
202 CPLocations.clear();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000203 CPSections.clear();
Nate Begeman019f8512006-09-10 23:03:44 +0000204 JTLocations.clear();
Nate Begemaneb883af2006-08-23 21:08:52 +0000205 MBBLocations.clear();
206}
207
208/// finishFunction - This callback is invoked after the function is completely
209/// finished.
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000210bool MachOCodeEmitter::finishFunction(MachineFunction &MF) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000211 // Get the Mach-O Section that this function belongs in.
212 MachOWriter::MachOSection *MOS = MOW.getTextSection();
213
Nate Begemaneb883af2006-08-23 21:08:52 +0000214 // Get a symbol for the function to add to the symbol table
Nate Begeman6635f352007-01-26 22:39:48 +0000215 // FIXME: it seems like we should call something like AddSymbolToSection
216 // in startFunction rather than changing the section size and symbol n_value
217 // here.
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000218 const GlobalValue *FuncV = MF.getFunction();
Bill Wendling203d3e42007-01-17 22:22:31 +0000219 MachOSym FnSym(FuncV, MOW.Mang->getValueName(FuncV), MOS->Index, TM);
Nate Begeman6635f352007-01-26 22:39:48 +0000220 FnSym.n_value = MOS->size;
221 MOS->size = CurBufferPtr - BufferBegin;
222
Nate Begeman019f8512006-09-10 23:03:44 +0000223 // Emit constant pool to appropriate section(s)
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000224 emitConstantPool(MF.getConstantPool());
Nate Begeman019f8512006-09-10 23:03:44 +0000225
226 // Emit jump tables to appropriate section
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000227 emitJumpTables(MF.getJumpTableInfo());
Nate Begemaneb883af2006-08-23 21:08:52 +0000228
Nate Begeman019f8512006-09-10 23:03:44 +0000229 // If we have emitted any relocations to function-specific objects such as
230 // basic blocks, constant pools entries, or jump tables, record their
231 // addresses now so that we can rewrite them with the correct addresses
232 // later.
Nate Begemaneb883af2006-08-23 21:08:52 +0000233 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
234 MachineRelocation &MR = Relocations[i];
Nate Begeman019f8512006-09-10 23:03:44 +0000235 intptr_t Addr;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000236
Nate Begemaneb883af2006-08-23 21:08:52 +0000237 if (MR.isBasicBlock()) {
Nate Begeman019f8512006-09-10 23:03:44 +0000238 Addr = getMachineBasicBlockAddress(MR.getBasicBlock());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000239 MR.setConstantVal(MOS->Index);
240 MR.setResultPointer((void*)Addr);
241 } else if (MR.isJumpTableIndex()) {
242 Addr = getJumpTableEntryAddress(MR.getJumpTableIndex());
243 MR.setConstantVal(MOW.getJumpTableSection()->Index);
244 MR.setResultPointer((void*)Addr);
Nate Begeman019f8512006-09-10 23:03:44 +0000245 } else if (MR.isConstantPoolIndex()) {
246 Addr = getConstantPoolEntryAddress(MR.getConstantPoolIndex());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000247 MR.setConstantVal(CPSections[MR.getConstantPoolIndex()]);
248 MR.setResultPointer((void*)Addr);
Nate Begemanfec910c2007-02-28 07:40:50 +0000249 } else if (MR.isGlobalValue()) {
250 // FIXME: This should be a set or something that uniques
251 MOW.PendingGlobals.push_back(MR.getGlobalValue());
252 } else {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000253 assert(0 && "Unhandled relocation type");
Nate Begemaneb883af2006-08-23 21:08:52 +0000254 }
Nate Begeman019f8512006-09-10 23:03:44 +0000255 MOS->Relocations.push_back(MR);
Nate Begemaneb883af2006-08-23 21:08:52 +0000256 }
257 Relocations.clear();
258
259 // Finally, add it to the symtab.
260 MOW.SymbolTable.push_back(FnSym);
261 return false;
262}
263
Nate Begeman019f8512006-09-10 23:03:44 +0000264/// emitConstantPool - For each constant pool entry, figure out which section
265/// the constant should live in, allocate space for it, and emit it to the
266/// Section data buffer.
267void MachOCodeEmitter::emitConstantPool(MachineConstantPool *MCP) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000268 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
269 if (CP.empty()) return;
270
271 // FIXME: handle PIC codegen
Chris Lattnera33649e2008-12-19 17:03:38 +0000272 assert(TM.getRelocationModel() != Reloc::PIC_ &&
273 "PIC codegen not yet handled for mach-o jump tables!");
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000274
275 // Although there is no strict necessity that I am aware of, we will do what
276 // gcc for OS X does and put each constant pool entry in a section of constant
277 // objects of a certain size. That means that float constants go in the
278 // literal4 section, and double objects go in literal8, etc.
279 //
280 // FIXME: revisit this decision if we ever do the "stick everything into one
281 // "giant object for PIC" optimization.
282 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
283 const Type *Ty = CP[i].getType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000284 unsigned Size = TM.getTargetData()->getTypePaddedSize(Ty);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000285
Nate Begeman1257c852007-01-29 21:20:42 +0000286 MachOWriter::MachOSection *Sec = MOW.getConstSection(CP[i].Val.ConstVal);
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000287 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000288
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000289 CPLocations.push_back(Sec->SectionData.size());
290 CPSections.push_back(Sec->Index);
291
292 // FIXME: remove when we have unified size + output buffer
293 Sec->size += Size;
294
295 // Allocate space in the section for the global.
296 // FIXME: need alignment?
297 // FIXME: share between here and AddSymbolToSection?
298 for (unsigned j = 0; j < Size; ++j)
Bill Wendling203d3e42007-01-17 22:22:31 +0000299 SecDataOut.outbyte(0);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000300
301 MOW.InitMem(CP[i].Val.ConstVal, &Sec->SectionData[0], CPLocations[i],
Bill Wendling203d3e42007-01-17 22:22:31 +0000302 TM.getTargetData(), Sec->Relocations);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000303 }
Nate Begeman019f8512006-09-10 23:03:44 +0000304}
305
306/// emitJumpTables - Emit all the jump tables for a given jump table info
307/// record to the appropriate section.
308void MachOCodeEmitter::emitJumpTables(MachineJumpTableInfo *MJTI) {
309 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
310 if (JT.empty()) return;
311
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000312 // FIXME: handle PIC codegen
Chris Lattnera33649e2008-12-19 17:03:38 +0000313 assert(TM.getRelocationModel() != Reloc::PIC_ &&
314 "PIC codegen not yet handled for mach-o jump tables!");
Nate Begeman019f8512006-09-10 23:03:44 +0000315
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000316 MachOWriter::MachOSection *Sec = MOW.getJumpTableSection();
317 unsigned TextSecIndex = MOW.getTextSection()->Index;
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000318 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
Nate Begeman019f8512006-09-10 23:03:44 +0000319
320 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
321 // For each jump table, record its offset from the start of the section,
322 // reserve space for the relocations to the MBBs, and add the relocations.
323 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000324 JTLocations.push_back(Sec->SectionData.size());
Nate Begeman019f8512006-09-10 23:03:44 +0000325 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000326 MachineRelocation MR(MOW.GetJTRelocation(Sec->SectionData.size(),
Nate Begeman019f8512006-09-10 23:03:44 +0000327 MBBs[mi]));
328 MR.setResultPointer((void *)JTLocations[i]);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000329 MR.setConstantVal(TextSecIndex);
330 Sec->Relocations.push_back(MR);
Bill Wendling203d3e42007-01-17 22:22:31 +0000331 SecDataOut.outaddr(0);
Nate Begeman019f8512006-09-10 23:03:44 +0000332 }
333 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000334 // FIXME: remove when we have unified size + output buffer
335 Sec->size = Sec->SectionData.size();
Nate Begeman019f8512006-09-10 23:03:44 +0000336}
337
Nate Begemaneb883af2006-08-23 21:08:52 +0000338//===----------------------------------------------------------------------===//
339// MachOWriter Implementation
340//===----------------------------------------------------------------------===//
341
Devang Patel19974732007-05-03 01:11:54 +0000342char MachOWriter::ID = 0;
Owen Andersoncb371882008-08-21 00:14:44 +0000343MachOWriter::MachOWriter(raw_ostream &o, TargetMachine &tm)
Dan Gohmanae73dc12008-09-04 17:05:41 +0000344 : MachineFunctionPass(&ID), O(o), TM(tm) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000345 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
346 isLittleEndian = TM.getTargetData()->isLittleEndian();
347
348 // Create the machine code emitter object for this target.
Bill Wendlinge9116152007-01-17 09:06:13 +0000349 MCE = new MachOCodeEmitter(*this);
Nate Begemaneb883af2006-08-23 21:08:52 +0000350}
351
352MachOWriter::~MachOWriter() {
353 delete MCE;
354}
355
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000356void MachOWriter::AddSymbolToSection(MachOSection *Sec, GlobalVariable *GV) {
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000357 const Type *Ty = GV->getType()->getElementType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000358 unsigned Size = TM.getTargetData()->getTypePaddedSize(Ty);
Duncan Sandsd1025932008-01-29 06:23:44 +0000359 unsigned Align = TM.getTargetData()->getPreferredAlignment(GV);
360
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000361 // Reserve space in the .bss section for this symbol while maintaining the
362 // desired section alignment, which must be at least as much as required by
363 // this symbol.
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000364 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000365
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000366 if (Align) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000367 uint64_t OrigSize = Sec->size;
368 Align = Log2_32(Align);
369 Sec->align = std::max(unsigned(Sec->align), Align);
370 Sec->size = (Sec->size + Align - 1) & ~(Align-1);
371
372 // Add alignment padding to buffer as well.
373 // FIXME: remove when we have unified size + output buffer
374 unsigned AlignedSize = Sec->size - OrigSize;
375 for (unsigned i = 0; i < AlignedSize; ++i)
Bill Wendling203d3e42007-01-17 22:22:31 +0000376 SecDataOut.outbyte(0);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000377 }
Nate Begemanfec910c2007-02-28 07:40:50 +0000378 // Globals without external linkage apparently do not go in the symbol table.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000379 if (!GV->hasLocalLinkage()) {
Nate Begemanfec910c2007-02-28 07:40:50 +0000380 MachOSym Sym(GV, Mang->getValueName(GV), Sec->Index, TM);
381 Sym.n_value = Sec->size;
382 SymbolTable.push_back(Sym);
383 }
384
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000385 // Record the offset of the symbol, and then allocate space for it.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000386 // FIXME: remove when we have unified size + output buffer
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000387 Sec->size += Size;
Nate Begemanfec910c2007-02-28 07:40:50 +0000388
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000389 // Now that we know what section the GlovalVariable is going to be emitted
390 // into, update our mappings.
391 // FIXME: We may also need to update this when outputting non-GlobalVariable
392 // GlobalValues such as functions.
393 GVSection[GV] = Sec;
394 GVOffset[GV] = Sec->SectionData.size();
395
396 // Allocate space in the section for the global.
397 for (unsigned i = 0; i < Size; ++i)
Bill Wendling203d3e42007-01-17 22:22:31 +0000398 SecDataOut.outbyte(0);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000399}
400
Nate Begemaneb883af2006-08-23 21:08:52 +0000401void MachOWriter::EmitGlobal(GlobalVariable *GV) {
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000402 const Type *Ty = GV->getType()->getElementType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000403 unsigned Size = TM.getTargetData()->getTypePaddedSize(Ty);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000404 bool NoInit = !GV->hasInitializer();
Nate Begemand2030e62006-08-26 15:46:34 +0000405
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000406 // If this global has a zero initializer, it is part of the .bss or common
407 // section.
408 if (NoInit || GV->getInitializer()->isNullValue()) {
409 // If this global is part of the common block, add it now. Variables are
410 // part of the common block if they are zero initialized and allowed to be
411 // merged with other symbols.
Dale Johannesenaafce772008-05-14 20:12:51 +0000412 if (NoInit || GV->hasLinkOnceLinkage() || GV->hasWeakLinkage() ||
413 GV->hasCommonLinkage()) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000414 MachOSym ExtOrCommonSym(GV, Mang->getValueName(GV), MachOSym::NO_SECT,TM);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000415 // For undefined (N_UNDF) external (N_EXT) types, n_value is the size in
416 // bytes of the symbol.
417 ExtOrCommonSym.n_value = Size;
Nate Begemanfec910c2007-02-28 07:40:50 +0000418 SymbolTable.push_back(ExtOrCommonSym);
419 // Remember that we've seen this symbol
420 GVOffset[GV] = Size;
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000421 return;
422 }
423 // Otherwise, this symbol is part of the .bss section.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000424 MachOSection *BSS = getBSSSection();
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000425 AddSymbolToSection(BSS, GV);
426 return;
427 }
428
429 // Scalar read-only data goes in a literal section if the scalar is 4, 8, or
430 // 16 bytes, or a cstring. Other read only data goes into a regular const
431 // section. Read-write data goes in the data section.
Nate Begeman1257c852007-01-29 21:20:42 +0000432 MachOSection *Sec = GV->isConstant() ? getConstSection(GV->getInitializer()) :
433 getDataSection();
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000434 AddSymbolToSection(Sec, GV);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000435 InitMem(GV->getInitializer(), &Sec->SectionData[0], GVOffset[GV],
436 TM.getTargetData(), Sec->Relocations);
Nate Begemaneb883af2006-08-23 21:08:52 +0000437}
438
439
440bool MachOWriter::runOnMachineFunction(MachineFunction &MF) {
441 // Nothing to do here, this is all done through the MCE object.
442 return false;
443}
444
445bool MachOWriter::doInitialization(Module &M) {
446 // Set the magic value, now that we know the pointer size and endianness
447 Header.setMagic(isLittleEndian, is64Bit);
448
449 // Set the file type
450 // FIXME: this only works for object files, we do not support the creation
451 // of dynamic libraries or executables at this time.
452 Header.filetype = MachOHeader::MH_OBJECT;
453
454 Mang = new Mangler(M);
455 return false;
456}
457
458/// doFinalization - Now that the module has been completely processed, emit
459/// the Mach-O file to 'O'.
460bool MachOWriter::doFinalization(Module &M) {
Nate Begemand2030e62006-08-26 15:46:34 +0000461 // FIXME: we don't handle debug info yet, we should probably do that.
462
Nate Begemaneb883af2006-08-23 21:08:52 +0000463 // Okay, the.text section has been completed, build the .data, .bss, and
464 // "common" sections next.
465 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
466 I != E; ++I)
467 EmitGlobal(I);
468
469 // Emit the header and load commands.
470 EmitHeaderAndLoadCommands();
471
Nate Begeman019f8512006-09-10 23:03:44 +0000472 // Emit the various sections and their relocation info.
Nate Begemaneb883af2006-08-23 21:08:52 +0000473 EmitSections();
474
Nate Begemand2030e62006-08-26 15:46:34 +0000475 // Write the symbol table and the string table to the end of the file.
476 O.write((char*)&SymT[0], SymT.size());
477 O.write((char*)&StrT[0], StrT.size());
Nate Begemaneb883af2006-08-23 21:08:52 +0000478
479 // We are done with the abstract symbols.
480 SectionList.clear();
481 SymbolTable.clear();
482 DynamicSymbolTable.clear();
483
484 // Release the name mangler object.
485 delete Mang; Mang = 0;
486 return false;
487}
488
489void MachOWriter::EmitHeaderAndLoadCommands() {
490 // Step #0: Fill in the segment load command size, since we need it to figure
491 // out the rest of the header fields
492 MachOSegment SEG("", is64Bit);
493 SEG.nsects = SectionList.size();
494 SEG.cmdsize = SEG.cmdSize(is64Bit) +
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000495 SEG.nsects * SectionList[0]->cmdSize(is64Bit);
Nate Begemaneb883af2006-08-23 21:08:52 +0000496
497 // Step #1: calculate the number of load commands. We always have at least
498 // one, for the LC_SEGMENT load command, plus two for the normal
499 // and dynamic symbol tables, if there are any symbols.
500 Header.ncmds = SymbolTable.empty() ? 1 : 3;
501
502 // Step #2: calculate the size of the load commands
503 Header.sizeofcmds = SEG.cmdsize;
504 if (!SymbolTable.empty())
505 Header.sizeofcmds += SymTab.cmdsize + DySymTab.cmdsize;
506
507 // Step #3: write the header to the file
508 // Local alias to shortenify coming code.
509 DataBuffer &FH = Header.HeaderData;
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000510 OutputBuffer FHOut(FH, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000511
512 FHOut.outword(Header.magic);
Bill Wendling2b721822007-01-24 07:13:56 +0000513 FHOut.outword(TM.getMachOWriterInfo()->getCPUType());
514 FHOut.outword(TM.getMachOWriterInfo()->getCPUSubType());
Bill Wendling203d3e42007-01-17 22:22:31 +0000515 FHOut.outword(Header.filetype);
516 FHOut.outword(Header.ncmds);
517 FHOut.outword(Header.sizeofcmds);
518 FHOut.outword(Header.flags);
Nate Begemaneb883af2006-08-23 21:08:52 +0000519 if (is64Bit)
Bill Wendling203d3e42007-01-17 22:22:31 +0000520 FHOut.outword(Header.reserved);
Nate Begemaneb883af2006-08-23 21:08:52 +0000521
522 // Step #4: Finish filling in the segment load command and write it out
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000523 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begemaneb883af2006-08-23 21:08:52 +0000524 E = SectionList.end(); I != E; ++I)
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000525 SEG.filesize += (*I)->size;
526
Nate Begemaneb883af2006-08-23 21:08:52 +0000527 SEG.vmsize = SEG.filesize;
528 SEG.fileoff = Header.cmdSize(is64Bit) + Header.sizeofcmds;
529
Bill Wendling203d3e42007-01-17 22:22:31 +0000530 FHOut.outword(SEG.cmd);
531 FHOut.outword(SEG.cmdsize);
532 FHOut.outstring(SEG.segname, 16);
533 FHOut.outaddr(SEG.vmaddr);
534 FHOut.outaddr(SEG.vmsize);
535 FHOut.outaddr(SEG.fileoff);
536 FHOut.outaddr(SEG.filesize);
537 FHOut.outword(SEG.maxprot);
538 FHOut.outword(SEG.initprot);
539 FHOut.outword(SEG.nsects);
540 FHOut.outword(SEG.flags);
Nate Begemaneb883af2006-08-23 21:08:52 +0000541
Nate Begeman94be2482006-09-08 22:42:09 +0000542 // Step #5: Finish filling in the fields of the MachOSections
543 uint64_t currentAddr = 0;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000544 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begemaneb883af2006-08-23 21:08:52 +0000545 E = SectionList.end(); I != E; ++I) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000546 MachOSection *MOS = *I;
547 MOS->addr = currentAddr;
548 MOS->offset = currentAddr + SEG.fileoff;
Nate Begeman019f8512006-09-10 23:03:44 +0000549
Nate Begeman94be2482006-09-08 22:42:09 +0000550 // FIXME: do we need to do something with alignment here?
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000551 currentAddr += MOS->size;
Nate Begeman94be2482006-09-08 22:42:09 +0000552 }
553
Nate Begemanfec910c2007-02-28 07:40:50 +0000554 // Step #6: Emit the symbol table to temporary buffers, so that we know the
555 // size of the string table when we write the next load command. This also
556 // sorts and assigns indices to each of the symbols, which is necessary for
557 // emitting relocations to externally-defined objects.
558 BufferSymbolAndStringTable();
559
560 // Step #7: Calculate the number of relocations for each section and write out
Nate Begeman94be2482006-09-08 22:42:09 +0000561 // the section commands for each section
562 currentAddr += SEG.fileoff;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000563 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman94be2482006-09-08 22:42:09 +0000564 E = SectionList.end(); I != E; ++I) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000565 MachOSection *MOS = *I;
566 // Convert the relocations to target-specific relocations, and fill in the
567 // relocation offset for this section.
568 CalculateRelocations(*MOS);
569 MOS->reloff = MOS->nreloc ? currentAddr : 0;
570 currentAddr += MOS->nreloc * 8;
Nate Begeman94be2482006-09-08 22:42:09 +0000571
572 // write the finalized section command to the output buffer
Bill Wendling203d3e42007-01-17 22:22:31 +0000573 FHOut.outstring(MOS->sectname, 16);
574 FHOut.outstring(MOS->segname, 16);
575 FHOut.outaddr(MOS->addr);
576 FHOut.outaddr(MOS->size);
577 FHOut.outword(MOS->offset);
578 FHOut.outword(MOS->align);
579 FHOut.outword(MOS->reloff);
580 FHOut.outword(MOS->nreloc);
581 FHOut.outword(MOS->flags);
582 FHOut.outword(MOS->reserved1);
583 FHOut.outword(MOS->reserved2);
Nate Begemaneb883af2006-08-23 21:08:52 +0000584 if (is64Bit)
Bill Wendling203d3e42007-01-17 22:22:31 +0000585 FHOut.outword(MOS->reserved3);
Nate Begemaneb883af2006-08-23 21:08:52 +0000586 }
587
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000588 // Step #8: Emit LC_SYMTAB/LC_DYSYMTAB load commands
Nate Begeman94be2482006-09-08 22:42:09 +0000589 SymTab.symoff = currentAddr;
Nate Begemaneb883af2006-08-23 21:08:52 +0000590 SymTab.nsyms = SymbolTable.size();
Nate Begemand2030e62006-08-26 15:46:34 +0000591 SymTab.stroff = SymTab.symoff + SymT.size();
592 SymTab.strsize = StrT.size();
Bill Wendling203d3e42007-01-17 22:22:31 +0000593 FHOut.outword(SymTab.cmd);
594 FHOut.outword(SymTab.cmdsize);
595 FHOut.outword(SymTab.symoff);
596 FHOut.outword(SymTab.nsyms);
597 FHOut.outword(SymTab.stroff);
598 FHOut.outword(SymTab.strsize);
Nate Begemaneb883af2006-08-23 21:08:52 +0000599
600 // FIXME: set DySymTab fields appropriately
Nate Begemand2030e62006-08-26 15:46:34 +0000601 // We should probably just update these in BufferSymbolAndStringTable since
602 // thats where we're partitioning up the different kinds of symbols.
Bill Wendling203d3e42007-01-17 22:22:31 +0000603 FHOut.outword(DySymTab.cmd);
604 FHOut.outword(DySymTab.cmdsize);
605 FHOut.outword(DySymTab.ilocalsym);
606 FHOut.outword(DySymTab.nlocalsym);
607 FHOut.outword(DySymTab.iextdefsym);
608 FHOut.outword(DySymTab.nextdefsym);
609 FHOut.outword(DySymTab.iundefsym);
610 FHOut.outword(DySymTab.nundefsym);
611 FHOut.outword(DySymTab.tocoff);
612 FHOut.outword(DySymTab.ntoc);
613 FHOut.outword(DySymTab.modtaboff);
614 FHOut.outword(DySymTab.nmodtab);
615 FHOut.outword(DySymTab.extrefsymoff);
616 FHOut.outword(DySymTab.nextrefsyms);
617 FHOut.outword(DySymTab.indirectsymoff);
618 FHOut.outword(DySymTab.nindirectsyms);
619 FHOut.outword(DySymTab.extreloff);
620 FHOut.outword(DySymTab.nextrel);
621 FHOut.outword(DySymTab.locreloff);
622 FHOut.outword(DySymTab.nlocrel);
Nate Begemaneb883af2006-08-23 21:08:52 +0000623
624 O.write((char*)&FH[0], FH.size());
625}
626
627/// EmitSections - Now that we have constructed the file header and load
628/// commands, emit the data for each section to the file.
629void MachOWriter::EmitSections() {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000630 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman019f8512006-09-10 23:03:44 +0000631 E = SectionList.end(); I != E; ++I)
632 // Emit the contents of each section
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000633 O.write((char*)&(*I)->SectionData[0], (*I)->size);
634 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman019f8512006-09-10 23:03:44 +0000635 E = SectionList.end(); I != E; ++I)
636 // Emit the relocation entry data for each section.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000637 O.write((char*)&(*I)->RelocBuffer[0], (*I)->RelocBuffer.size());
Nate Begemaneb883af2006-08-23 21:08:52 +0000638}
639
Nate Begemand2030e62006-08-26 15:46:34 +0000640/// PartitionByLocal - Simple boolean predicate that returns true if Sym is
641/// a local symbol rather than an external symbol.
642bool MachOWriter::PartitionByLocal(const MachOSym &Sym) {
Nate Begemand2030e62006-08-26 15:46:34 +0000643 return (Sym.n_type & (MachOSym::N_EXT | MachOSym::N_PEXT)) == 0;
Nate Begemaneb883af2006-08-23 21:08:52 +0000644}
645
Nate Begemand2030e62006-08-26 15:46:34 +0000646/// PartitionByDefined - Simple boolean predicate that returns true if Sym is
647/// defined in this module.
648bool MachOWriter::PartitionByDefined(const MachOSym &Sym) {
649 // FIXME: Do N_ABS or N_INDR count as defined?
650 return (Sym.n_type & MachOSym::N_SECT) == MachOSym::N_SECT;
651}
Nate Begemaneb883af2006-08-23 21:08:52 +0000652
Nate Begemand2030e62006-08-26 15:46:34 +0000653/// BufferSymbolAndStringTable - Sort the symbols we encountered and assign them
654/// each a string table index so that they appear in the correct order in the
655/// output file.
656void MachOWriter::BufferSymbolAndStringTable() {
657 // The order of the symbol table is:
658 // 1. local symbols
659 // 2. defined external symbols (sorted by name)
660 // 3. undefined external symbols (sorted by name)
661
Nate Begemanfec910c2007-02-28 07:40:50 +0000662 // Before sorting the symbols, check the PendingGlobals for any undefined
663 // globals that need to be put in the symbol table.
664 for (std::vector<GlobalValue*>::iterator I = PendingGlobals.begin(),
665 E = PendingGlobals.end(); I != E; ++I) {
666 if (GVOffset[*I] == 0 && GVSection[*I] == 0) {
667 MachOSym UndfSym(*I, Mang->getValueName(*I), MachOSym::NO_SECT, TM);
668 SymbolTable.push_back(UndfSym);
669 GVOffset[*I] = -1;
670 }
671 }
672
Nate Begemand2030e62006-08-26 15:46:34 +0000673 // Sort the symbols by name, so that when we partition the symbols by scope
674 // of definition, we won't have to sort by name within each partition.
675 std::sort(SymbolTable.begin(), SymbolTable.end(), MachOSymCmp());
676
677 // Parition the symbol table entries so that all local symbols come before
678 // all symbols with external linkage. { 1 | 2 3 }
679 std::partition(SymbolTable.begin(), SymbolTable.end(), PartitionByLocal);
680
681 // Advance iterator to beginning of external symbols and partition so that
682 // all external symbols defined in this module come before all external
683 // symbols defined elsewhere. { 1 | 2 | 3 }
684 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
685 E = SymbolTable.end(); I != E; ++I) {
686 if (!PartitionByLocal(*I)) {
687 std::partition(I, E, PartitionByDefined);
688 break;
689 }
690 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000691
692 // Calculate the starting index for each of the local, extern defined, and
693 // undefined symbols, as well as the number of each to put in the LC_DYSYMTAB
694 // load command.
695 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
696 E = SymbolTable.end(); I != E; ++I) {
697 if (PartitionByLocal(*I)) {
698 ++DySymTab.nlocalsym;
699 ++DySymTab.iextdefsym;
Nate Begeman6635f352007-01-26 22:39:48 +0000700 ++DySymTab.iundefsym;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000701 } else if (PartitionByDefined(*I)) {
702 ++DySymTab.nextdefsym;
703 ++DySymTab.iundefsym;
704 } else {
705 ++DySymTab.nundefsym;
706 }
707 }
Nate Begemand2030e62006-08-26 15:46:34 +0000708
Nate Begemaneb883af2006-08-23 21:08:52 +0000709 // Write out a leading zero byte when emitting string table, for n_strx == 0
710 // which means an empty string.
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000711 OutputBuffer StrTOut(StrT, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000712 StrTOut.outbyte(0);
Nate Begemaneb883af2006-08-23 21:08:52 +0000713
Nate Begemand2030e62006-08-26 15:46:34 +0000714 // The order of the string table is:
715 // 1. strings for external symbols
716 // 2. strings for local symbols
717 // Since this is the opposite order from the symbol table, which we have just
718 // sorted, we can walk the symbol table backwards to output the string table.
719 for (std::vector<MachOSym>::reverse_iterator I = SymbolTable.rbegin(),
720 E = SymbolTable.rend(); I != E; ++I) {
721 if (I->GVName == "") {
722 I->n_strx = 0;
723 } else {
724 I->n_strx = StrT.size();
Bill Wendling203d3e42007-01-17 22:22:31 +0000725 StrTOut.outstring(I->GVName, I->GVName.length()+1);
Nate Begemand2030e62006-08-26 15:46:34 +0000726 }
Nate Begemaneb883af2006-08-23 21:08:52 +0000727 }
Nate Begemand2030e62006-08-26 15:46:34 +0000728
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000729 OutputBuffer SymTOut(SymT, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000730
Nate Begemanfec910c2007-02-28 07:40:50 +0000731 unsigned index = 0;
Nate Begemand2030e62006-08-26 15:46:34 +0000732 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
Nate Begemanfec910c2007-02-28 07:40:50 +0000733 E = SymbolTable.end(); I != E; ++I, ++index) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000734 // Add the section base address to the section offset in the n_value field
735 // to calculate the full address.
736 // FIXME: handle symbols where the n_value field is not the address
737 GlobalValue *GV = const_cast<GlobalValue*>(I->GV);
738 if (GV && GVSection[GV])
739 I->n_value += GVSection[GV]->addr;
Nate Begemanfec910c2007-02-28 07:40:50 +0000740 if (GV && (GVOffset[GV] == -1))
741 GVOffset[GV] = index;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000742
Nate Begemand2030e62006-08-26 15:46:34 +0000743 // Emit nlist to buffer
Bill Wendling203d3e42007-01-17 22:22:31 +0000744 SymTOut.outword(I->n_strx);
745 SymTOut.outbyte(I->n_type);
746 SymTOut.outbyte(I->n_sect);
747 SymTOut.outhalf(I->n_desc);
748 SymTOut.outaddr(I->n_value);
Nate Begemand2030e62006-08-26 15:46:34 +0000749 }
Nate Begemaneb883af2006-08-23 21:08:52 +0000750}
Nate Begeman94be2482006-09-08 22:42:09 +0000751
Nate Begeman019f8512006-09-10 23:03:44 +0000752/// CalculateRelocations - For each MachineRelocation in the current section,
753/// calculate the index of the section containing the object to be relocated,
754/// and the offset into that section. From this information, create the
755/// appropriate target-specific MachORelocation type and add buffer it to be
756/// written out after we are finished writing out sections.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000757void MachOWriter::CalculateRelocations(MachOSection &MOS) {
Nate Begeman019f8512006-09-10 23:03:44 +0000758 for (unsigned i = 0, e = MOS.Relocations.size(); i != e; ++i) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000759 MachineRelocation &MR = MOS.Relocations[i];
760 unsigned TargetSection = MR.getConstantVal();
Nate Begemanaf806382007-03-03 06:18:18 +0000761 unsigned TargetAddr = 0;
762 unsigned TargetIndex = 0;
Nate Begeman6635f352007-01-26 22:39:48 +0000763
764 // This is a scattered relocation entry if it points to a global value with
765 // a non-zero offset.
766 bool Scattered = false;
Nate Begemanfec910c2007-02-28 07:40:50 +0000767 bool Extern = false;
Nate Begemanaf806382007-03-03 06:18:18 +0000768
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000769 // Since we may not have seen the GlobalValue we were interested in yet at
770 // the time we emitted the relocation for it, fix it up now so that it
771 // points to the offset into the correct section.
772 if (MR.isGlobalValue()) {
773 GlobalValue *GV = MR.getGlobalValue();
774 MachOSection *MOSPtr = GVSection[GV];
Nate Begeman6635f352007-01-26 22:39:48 +0000775 intptr_t Offset = GVOffset[GV];
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000776
Nate Begemanfec910c2007-02-28 07:40:50 +0000777 // If we have never seen the global before, it must be to a symbol
778 // defined in another module (N_UNDF).
Nate Begeman1257c852007-01-29 21:20:42 +0000779 if (!MOSPtr) {
Nate Begemanfec910c2007-02-28 07:40:50 +0000780 // FIXME: need to append stub suffix
781 Extern = true;
782 TargetAddr = 0;
783 TargetIndex = GVOffset[GV];
784 } else {
785 Scattered = TargetSection != 0;
786 TargetSection = MOSPtr->Index;
Nate Begemanaf806382007-03-03 06:18:18 +0000787 }
788 MR.setResultPointer((void*)Offset);
789 }
790
791 // If the symbol is locally defined, pass in the address of the section and
792 // the section index to the code which will generate the target relocation.
793 if (!Extern) {
Nate Begemanfec910c2007-02-28 07:40:50 +0000794 MachOSection &To = *SectionList[TargetSection - 1];
795 TargetAddr = To.addr;
796 TargetIndex = To.Index;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000797 }
Bill Wendling886b4122007-02-03 02:39:40 +0000798
799 OutputBuffer RelocOut(MOS.RelocBuffer, is64Bit, isLittleEndian);
800 OutputBuffer SecOut(MOS.SectionData, is64Bit, isLittleEndian);
Nate Begemanfec910c2007-02-28 07:40:50 +0000801
802 MOS.nreloc += GetTargetRelocation(MR, MOS.Index, TargetAddr, TargetIndex,
803 RelocOut, SecOut, Scattered, Extern);
Nate Begeman019f8512006-09-10 23:03:44 +0000804 }
Nate Begeman019f8512006-09-10 23:03:44 +0000805}
806
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000807// InitMem - Write the value of a Constant to the specified memory location,
808// converting it into bytes and relocations.
809void MachOWriter::InitMem(const Constant *C, void *Addr, intptr_t Offset,
810 const TargetData *TD,
811 std::vector<MachineRelocation> &MRs) {
812 typedef std::pair<const Constant*, intptr_t> CPair;
813 std::vector<CPair> WorkList;
814
815 WorkList.push_back(CPair(C,(intptr_t)Addr + Offset));
816
Nate Begeman6635f352007-01-26 22:39:48 +0000817 intptr_t ScatteredOffset = 0;
818
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000819 while (!WorkList.empty()) {
820 const Constant *PC = WorkList.back().first;
821 intptr_t PA = WorkList.back().second;
822 WorkList.pop_back();
823
824 if (isa<UndefValue>(PC)) {
825 continue;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000826 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(PC)) {
Duncan Sandsca0ed742007-11-05 00:04:43 +0000827 unsigned ElementSize =
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000828 TD->getTypePaddedSize(CP->getType()->getElementType());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000829 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
830 WorkList.push_back(CPair(CP->getOperand(i), PA+i*ElementSize));
831 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(PC)) {
832 //
833 // FIXME: Handle ConstantExpression. See EE::getConstantValue()
834 //
835 switch (CE->getOpcode()) {
Nate Begeman6635f352007-01-26 22:39:48 +0000836 case Instruction::GetElementPtr: {
Chris Lattner7f6b9d22007-02-10 20:31:59 +0000837 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Nate Begeman6635f352007-01-26 22:39:48 +0000838 ScatteredOffset = TD->getIndexedOffset(CE->getOperand(0)->getType(),
Chris Lattner7f6b9d22007-02-10 20:31:59 +0000839 &Indices[0], Indices.size());
Nate Begeman6635f352007-01-26 22:39:48 +0000840 WorkList.push_back(CPair(CE->getOperand(0), PA));
841 break;
842 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000843 case Instruction::Add:
844 default:
845 cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
846 abort();
847 break;
848 }
Dan Gohman399101a2008-05-23 00:17:26 +0000849 } else if (PC->getType()->isSingleValueType()) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000850 unsigned char *ptr = (unsigned char *)PA;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000851 switch (PC->getType()->getTypeID()) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000852 case Type::IntegerTyID: {
853 unsigned NumBits = cast<IntegerType>(PC->getType())->getBitWidth();
854 uint64_t val = cast<ConstantInt>(PC)->getZExtValue();
855 if (NumBits <= 8)
856 ptr[0] = val;
857 else if (NumBits <= 16) {
858 if (TD->isBigEndian())
859 val = ByteSwap_16(val);
860 ptr[0] = val;
861 ptr[1] = val >> 8;
862 } else if (NumBits <= 32) {
863 if (TD->isBigEndian())
864 val = ByteSwap_32(val);
865 ptr[0] = val;
866 ptr[1] = val >> 8;
867 ptr[2] = val >> 16;
868 ptr[3] = val >> 24;
869 } else if (NumBits <= 64) {
870 if (TD->isBigEndian())
871 val = ByteSwap_64(val);
872 ptr[0] = val;
873 ptr[1] = val >> 8;
874 ptr[2] = val >> 16;
875 ptr[3] = val >> 24;
876 ptr[4] = val >> 32;
877 ptr[5] = val >> 40;
878 ptr[6] = val >> 48;
879 ptr[7] = val >> 56;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000880 } else {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000881 assert(0 && "Not implemented: bit widths > 64");
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000882 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000883 break;
884 }
885 case Type::FloatTyID: {
Dale Johannesen7111b022008-10-09 18:53:47 +0000886 uint32_t val = cast<ConstantFP>(PC)->getValueAPF().bitcastToAPInt().
Dale Johannesen9d5f4562007-09-12 03:30:33 +0000887 getZExtValue();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000888 if (TD->isBigEndian())
889 val = ByteSwap_32(val);
890 ptr[0] = val;
891 ptr[1] = val >> 8;
892 ptr[2] = val >> 16;
893 ptr[3] = val >> 24;
894 break;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000895 }
896 case Type::DoubleTyID: {
Dale Johannesen7111b022008-10-09 18:53:47 +0000897 uint64_t val = cast<ConstantFP>(PC)->getValueAPF().bitcastToAPInt().
Dale Johannesen9d5f4562007-09-12 03:30:33 +0000898 getZExtValue();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000899 if (TD->isBigEndian())
900 val = ByteSwap_64(val);
901 ptr[0] = val;
902 ptr[1] = val >> 8;
903 ptr[2] = val >> 16;
904 ptr[3] = val >> 24;
905 ptr[4] = val >> 32;
906 ptr[5] = val >> 40;
907 ptr[6] = val >> 48;
908 ptr[7] = val >> 56;
909 break;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000910 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000911 case Type::PointerTyID:
Nate Begeman6635f352007-01-26 22:39:48 +0000912 if (isa<ConstantPointerNull>(PC))
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000913 memset(ptr, 0, TD->getPointerSize());
Nate Begeman6635f352007-01-26 22:39:48 +0000914 else if (const GlobalValue* GV = dyn_cast<GlobalValue>(PC)) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000915 // FIXME: what about function stubs?
916 MRs.push_back(MachineRelocation::getGV(PA-(intptr_t)Addr,
917 MachineRelocation::VANILLA,
Nate Begeman6635f352007-01-26 22:39:48 +0000918 const_cast<GlobalValue*>(GV),
919 ScatteredOffset));
920 ScatteredOffset = 0;
921 } else
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000922 assert(0 && "Unknown constant pointer type!");
923 break;
924 default:
925 cerr << "ERROR: Constant unimp for type: " << *PC->getType() << "\n";
926 abort();
927 }
928 } else if (isa<ConstantAggregateZero>(PC)) {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000929 memset((void*)PA, 0, (size_t)TD->getTypePaddedSize(PC->getType()));
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000930 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(PC)) {
Duncan Sandsca0ed742007-11-05 00:04:43 +0000931 unsigned ElementSize =
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000932 TD->getTypePaddedSize(CPA->getType()->getElementType());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000933 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
934 WorkList.push_back(CPair(CPA->getOperand(i), PA+i*ElementSize));
935 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(PC)) {
936 const StructLayout *SL =
937 TD->getStructLayout(cast<StructType>(CPS->getType()));
938 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
Chris Lattnerb1919e22007-02-10 19:55:17 +0000939 WorkList.push_back(CPair(CPS->getOperand(i),
940 PA+SL->getElementOffset(i)));
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000941 } else {
942 cerr << "Bad Type: " << *PC->getType() << "\n";
943 assert(0 && "Unknown constant type to initialize memory with!");
944 }
945 }
946}
947
948MachOSym::MachOSym(const GlobalValue *gv, std::string name, uint8_t sect,
949 TargetMachine &TM) :
950 GV(gv), n_strx(0), n_type(sect == NO_SECT ? N_UNDF : N_SECT), n_sect(sect),
951 n_desc(0), n_value(0) {
952
953 const TargetAsmInfo *TAI = TM.getTargetAsmInfo();
954
Nate Begeman94be2482006-09-08 22:42:09 +0000955 switch (GV->getLinkage()) {
956 default:
957 assert(0 && "Unexpected linkage type!");
958 break;
Duncan Sands667d4b82009-03-07 15:45:40 +0000959 case GlobalValue::WeakAnyLinkage:
960 case GlobalValue::WeakODRLinkage:
961 case GlobalValue::LinkOnceAnyLinkage:
962 case GlobalValue::LinkOnceODRLinkage:
Duncan Sands4dc2b392009-03-11 20:14:15 +0000963 case GlobalValue::CommonLinkage:
Nate Begeman94be2482006-09-08 22:42:09 +0000964 assert(!isa<Function>(gv) && "Unexpected linkage type for Function!");
965 case GlobalValue::ExternalLinkage:
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000966 GVName = TAI->getGlobalPrefix() + name;
Nate Begeman6635f352007-01-26 22:39:48 +0000967 n_type |= GV->hasHiddenVisibility() ? N_PEXT : N_EXT;
Nate Begeman94be2482006-09-08 22:42:09 +0000968 break;
Rafael Espindolabb46f522009-01-15 20:18:42 +0000969 case GlobalValue::PrivateLinkage:
970 GVName = TAI->getPrivateGlobalPrefix() + name;
971 break;
Nate Begeman94be2482006-09-08 22:42:09 +0000972 case GlobalValue::InternalLinkage:
Nate Begeman6635f352007-01-26 22:39:48 +0000973 GVName = TAI->getGlobalPrefix() + name;
Nate Begeman94be2482006-09-08 22:42:09 +0000974 break;
975 }
976}