blob: 56bf70a62ae44ab99e3184f1219e07fef1f470d8 [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>
Nate Begemaneb883af2006-08-23 21:08:52 +000041using namespace llvm;
42
Bill Wendling8f84f1f2007-02-08 01:35:27 +000043/// AddMachOWriter - Concrete function to add the Mach-O writer to the function
44/// pass manager.
45MachineCodeEmitter *llvm::AddMachOWriter(FunctionPassManager &FPM,
46 std::ostream &O,
47 TargetMachine &TM) {
48 MachOWriter *MOW = new MachOWriter(O, TM);
49 FPM.add(MOW);
50 return &MOW->getMachineCodeEmitter();
51}
52
Nate Begemaneb883af2006-08-23 21:08:52 +000053//===----------------------------------------------------------------------===//
54// MachOCodeEmitter Implementation
55//===----------------------------------------------------------------------===//
56
57namespace llvm {
58 /// MachOCodeEmitter - This class is used by the MachOWriter to emit the code
59 /// for functions to the Mach-O file.
60 class MachOCodeEmitter : public MachineCodeEmitter {
61 MachOWriter &MOW;
Nate Begemaneb883af2006-08-23 21:08:52 +000062
Bill Wendling203d3e42007-01-17 22:22:31 +000063 /// Target machine description.
64 TargetMachine &TM;
65
Bill Wendlingc904a5b2007-01-18 01:23:11 +000066 /// is64Bit/isLittleEndian - This information is inferred from the target
67 /// machine directly, indicating what header values and flags to set.
68 bool is64Bit, isLittleEndian;
69
Nate Begemaneb883af2006-08-23 21:08:52 +000070 /// Relocations - These are the relocations that the function needs, as
71 /// emitted.
72 std::vector<MachineRelocation> Relocations;
Nate Begeman019f8512006-09-10 23:03:44 +000073
74 /// CPLocations - This is a map of constant pool indices to offsets from the
75 /// start of the section for that constant pool index.
76 std::vector<intptr_t> CPLocations;
77
Nate Begemanbfaaaa62006-12-11 02:20:45 +000078 /// CPSections - This is a map of constant pool indices to the MachOSection
79 /// containing the constant pool entry for that index.
80 std::vector<unsigned> CPSections;
81
Nate Begeman019f8512006-09-10 23:03:44 +000082 /// JTLocations - This is a map of jump table indices to offsets from the
83 /// start of the section for that jump table index.
84 std::vector<intptr_t> JTLocations;
Nate Begemaneb883af2006-08-23 21:08:52 +000085
86 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
87 /// It is filled in by the StartMachineBasicBlock callback and queried by
88 /// the getMachineBasicBlockAddress callback.
89 std::vector<intptr_t> MBBLocations;
90
91 public:
Bill Wendlingc904a5b2007-01-18 01:23:11 +000092 MachOCodeEmitter(MachOWriter &mow) : MOW(mow), TM(MOW.TM) {
93 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
94 isLittleEndian = TM.getTargetData()->isLittleEndian();
95 }
Nate Begemaneb883af2006-08-23 21:08:52 +000096
Nate Begemanc2b2d6a2007-02-07 05:47:16 +000097 virtual void startFunction(MachineFunction &MF);
98 virtual bool finishFunction(MachineFunction &MF);
Nate Begemaneb883af2006-08-23 21:08:52 +000099
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000100 virtual void addRelocation(const MachineRelocation &MR) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000101 Relocations.push_back(MR);
102 }
103
Nate Begeman019f8512006-09-10 23:03:44 +0000104 void emitConstantPool(MachineConstantPool *MCP);
105 void emitJumpTables(MachineJumpTableInfo *MJTI);
106
Nate Begemaneb883af2006-08-23 21:08:52 +0000107 virtual intptr_t getConstantPoolEntryAddress(unsigned Index) const {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000108 assert(CPLocations.size() > Index && "CP not emitted!");
Nate Begemana0a62782007-02-28 09:16:38 +0000109 return CPLocations[Index];
Nate Begemaneb883af2006-08-23 21:08:52 +0000110 }
111 virtual intptr_t getJumpTableEntryAddress(unsigned Index) const {
Nate Begeman019f8512006-09-10 23:03:44 +0000112 assert(JTLocations.size() > Index && "JT not emitted!");
113 return JTLocations[Index];
114 }
115
116 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
117 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
118 MBBLocations.resize((MBB->getNumber()+1)*2);
119 MBBLocations[MBB->getNumber()] = getCurrentPCOffset();
Nate Begemaneb883af2006-08-23 21:08:52 +0000120 }
121
122 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
123 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
124 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
125 return MBBLocations[MBB->getNumber()];
126 }
127
128 /// JIT SPECIFIC FUNCTIONS - DO NOT IMPLEMENT THESE HERE!
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000129 virtual void startFunctionStub(unsigned StubSize, unsigned Alignment = 1) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000130 assert(0 && "JIT specific function called!");
131 abort();
132 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000133 virtual void *finishFunctionStub(const Function *F) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000134 assert(0 && "JIT specific function called!");
135 abort();
136 return 0;
137 }
138 };
139}
140
141/// startFunction - This callback is invoked when a new machine function is
142/// about to be emitted.
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000143void MachOCodeEmitter::startFunction(MachineFunction &MF) {
144 const TargetData *TD = TM.getTargetData();
145 const Function *F = MF.getFunction();
146
Nate Begemaneb883af2006-08-23 21:08:52 +0000147 // Align the output buffer to the appropriate alignment, power of 2.
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000148 unsigned FnAlign = F->getAlignment();
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000149 unsigned TDAlign = TD->getPrefTypeAlignment(F->getType());
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000150 unsigned Align = Log2_32(std::max(FnAlign, TDAlign));
151 assert(!(Align & (Align-1)) && "Alignment is not a power of two!");
Nate Begemaneb883af2006-08-23 21:08:52 +0000152
153 // Get the Mach-O Section that this function belongs in.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000154 MachOWriter::MachOSection *MOS = MOW.getTextSection();
Nate Begemaneb883af2006-08-23 21:08:52 +0000155
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000156 // FIXME: better memory management
Nate Begemaneb883af2006-08-23 21:08:52 +0000157 MOS->SectionData.reserve(4096);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000158 BufferBegin = &MOS->SectionData[0];
Nate Begemaneb883af2006-08-23 21:08:52 +0000159 BufferEnd = BufferBegin + MOS->SectionData.capacity();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000160
Nate Begeman6635f352007-01-26 22:39:48 +0000161 // Upgrade the section alignment if required.
162 if (MOS->align < Align) MOS->align = Align;
163
164 // Round the size up to the correct alignment for starting the new function.
165 if ((MOS->size & ((1 << Align) - 1)) != 0) {
166 MOS->size += (1 << Align);
167 MOS->size &= ~((1 << Align) - 1);
168 }
169
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000170 // FIXME: Using MOS->size directly here instead of calculating it from the
171 // output buffer size (impossible because the code emitter deals only in raw
172 // bytes) forces us to manually synchronize size and write padding zero bytes
173 // to the output buffer for all non-text sections. For text sections, we do
174 // not synchonize the output buffer, and we just blow up if anyone tries to
175 // write non-code to it. An assert should probably be added to
176 // AddSymbolToSection to prevent calling it on the text section.
Nate Begemaneb883af2006-08-23 21:08:52 +0000177 CurBufferPtr = BufferBegin + MOS->size;
178
Nate Begeman019f8512006-09-10 23:03:44 +0000179 // Clear per-function data structures.
180 CPLocations.clear();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000181 CPSections.clear();
Nate Begeman019f8512006-09-10 23:03:44 +0000182 JTLocations.clear();
Nate Begemaneb883af2006-08-23 21:08:52 +0000183 MBBLocations.clear();
184}
185
186/// finishFunction - This callback is invoked after the function is completely
187/// finished.
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000188bool MachOCodeEmitter::finishFunction(MachineFunction &MF) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000189 // Get the Mach-O Section that this function belongs in.
190 MachOWriter::MachOSection *MOS = MOW.getTextSection();
191
Nate Begemaneb883af2006-08-23 21:08:52 +0000192 // Get a symbol for the function to add to the symbol table
Nate Begeman6635f352007-01-26 22:39:48 +0000193 // FIXME: it seems like we should call something like AddSymbolToSection
194 // in startFunction rather than changing the section size and symbol n_value
195 // here.
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000196 const GlobalValue *FuncV = MF.getFunction();
Bill Wendling203d3e42007-01-17 22:22:31 +0000197 MachOSym FnSym(FuncV, MOW.Mang->getValueName(FuncV), MOS->Index, TM);
Nate Begeman6635f352007-01-26 22:39:48 +0000198 FnSym.n_value = MOS->size;
199 MOS->size = CurBufferPtr - BufferBegin;
200
Nate Begeman019f8512006-09-10 23:03:44 +0000201 // Emit constant pool to appropriate section(s)
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000202 emitConstantPool(MF.getConstantPool());
Nate Begeman019f8512006-09-10 23:03:44 +0000203
204 // Emit jump tables to appropriate section
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000205 emitJumpTables(MF.getJumpTableInfo());
Nate Begemaneb883af2006-08-23 21:08:52 +0000206
Nate Begeman019f8512006-09-10 23:03:44 +0000207 // If we have emitted any relocations to function-specific objects such as
208 // basic blocks, constant pools entries, or jump tables, record their
209 // addresses now so that we can rewrite them with the correct addresses
210 // later.
Nate Begemaneb883af2006-08-23 21:08:52 +0000211 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
212 MachineRelocation &MR = Relocations[i];
Nate Begeman019f8512006-09-10 23:03:44 +0000213 intptr_t Addr;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000214
Nate Begemaneb883af2006-08-23 21:08:52 +0000215 if (MR.isBasicBlock()) {
Nate Begeman019f8512006-09-10 23:03:44 +0000216 Addr = getMachineBasicBlockAddress(MR.getBasicBlock());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000217 MR.setConstantVal(MOS->Index);
218 MR.setResultPointer((void*)Addr);
219 } else if (MR.isJumpTableIndex()) {
220 Addr = getJumpTableEntryAddress(MR.getJumpTableIndex());
221 MR.setConstantVal(MOW.getJumpTableSection()->Index);
222 MR.setResultPointer((void*)Addr);
Nate Begeman019f8512006-09-10 23:03:44 +0000223 } else if (MR.isConstantPoolIndex()) {
224 Addr = getConstantPoolEntryAddress(MR.getConstantPoolIndex());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000225 MR.setConstantVal(CPSections[MR.getConstantPoolIndex()]);
226 MR.setResultPointer((void*)Addr);
Nate Begemanfec910c2007-02-28 07:40:50 +0000227 } else if (MR.isGlobalValue()) {
228 // FIXME: This should be a set or something that uniques
229 MOW.PendingGlobals.push_back(MR.getGlobalValue());
230 } else {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000231 assert(0 && "Unhandled relocation type");
Nate Begemaneb883af2006-08-23 21:08:52 +0000232 }
Nate Begeman019f8512006-09-10 23:03:44 +0000233 MOS->Relocations.push_back(MR);
Nate Begemaneb883af2006-08-23 21:08:52 +0000234 }
235 Relocations.clear();
236
237 // Finally, add it to the symtab.
238 MOW.SymbolTable.push_back(FnSym);
239 return false;
240}
241
Nate Begeman019f8512006-09-10 23:03:44 +0000242/// emitConstantPool - For each constant pool entry, figure out which section
243/// the constant should live in, allocate space for it, and emit it to the
244/// Section data buffer.
245void MachOCodeEmitter::emitConstantPool(MachineConstantPool *MCP) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000246 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
247 if (CP.empty()) return;
248
249 // FIXME: handle PIC codegen
Bill Wendling203d3e42007-01-17 22:22:31 +0000250 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000251 assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
252
253 // Although there is no strict necessity that I am aware of, we will do what
254 // gcc for OS X does and put each constant pool entry in a section of constant
255 // objects of a certain size. That means that float constants go in the
256 // literal4 section, and double objects go in literal8, etc.
257 //
258 // FIXME: revisit this decision if we ever do the "stick everything into one
259 // "giant object for PIC" optimization.
260 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
261 const Type *Ty = CP[i].getType();
Duncan Sandsca0ed742007-11-05 00:04:43 +0000262 unsigned Size = TM.getTargetData()->getABITypeSize(Ty);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000263
Nate Begeman1257c852007-01-29 21:20:42 +0000264 MachOWriter::MachOSection *Sec = MOW.getConstSection(CP[i].Val.ConstVal);
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000265 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000266
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000267 CPLocations.push_back(Sec->SectionData.size());
268 CPSections.push_back(Sec->Index);
269
270 // FIXME: remove when we have unified size + output buffer
271 Sec->size += Size;
272
273 // Allocate space in the section for the global.
274 // FIXME: need alignment?
275 // FIXME: share between here and AddSymbolToSection?
276 for (unsigned j = 0; j < Size; ++j)
Bill Wendling203d3e42007-01-17 22:22:31 +0000277 SecDataOut.outbyte(0);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000278
279 MOW.InitMem(CP[i].Val.ConstVal, &Sec->SectionData[0], CPLocations[i],
Bill Wendling203d3e42007-01-17 22:22:31 +0000280 TM.getTargetData(), Sec->Relocations);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000281 }
Nate Begeman019f8512006-09-10 23:03:44 +0000282}
283
284/// emitJumpTables - Emit all the jump tables for a given jump table info
285/// record to the appropriate section.
286void MachOCodeEmitter::emitJumpTables(MachineJumpTableInfo *MJTI) {
287 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
288 if (JT.empty()) return;
289
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000290 // FIXME: handle PIC codegen
Bill Wendling203d3e42007-01-17 22:22:31 +0000291 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
Nate Begeman019f8512006-09-10 23:03:44 +0000292 assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
293
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000294 MachOWriter::MachOSection *Sec = MOW.getJumpTableSection();
295 unsigned TextSecIndex = MOW.getTextSection()->Index;
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000296 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
Nate Begeman019f8512006-09-10 23:03:44 +0000297
298 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
299 // For each jump table, record its offset from the start of the section,
300 // reserve space for the relocations to the MBBs, and add the relocations.
301 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000302 JTLocations.push_back(Sec->SectionData.size());
Nate Begeman019f8512006-09-10 23:03:44 +0000303 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000304 MachineRelocation MR(MOW.GetJTRelocation(Sec->SectionData.size(),
Nate Begeman019f8512006-09-10 23:03:44 +0000305 MBBs[mi]));
306 MR.setResultPointer((void *)JTLocations[i]);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000307 MR.setConstantVal(TextSecIndex);
308 Sec->Relocations.push_back(MR);
Bill Wendling203d3e42007-01-17 22:22:31 +0000309 SecDataOut.outaddr(0);
Nate Begeman019f8512006-09-10 23:03:44 +0000310 }
311 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000312 // FIXME: remove when we have unified size + output buffer
313 Sec->size = Sec->SectionData.size();
Nate Begeman019f8512006-09-10 23:03:44 +0000314}
315
Nate Begemaneb883af2006-08-23 21:08:52 +0000316//===----------------------------------------------------------------------===//
317// MachOWriter Implementation
318//===----------------------------------------------------------------------===//
319
Devang Patel19974732007-05-03 01:11:54 +0000320char MachOWriter::ID = 0;
Devang Patel794fd752007-05-01 21:15:47 +0000321MachOWriter::MachOWriter(std::ostream &o, TargetMachine &tm)
322 : MachineFunctionPass((intptr_t)&ID), O(o), TM(tm) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000323 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
324 isLittleEndian = TM.getTargetData()->isLittleEndian();
325
326 // Create the machine code emitter object for this target.
Bill Wendlinge9116152007-01-17 09:06:13 +0000327 MCE = new MachOCodeEmitter(*this);
Nate Begemaneb883af2006-08-23 21:08:52 +0000328}
329
330MachOWriter::~MachOWriter() {
331 delete MCE;
332}
333
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000334void MachOWriter::AddSymbolToSection(MachOSection *Sec, GlobalVariable *GV) {
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000335 const Type *Ty = GV->getType()->getElementType();
Duncan Sandsca0ed742007-11-05 00:04:43 +0000336 unsigned Size = TM.getTargetData()->getABITypeSize(Ty);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000337 unsigned Align = GV->getAlignment();
338 if (Align == 0)
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000339 Align = TM.getTargetData()->getPrefTypeAlignment(Ty);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000340
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000341 // Reserve space in the .bss section for this symbol while maintaining the
342 // desired section alignment, which must be at least as much as required by
343 // this symbol.
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000344 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000345
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000346 if (Align) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000347 uint64_t OrigSize = Sec->size;
348 Align = Log2_32(Align);
349 Sec->align = std::max(unsigned(Sec->align), Align);
350 Sec->size = (Sec->size + Align - 1) & ~(Align-1);
351
352 // Add alignment padding to buffer as well.
353 // FIXME: remove when we have unified size + output buffer
354 unsigned AlignedSize = Sec->size - OrigSize;
355 for (unsigned i = 0; i < AlignedSize; ++i)
Bill Wendling203d3e42007-01-17 22:22:31 +0000356 SecDataOut.outbyte(0);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000357 }
Nate Begemanfec910c2007-02-28 07:40:50 +0000358 // Globals without external linkage apparently do not go in the symbol table.
359 if (GV->getLinkage() != GlobalValue::InternalLinkage) {
360 MachOSym Sym(GV, Mang->getValueName(GV), Sec->Index, TM);
361 Sym.n_value = Sec->size;
362 SymbolTable.push_back(Sym);
363 }
364
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000365 // Record the offset of the symbol, and then allocate space for it.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000366 // FIXME: remove when we have unified size + output buffer
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000367 Sec->size += Size;
Nate Begemanfec910c2007-02-28 07:40:50 +0000368
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000369 // Now that we know what section the GlovalVariable is going to be emitted
370 // into, update our mappings.
371 // FIXME: We may also need to update this when outputting non-GlobalVariable
372 // GlobalValues such as functions.
373 GVSection[GV] = Sec;
374 GVOffset[GV] = Sec->SectionData.size();
375
376 // Allocate space in the section for the global.
377 for (unsigned i = 0; i < Size; ++i)
Bill Wendling203d3e42007-01-17 22:22:31 +0000378 SecDataOut.outbyte(0);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000379}
380
Nate Begemaneb883af2006-08-23 21:08:52 +0000381void MachOWriter::EmitGlobal(GlobalVariable *GV) {
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000382 const Type *Ty = GV->getType()->getElementType();
Duncan Sandsca0ed742007-11-05 00:04:43 +0000383 unsigned Size = TM.getTargetData()->getABITypeSize(Ty);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000384 bool NoInit = !GV->hasInitializer();
Nate Begemand2030e62006-08-26 15:46:34 +0000385
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000386 // If this global has a zero initializer, it is part of the .bss or common
387 // section.
388 if (NoInit || GV->getInitializer()->isNullValue()) {
389 // If this global is part of the common block, add it now. Variables are
390 // part of the common block if they are zero initialized and allowed to be
391 // merged with other symbols.
392 if (NoInit || GV->hasLinkOnceLinkage() || GV->hasWeakLinkage()) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000393 MachOSym ExtOrCommonSym(GV, Mang->getValueName(GV), MachOSym::NO_SECT,TM);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000394 // For undefined (N_UNDF) external (N_EXT) types, n_value is the size in
395 // bytes of the symbol.
396 ExtOrCommonSym.n_value = Size;
Nate Begemanfec910c2007-02-28 07:40:50 +0000397 SymbolTable.push_back(ExtOrCommonSym);
398 // Remember that we've seen this symbol
399 GVOffset[GV] = Size;
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000400 return;
401 }
402 // Otherwise, this symbol is part of the .bss section.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000403 MachOSection *BSS = getBSSSection();
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000404 AddSymbolToSection(BSS, GV);
405 return;
406 }
407
408 // Scalar read-only data goes in a literal section if the scalar is 4, 8, or
409 // 16 bytes, or a cstring. Other read only data goes into a regular const
410 // section. Read-write data goes in the data section.
Nate Begeman1257c852007-01-29 21:20:42 +0000411 MachOSection *Sec = GV->isConstant() ? getConstSection(GV->getInitializer()) :
412 getDataSection();
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000413 AddSymbolToSection(Sec, GV);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000414 InitMem(GV->getInitializer(), &Sec->SectionData[0], GVOffset[GV],
415 TM.getTargetData(), Sec->Relocations);
Nate Begemaneb883af2006-08-23 21:08:52 +0000416}
417
418
419bool MachOWriter::runOnMachineFunction(MachineFunction &MF) {
420 // Nothing to do here, this is all done through the MCE object.
421 return false;
422}
423
424bool MachOWriter::doInitialization(Module &M) {
425 // Set the magic value, now that we know the pointer size and endianness
426 Header.setMagic(isLittleEndian, is64Bit);
427
428 // Set the file type
429 // FIXME: this only works for object files, we do not support the creation
430 // of dynamic libraries or executables at this time.
431 Header.filetype = MachOHeader::MH_OBJECT;
432
433 Mang = new Mangler(M);
434 return false;
435}
436
437/// doFinalization - Now that the module has been completely processed, emit
438/// the Mach-O file to 'O'.
439bool MachOWriter::doFinalization(Module &M) {
Nate Begemand2030e62006-08-26 15:46:34 +0000440 // FIXME: we don't handle debug info yet, we should probably do that.
441
Nate Begemaneb883af2006-08-23 21:08:52 +0000442 // Okay, the.text section has been completed, build the .data, .bss, and
443 // "common" sections next.
444 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
445 I != E; ++I)
446 EmitGlobal(I);
447
448 // Emit the header and load commands.
449 EmitHeaderAndLoadCommands();
450
Nate Begeman019f8512006-09-10 23:03:44 +0000451 // Emit the various sections and their relocation info.
Nate Begemaneb883af2006-08-23 21:08:52 +0000452 EmitSections();
453
Nate Begemand2030e62006-08-26 15:46:34 +0000454 // Write the symbol table and the string table to the end of the file.
455 O.write((char*)&SymT[0], SymT.size());
456 O.write((char*)&StrT[0], StrT.size());
Nate Begemaneb883af2006-08-23 21:08:52 +0000457
458 // We are done with the abstract symbols.
459 SectionList.clear();
460 SymbolTable.clear();
461 DynamicSymbolTable.clear();
462
463 // Release the name mangler object.
464 delete Mang; Mang = 0;
465 return false;
466}
467
468void MachOWriter::EmitHeaderAndLoadCommands() {
469 // Step #0: Fill in the segment load command size, since we need it to figure
470 // out the rest of the header fields
471 MachOSegment SEG("", is64Bit);
472 SEG.nsects = SectionList.size();
473 SEG.cmdsize = SEG.cmdSize(is64Bit) +
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000474 SEG.nsects * SectionList[0]->cmdSize(is64Bit);
Nate Begemaneb883af2006-08-23 21:08:52 +0000475
476 // Step #1: calculate the number of load commands. We always have at least
477 // one, for the LC_SEGMENT load command, plus two for the normal
478 // and dynamic symbol tables, if there are any symbols.
479 Header.ncmds = SymbolTable.empty() ? 1 : 3;
480
481 // Step #2: calculate the size of the load commands
482 Header.sizeofcmds = SEG.cmdsize;
483 if (!SymbolTable.empty())
484 Header.sizeofcmds += SymTab.cmdsize + DySymTab.cmdsize;
485
486 // Step #3: write the header to the file
487 // Local alias to shortenify coming code.
488 DataBuffer &FH = Header.HeaderData;
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000489 OutputBuffer FHOut(FH, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000490
491 FHOut.outword(Header.magic);
Bill Wendling2b721822007-01-24 07:13:56 +0000492 FHOut.outword(TM.getMachOWriterInfo()->getCPUType());
493 FHOut.outword(TM.getMachOWriterInfo()->getCPUSubType());
Bill Wendling203d3e42007-01-17 22:22:31 +0000494 FHOut.outword(Header.filetype);
495 FHOut.outword(Header.ncmds);
496 FHOut.outword(Header.sizeofcmds);
497 FHOut.outword(Header.flags);
Nate Begemaneb883af2006-08-23 21:08:52 +0000498 if (is64Bit)
Bill Wendling203d3e42007-01-17 22:22:31 +0000499 FHOut.outword(Header.reserved);
Nate Begemaneb883af2006-08-23 21:08:52 +0000500
501 // Step #4: Finish filling in the segment load command and write it out
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000502 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begemaneb883af2006-08-23 21:08:52 +0000503 E = SectionList.end(); I != E; ++I)
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000504 SEG.filesize += (*I)->size;
505
Nate Begemaneb883af2006-08-23 21:08:52 +0000506 SEG.vmsize = SEG.filesize;
507 SEG.fileoff = Header.cmdSize(is64Bit) + Header.sizeofcmds;
508
Bill Wendling203d3e42007-01-17 22:22:31 +0000509 FHOut.outword(SEG.cmd);
510 FHOut.outword(SEG.cmdsize);
511 FHOut.outstring(SEG.segname, 16);
512 FHOut.outaddr(SEG.vmaddr);
513 FHOut.outaddr(SEG.vmsize);
514 FHOut.outaddr(SEG.fileoff);
515 FHOut.outaddr(SEG.filesize);
516 FHOut.outword(SEG.maxprot);
517 FHOut.outword(SEG.initprot);
518 FHOut.outword(SEG.nsects);
519 FHOut.outword(SEG.flags);
Nate Begemaneb883af2006-08-23 21:08:52 +0000520
Nate Begeman94be2482006-09-08 22:42:09 +0000521 // Step #5: Finish filling in the fields of the MachOSections
522 uint64_t currentAddr = 0;
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 MachOSection *MOS = *I;
526 MOS->addr = currentAddr;
527 MOS->offset = currentAddr + SEG.fileoff;
Nate Begeman019f8512006-09-10 23:03:44 +0000528
Nate Begeman94be2482006-09-08 22:42:09 +0000529 // FIXME: do we need to do something with alignment here?
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000530 currentAddr += MOS->size;
Nate Begeman94be2482006-09-08 22:42:09 +0000531 }
532
Nate Begemanfec910c2007-02-28 07:40:50 +0000533 // Step #6: Emit the symbol table to temporary buffers, so that we know the
534 // size of the string table when we write the next load command. This also
535 // sorts and assigns indices to each of the symbols, which is necessary for
536 // emitting relocations to externally-defined objects.
537 BufferSymbolAndStringTable();
538
539 // Step #7: Calculate the number of relocations for each section and write out
Nate Begeman94be2482006-09-08 22:42:09 +0000540 // the section commands for each section
541 currentAddr += SEG.fileoff;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000542 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman94be2482006-09-08 22:42:09 +0000543 E = SectionList.end(); I != E; ++I) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000544 MachOSection *MOS = *I;
545 // Convert the relocations to target-specific relocations, and fill in the
546 // relocation offset for this section.
547 CalculateRelocations(*MOS);
548 MOS->reloff = MOS->nreloc ? currentAddr : 0;
549 currentAddr += MOS->nreloc * 8;
Nate Begeman94be2482006-09-08 22:42:09 +0000550
551 // write the finalized section command to the output buffer
Bill Wendling203d3e42007-01-17 22:22:31 +0000552 FHOut.outstring(MOS->sectname, 16);
553 FHOut.outstring(MOS->segname, 16);
554 FHOut.outaddr(MOS->addr);
555 FHOut.outaddr(MOS->size);
556 FHOut.outword(MOS->offset);
557 FHOut.outword(MOS->align);
558 FHOut.outword(MOS->reloff);
559 FHOut.outword(MOS->nreloc);
560 FHOut.outword(MOS->flags);
561 FHOut.outword(MOS->reserved1);
562 FHOut.outword(MOS->reserved2);
Nate Begemaneb883af2006-08-23 21:08:52 +0000563 if (is64Bit)
Bill Wendling203d3e42007-01-17 22:22:31 +0000564 FHOut.outword(MOS->reserved3);
Nate Begemaneb883af2006-08-23 21:08:52 +0000565 }
566
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000567 // Step #8: Emit LC_SYMTAB/LC_DYSYMTAB load commands
Nate Begeman94be2482006-09-08 22:42:09 +0000568 SymTab.symoff = currentAddr;
Nate Begemaneb883af2006-08-23 21:08:52 +0000569 SymTab.nsyms = SymbolTable.size();
Nate Begemand2030e62006-08-26 15:46:34 +0000570 SymTab.stroff = SymTab.symoff + SymT.size();
571 SymTab.strsize = StrT.size();
Bill Wendling203d3e42007-01-17 22:22:31 +0000572 FHOut.outword(SymTab.cmd);
573 FHOut.outword(SymTab.cmdsize);
574 FHOut.outword(SymTab.symoff);
575 FHOut.outword(SymTab.nsyms);
576 FHOut.outword(SymTab.stroff);
577 FHOut.outword(SymTab.strsize);
Nate Begemaneb883af2006-08-23 21:08:52 +0000578
579 // FIXME: set DySymTab fields appropriately
Nate Begemand2030e62006-08-26 15:46:34 +0000580 // We should probably just update these in BufferSymbolAndStringTable since
581 // thats where we're partitioning up the different kinds of symbols.
Bill Wendling203d3e42007-01-17 22:22:31 +0000582 FHOut.outword(DySymTab.cmd);
583 FHOut.outword(DySymTab.cmdsize);
584 FHOut.outword(DySymTab.ilocalsym);
585 FHOut.outword(DySymTab.nlocalsym);
586 FHOut.outword(DySymTab.iextdefsym);
587 FHOut.outword(DySymTab.nextdefsym);
588 FHOut.outword(DySymTab.iundefsym);
589 FHOut.outword(DySymTab.nundefsym);
590 FHOut.outword(DySymTab.tocoff);
591 FHOut.outword(DySymTab.ntoc);
592 FHOut.outword(DySymTab.modtaboff);
593 FHOut.outword(DySymTab.nmodtab);
594 FHOut.outword(DySymTab.extrefsymoff);
595 FHOut.outword(DySymTab.nextrefsyms);
596 FHOut.outword(DySymTab.indirectsymoff);
597 FHOut.outword(DySymTab.nindirectsyms);
598 FHOut.outword(DySymTab.extreloff);
599 FHOut.outword(DySymTab.nextrel);
600 FHOut.outword(DySymTab.locreloff);
601 FHOut.outword(DySymTab.nlocrel);
Nate Begemaneb883af2006-08-23 21:08:52 +0000602
603 O.write((char*)&FH[0], FH.size());
604}
605
606/// EmitSections - Now that we have constructed the file header and load
607/// commands, emit the data for each section to the file.
608void MachOWriter::EmitSections() {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000609 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman019f8512006-09-10 23:03:44 +0000610 E = SectionList.end(); I != E; ++I)
611 // Emit the contents of each section
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000612 O.write((char*)&(*I)->SectionData[0], (*I)->size);
613 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman019f8512006-09-10 23:03:44 +0000614 E = SectionList.end(); I != E; ++I)
615 // Emit the relocation entry data for each section.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000616 O.write((char*)&(*I)->RelocBuffer[0], (*I)->RelocBuffer.size());
Nate Begemaneb883af2006-08-23 21:08:52 +0000617}
618
Nate Begemand2030e62006-08-26 15:46:34 +0000619/// PartitionByLocal - Simple boolean predicate that returns true if Sym is
620/// a local symbol rather than an external symbol.
621bool MachOWriter::PartitionByLocal(const MachOSym &Sym) {
Nate Begemand2030e62006-08-26 15:46:34 +0000622 return (Sym.n_type & (MachOSym::N_EXT | MachOSym::N_PEXT)) == 0;
Nate Begemaneb883af2006-08-23 21:08:52 +0000623}
624
Nate Begemand2030e62006-08-26 15:46:34 +0000625/// PartitionByDefined - Simple boolean predicate that returns true if Sym is
626/// defined in this module.
627bool MachOWriter::PartitionByDefined(const MachOSym &Sym) {
628 // FIXME: Do N_ABS or N_INDR count as defined?
629 return (Sym.n_type & MachOSym::N_SECT) == MachOSym::N_SECT;
630}
Nate Begemaneb883af2006-08-23 21:08:52 +0000631
Nate Begemand2030e62006-08-26 15:46:34 +0000632/// BufferSymbolAndStringTable - Sort the symbols we encountered and assign them
633/// each a string table index so that they appear in the correct order in the
634/// output file.
635void MachOWriter::BufferSymbolAndStringTable() {
636 // The order of the symbol table is:
637 // 1. local symbols
638 // 2. defined external symbols (sorted by name)
639 // 3. undefined external symbols (sorted by name)
640
Nate Begemanfec910c2007-02-28 07:40:50 +0000641 // Before sorting the symbols, check the PendingGlobals for any undefined
642 // globals that need to be put in the symbol table.
643 for (std::vector<GlobalValue*>::iterator I = PendingGlobals.begin(),
644 E = PendingGlobals.end(); I != E; ++I) {
645 if (GVOffset[*I] == 0 && GVSection[*I] == 0) {
646 MachOSym UndfSym(*I, Mang->getValueName(*I), MachOSym::NO_SECT, TM);
647 SymbolTable.push_back(UndfSym);
648 GVOffset[*I] = -1;
649 }
650 }
651
Nate Begemand2030e62006-08-26 15:46:34 +0000652 // Sort the symbols by name, so that when we partition the symbols by scope
653 // of definition, we won't have to sort by name within each partition.
654 std::sort(SymbolTable.begin(), SymbolTable.end(), MachOSymCmp());
655
656 // Parition the symbol table entries so that all local symbols come before
657 // all symbols with external linkage. { 1 | 2 3 }
658 std::partition(SymbolTable.begin(), SymbolTable.end(), PartitionByLocal);
659
660 // Advance iterator to beginning of external symbols and partition so that
661 // all external symbols defined in this module come before all external
662 // symbols defined elsewhere. { 1 | 2 | 3 }
663 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
664 E = SymbolTable.end(); I != E; ++I) {
665 if (!PartitionByLocal(*I)) {
666 std::partition(I, E, PartitionByDefined);
667 break;
668 }
669 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000670
671 // Calculate the starting index for each of the local, extern defined, and
672 // undefined symbols, as well as the number of each to put in the LC_DYSYMTAB
673 // load command.
674 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
675 E = SymbolTable.end(); I != E; ++I) {
676 if (PartitionByLocal(*I)) {
677 ++DySymTab.nlocalsym;
678 ++DySymTab.iextdefsym;
Nate Begeman6635f352007-01-26 22:39:48 +0000679 ++DySymTab.iundefsym;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000680 } else if (PartitionByDefined(*I)) {
681 ++DySymTab.nextdefsym;
682 ++DySymTab.iundefsym;
683 } else {
684 ++DySymTab.nundefsym;
685 }
686 }
Nate Begemand2030e62006-08-26 15:46:34 +0000687
Nate Begemaneb883af2006-08-23 21:08:52 +0000688 // Write out a leading zero byte when emitting string table, for n_strx == 0
689 // which means an empty string.
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000690 OutputBuffer StrTOut(StrT, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000691 StrTOut.outbyte(0);
Nate Begemaneb883af2006-08-23 21:08:52 +0000692
Nate Begemand2030e62006-08-26 15:46:34 +0000693 // The order of the string table is:
694 // 1. strings for external symbols
695 // 2. strings for local symbols
696 // Since this is the opposite order from the symbol table, which we have just
697 // sorted, we can walk the symbol table backwards to output the string table.
698 for (std::vector<MachOSym>::reverse_iterator I = SymbolTable.rbegin(),
699 E = SymbolTable.rend(); I != E; ++I) {
700 if (I->GVName == "") {
701 I->n_strx = 0;
702 } else {
703 I->n_strx = StrT.size();
Bill Wendling203d3e42007-01-17 22:22:31 +0000704 StrTOut.outstring(I->GVName, I->GVName.length()+1);
Nate Begemand2030e62006-08-26 15:46:34 +0000705 }
Nate Begemaneb883af2006-08-23 21:08:52 +0000706 }
Nate Begemand2030e62006-08-26 15:46:34 +0000707
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000708 OutputBuffer SymTOut(SymT, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000709
Nate Begemanfec910c2007-02-28 07:40:50 +0000710 unsigned index = 0;
Nate Begemand2030e62006-08-26 15:46:34 +0000711 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
Nate Begemanfec910c2007-02-28 07:40:50 +0000712 E = SymbolTable.end(); I != E; ++I, ++index) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000713 // Add the section base address to the section offset in the n_value field
714 // to calculate the full address.
715 // FIXME: handle symbols where the n_value field is not the address
716 GlobalValue *GV = const_cast<GlobalValue*>(I->GV);
717 if (GV && GVSection[GV])
718 I->n_value += GVSection[GV]->addr;
Nate Begemanfec910c2007-02-28 07:40:50 +0000719 if (GV && (GVOffset[GV] == -1))
720 GVOffset[GV] = index;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000721
Nate Begemand2030e62006-08-26 15:46:34 +0000722 // Emit nlist to buffer
Bill Wendling203d3e42007-01-17 22:22:31 +0000723 SymTOut.outword(I->n_strx);
724 SymTOut.outbyte(I->n_type);
725 SymTOut.outbyte(I->n_sect);
726 SymTOut.outhalf(I->n_desc);
727 SymTOut.outaddr(I->n_value);
Nate Begemand2030e62006-08-26 15:46:34 +0000728 }
Nate Begemaneb883af2006-08-23 21:08:52 +0000729}
Nate Begeman94be2482006-09-08 22:42:09 +0000730
Nate Begeman019f8512006-09-10 23:03:44 +0000731/// CalculateRelocations - For each MachineRelocation in the current section,
732/// calculate the index of the section containing the object to be relocated,
733/// and the offset into that section. From this information, create the
734/// appropriate target-specific MachORelocation type and add buffer it to be
735/// written out after we are finished writing out sections.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000736void MachOWriter::CalculateRelocations(MachOSection &MOS) {
Nate Begeman019f8512006-09-10 23:03:44 +0000737 for (unsigned i = 0, e = MOS.Relocations.size(); i != e; ++i) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000738 MachineRelocation &MR = MOS.Relocations[i];
739 unsigned TargetSection = MR.getConstantVal();
Nate Begemanaf806382007-03-03 06:18:18 +0000740 unsigned TargetAddr = 0;
741 unsigned TargetIndex = 0;
Nate Begeman6635f352007-01-26 22:39:48 +0000742
743 // This is a scattered relocation entry if it points to a global value with
744 // a non-zero offset.
745 bool Scattered = false;
Nate Begemanfec910c2007-02-28 07:40:50 +0000746 bool Extern = false;
Nate Begemanaf806382007-03-03 06:18:18 +0000747
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000748 // Since we may not have seen the GlobalValue we were interested in yet at
749 // the time we emitted the relocation for it, fix it up now so that it
750 // points to the offset into the correct section.
751 if (MR.isGlobalValue()) {
752 GlobalValue *GV = MR.getGlobalValue();
753 MachOSection *MOSPtr = GVSection[GV];
Nate Begeman6635f352007-01-26 22:39:48 +0000754 intptr_t Offset = GVOffset[GV];
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000755
Nate Begemanfec910c2007-02-28 07:40:50 +0000756 // If we have never seen the global before, it must be to a symbol
757 // defined in another module (N_UNDF).
Nate Begeman1257c852007-01-29 21:20:42 +0000758 if (!MOSPtr) {
Nate Begemanfec910c2007-02-28 07:40:50 +0000759 // FIXME: need to append stub suffix
760 Extern = true;
761 TargetAddr = 0;
762 TargetIndex = GVOffset[GV];
763 } else {
764 Scattered = TargetSection != 0;
765 TargetSection = MOSPtr->Index;
Nate Begemanaf806382007-03-03 06:18:18 +0000766 }
767 MR.setResultPointer((void*)Offset);
768 }
769
770 // If the symbol is locally defined, pass in the address of the section and
771 // the section index to the code which will generate the target relocation.
772 if (!Extern) {
Nate Begemanfec910c2007-02-28 07:40:50 +0000773 MachOSection &To = *SectionList[TargetSection - 1];
774 TargetAddr = To.addr;
775 TargetIndex = To.Index;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000776 }
Bill Wendling886b4122007-02-03 02:39:40 +0000777
778 OutputBuffer RelocOut(MOS.RelocBuffer, is64Bit, isLittleEndian);
779 OutputBuffer SecOut(MOS.SectionData, is64Bit, isLittleEndian);
Nate Begemanfec910c2007-02-28 07:40:50 +0000780
781 MOS.nreloc += GetTargetRelocation(MR, MOS.Index, TargetAddr, TargetIndex,
782 RelocOut, SecOut, Scattered, Extern);
Nate Begeman019f8512006-09-10 23:03:44 +0000783 }
Nate Begeman019f8512006-09-10 23:03:44 +0000784}
785
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000786// InitMem - Write the value of a Constant to the specified memory location,
787// converting it into bytes and relocations.
788void MachOWriter::InitMem(const Constant *C, void *Addr, intptr_t Offset,
789 const TargetData *TD,
790 std::vector<MachineRelocation> &MRs) {
791 typedef std::pair<const Constant*, intptr_t> CPair;
792 std::vector<CPair> WorkList;
793
794 WorkList.push_back(CPair(C,(intptr_t)Addr + Offset));
795
Nate Begeman6635f352007-01-26 22:39:48 +0000796 intptr_t ScatteredOffset = 0;
797
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000798 while (!WorkList.empty()) {
799 const Constant *PC = WorkList.back().first;
800 intptr_t PA = WorkList.back().second;
801 WorkList.pop_back();
802
803 if (isa<UndefValue>(PC)) {
804 continue;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000805 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(PC)) {
Duncan Sandsca0ed742007-11-05 00:04:43 +0000806 unsigned ElementSize =
807 TD->getABITypeSize(CP->getType()->getElementType());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000808 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
809 WorkList.push_back(CPair(CP->getOperand(i), PA+i*ElementSize));
810 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(PC)) {
811 //
812 // FIXME: Handle ConstantExpression. See EE::getConstantValue()
813 //
814 switch (CE->getOpcode()) {
Nate Begeman6635f352007-01-26 22:39:48 +0000815 case Instruction::GetElementPtr: {
Chris Lattner7f6b9d22007-02-10 20:31:59 +0000816 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Nate Begeman6635f352007-01-26 22:39:48 +0000817 ScatteredOffset = TD->getIndexedOffset(CE->getOperand(0)->getType(),
Chris Lattner7f6b9d22007-02-10 20:31:59 +0000818 &Indices[0], Indices.size());
Nate Begeman6635f352007-01-26 22:39:48 +0000819 WorkList.push_back(CPair(CE->getOperand(0), PA));
820 break;
821 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000822 case Instruction::Add:
823 default:
824 cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
825 abort();
826 break;
827 }
828 } else if (PC->getType()->isFirstClassType()) {
829 unsigned char *ptr = (unsigned char *)PA;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000830 switch (PC->getType()->getTypeID()) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000831 case Type::IntegerTyID: {
832 unsigned NumBits = cast<IntegerType>(PC->getType())->getBitWidth();
833 uint64_t val = cast<ConstantInt>(PC)->getZExtValue();
834 if (NumBits <= 8)
835 ptr[0] = val;
836 else if (NumBits <= 16) {
837 if (TD->isBigEndian())
838 val = ByteSwap_16(val);
839 ptr[0] = val;
840 ptr[1] = val >> 8;
841 } else if (NumBits <= 32) {
842 if (TD->isBigEndian())
843 val = ByteSwap_32(val);
844 ptr[0] = val;
845 ptr[1] = val >> 8;
846 ptr[2] = val >> 16;
847 ptr[3] = val >> 24;
848 } else if (NumBits <= 64) {
849 if (TD->isBigEndian())
850 val = ByteSwap_64(val);
851 ptr[0] = val;
852 ptr[1] = val >> 8;
853 ptr[2] = val >> 16;
854 ptr[3] = val >> 24;
855 ptr[4] = val >> 32;
856 ptr[5] = val >> 40;
857 ptr[6] = val >> 48;
858 ptr[7] = val >> 56;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000859 } else {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000860 assert(0 && "Not implemented: bit widths > 64");
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000861 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000862 break;
863 }
864 case Type::FloatTyID: {
Dale Johannesen9d5f4562007-09-12 03:30:33 +0000865 uint32_t val = cast<ConstantFP>(PC)->getValueAPF().convertToAPInt().
866 getZExtValue();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000867 if (TD->isBigEndian())
868 val = ByteSwap_32(val);
869 ptr[0] = val;
870 ptr[1] = val >> 8;
871 ptr[2] = val >> 16;
872 ptr[3] = val >> 24;
873 break;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000874 }
875 case Type::DoubleTyID: {
Dale Johannesen9d5f4562007-09-12 03:30:33 +0000876 uint64_t val = cast<ConstantFP>(PC)->getValueAPF().convertToAPInt().
877 getZExtValue();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000878 if (TD->isBigEndian())
879 val = ByteSwap_64(val);
880 ptr[0] = val;
881 ptr[1] = val >> 8;
882 ptr[2] = val >> 16;
883 ptr[3] = val >> 24;
884 ptr[4] = val >> 32;
885 ptr[5] = val >> 40;
886 ptr[6] = val >> 48;
887 ptr[7] = val >> 56;
888 break;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000889 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000890 case Type::PointerTyID:
Nate Begeman6635f352007-01-26 22:39:48 +0000891 if (isa<ConstantPointerNull>(PC))
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000892 memset(ptr, 0, TD->getPointerSize());
Nate Begeman6635f352007-01-26 22:39:48 +0000893 else if (const GlobalValue* GV = dyn_cast<GlobalValue>(PC)) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000894 // FIXME: what about function stubs?
895 MRs.push_back(MachineRelocation::getGV(PA-(intptr_t)Addr,
896 MachineRelocation::VANILLA,
Nate Begeman6635f352007-01-26 22:39:48 +0000897 const_cast<GlobalValue*>(GV),
898 ScatteredOffset));
899 ScatteredOffset = 0;
900 } else
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000901 assert(0 && "Unknown constant pointer type!");
902 break;
903 default:
904 cerr << "ERROR: Constant unimp for type: " << *PC->getType() << "\n";
905 abort();
906 }
907 } else if (isa<ConstantAggregateZero>(PC)) {
Duncan Sandsca0ed742007-11-05 00:04:43 +0000908 memset((void*)PA, 0, (size_t)TD->getABITypeSize(PC->getType()));
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000909 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(PC)) {
Duncan Sandsca0ed742007-11-05 00:04:43 +0000910 unsigned ElementSize =
911 TD->getABITypeSize(CPA->getType()->getElementType());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000912 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
913 WorkList.push_back(CPair(CPA->getOperand(i), PA+i*ElementSize));
914 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(PC)) {
915 const StructLayout *SL =
916 TD->getStructLayout(cast<StructType>(CPS->getType()));
917 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
Chris Lattnerb1919e22007-02-10 19:55:17 +0000918 WorkList.push_back(CPair(CPS->getOperand(i),
919 PA+SL->getElementOffset(i)));
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000920 } else {
921 cerr << "Bad Type: " << *PC->getType() << "\n";
922 assert(0 && "Unknown constant type to initialize memory with!");
923 }
924 }
925}
926
927MachOSym::MachOSym(const GlobalValue *gv, std::string name, uint8_t sect,
928 TargetMachine &TM) :
929 GV(gv), n_strx(0), n_type(sect == NO_SECT ? N_UNDF : N_SECT), n_sect(sect),
930 n_desc(0), n_value(0) {
931
932 const TargetAsmInfo *TAI = TM.getTargetAsmInfo();
933
Nate Begeman94be2482006-09-08 22:42:09 +0000934 switch (GV->getLinkage()) {
935 default:
936 assert(0 && "Unexpected linkage type!");
937 break;
938 case GlobalValue::WeakLinkage:
939 case GlobalValue::LinkOnceLinkage:
940 assert(!isa<Function>(gv) && "Unexpected linkage type for Function!");
941 case GlobalValue::ExternalLinkage:
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000942 GVName = TAI->getGlobalPrefix() + name;
Nate Begeman6635f352007-01-26 22:39:48 +0000943 n_type |= GV->hasHiddenVisibility() ? N_PEXT : N_EXT;
Nate Begeman94be2482006-09-08 22:42:09 +0000944 break;
945 case GlobalValue::InternalLinkage:
Nate Begeman6635f352007-01-26 22:39:48 +0000946 GVName = TAI->getGlobalPrefix() + name;
Nate Begeman94be2482006-09-08 22:42:09 +0000947 break;
948 }
949}