blob: 92b3eb4311c348c4b72115baaf5aa827446236a6 [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
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +0000128 virtual intptr_t getLabelAddress(uint64_t Label) const {
129 assert(0 && "get Label not implemented");
130 abort();
131 return 0;
132 }
133
134 virtual void emitLabel(uint64_t LabelID) {
135 assert(0 && "emit Label not implemented");
136 abort();
137 }
138
139
140 virtual void setModuleInfo(llvm::MachineModuleInfo* MMI) { }
141
Nate Begemaneb883af2006-08-23 21:08:52 +0000142 /// JIT SPECIFIC FUNCTIONS - DO NOT IMPLEMENT THESE HERE!
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000143 virtual void startFunctionStub(unsigned StubSize, unsigned Alignment = 1) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000144 assert(0 && "JIT specific function called!");
145 abort();
146 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000147 virtual void *finishFunctionStub(const Function *F) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000148 assert(0 && "JIT specific function called!");
149 abort();
150 return 0;
151 }
152 };
153}
154
155/// startFunction - This callback is invoked when a new machine function is
156/// about to be emitted.
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000157void MachOCodeEmitter::startFunction(MachineFunction &MF) {
158 const TargetData *TD = TM.getTargetData();
159 const Function *F = MF.getFunction();
160
Nate Begemaneb883af2006-08-23 21:08:52 +0000161 // Align the output buffer to the appropriate alignment, power of 2.
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000162 unsigned FnAlign = F->getAlignment();
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000163 unsigned TDAlign = TD->getPrefTypeAlignment(F->getType());
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000164 unsigned Align = Log2_32(std::max(FnAlign, TDAlign));
165 assert(!(Align & (Align-1)) && "Alignment is not a power of two!");
Nate Begemaneb883af2006-08-23 21:08:52 +0000166
167 // Get the Mach-O Section that this function belongs in.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000168 MachOWriter::MachOSection *MOS = MOW.getTextSection();
Nate Begemaneb883af2006-08-23 21:08:52 +0000169
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000170 // FIXME: better memory management
Nate Begemaneb883af2006-08-23 21:08:52 +0000171 MOS->SectionData.reserve(4096);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000172 BufferBegin = &MOS->SectionData[0];
Nate Begemaneb883af2006-08-23 21:08:52 +0000173 BufferEnd = BufferBegin + MOS->SectionData.capacity();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000174
Nate Begeman6635f352007-01-26 22:39:48 +0000175 // Upgrade the section alignment if required.
176 if (MOS->align < Align) MOS->align = Align;
177
178 // Round the size up to the correct alignment for starting the new function.
179 if ((MOS->size & ((1 << Align) - 1)) != 0) {
180 MOS->size += (1 << Align);
181 MOS->size &= ~((1 << Align) - 1);
182 }
183
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000184 // FIXME: Using MOS->size directly here instead of calculating it from the
185 // output buffer size (impossible because the code emitter deals only in raw
186 // bytes) forces us to manually synchronize size and write padding zero bytes
187 // to the output buffer for all non-text sections. For text sections, we do
188 // not synchonize the output buffer, and we just blow up if anyone tries to
189 // write non-code to it. An assert should probably be added to
190 // AddSymbolToSection to prevent calling it on the text section.
Nate Begemaneb883af2006-08-23 21:08:52 +0000191 CurBufferPtr = BufferBegin + MOS->size;
192
Nate Begeman019f8512006-09-10 23:03:44 +0000193 // Clear per-function data structures.
194 CPLocations.clear();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000195 CPSections.clear();
Nate Begeman019f8512006-09-10 23:03:44 +0000196 JTLocations.clear();
Nate Begemaneb883af2006-08-23 21:08:52 +0000197 MBBLocations.clear();
198}
199
200/// finishFunction - This callback is invoked after the function is completely
201/// finished.
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000202bool MachOCodeEmitter::finishFunction(MachineFunction &MF) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000203 // Get the Mach-O Section that this function belongs in.
204 MachOWriter::MachOSection *MOS = MOW.getTextSection();
205
Nate Begemaneb883af2006-08-23 21:08:52 +0000206 // Get a symbol for the function to add to the symbol table
Nate Begeman6635f352007-01-26 22:39:48 +0000207 // FIXME: it seems like we should call something like AddSymbolToSection
208 // in startFunction rather than changing the section size and symbol n_value
209 // here.
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000210 const GlobalValue *FuncV = MF.getFunction();
Bill Wendling203d3e42007-01-17 22:22:31 +0000211 MachOSym FnSym(FuncV, MOW.Mang->getValueName(FuncV), MOS->Index, TM);
Nate Begeman6635f352007-01-26 22:39:48 +0000212 FnSym.n_value = MOS->size;
213 MOS->size = CurBufferPtr - BufferBegin;
214
Nate Begeman019f8512006-09-10 23:03:44 +0000215 // Emit constant pool to appropriate section(s)
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000216 emitConstantPool(MF.getConstantPool());
Nate Begeman019f8512006-09-10 23:03:44 +0000217
218 // Emit jump tables to appropriate section
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000219 emitJumpTables(MF.getJumpTableInfo());
Nate Begemaneb883af2006-08-23 21:08:52 +0000220
Nate Begeman019f8512006-09-10 23:03:44 +0000221 // If we have emitted any relocations to function-specific objects such as
222 // basic blocks, constant pools entries, or jump tables, record their
223 // addresses now so that we can rewrite them with the correct addresses
224 // later.
Nate Begemaneb883af2006-08-23 21:08:52 +0000225 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
226 MachineRelocation &MR = Relocations[i];
Nate Begeman019f8512006-09-10 23:03:44 +0000227 intptr_t Addr;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000228
Nate Begemaneb883af2006-08-23 21:08:52 +0000229 if (MR.isBasicBlock()) {
Nate Begeman019f8512006-09-10 23:03:44 +0000230 Addr = getMachineBasicBlockAddress(MR.getBasicBlock());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000231 MR.setConstantVal(MOS->Index);
232 MR.setResultPointer((void*)Addr);
233 } else if (MR.isJumpTableIndex()) {
234 Addr = getJumpTableEntryAddress(MR.getJumpTableIndex());
235 MR.setConstantVal(MOW.getJumpTableSection()->Index);
236 MR.setResultPointer((void*)Addr);
Nate Begeman019f8512006-09-10 23:03:44 +0000237 } else if (MR.isConstantPoolIndex()) {
238 Addr = getConstantPoolEntryAddress(MR.getConstantPoolIndex());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000239 MR.setConstantVal(CPSections[MR.getConstantPoolIndex()]);
240 MR.setResultPointer((void*)Addr);
Nate Begemanfec910c2007-02-28 07:40:50 +0000241 } else if (MR.isGlobalValue()) {
242 // FIXME: This should be a set or something that uniques
243 MOW.PendingGlobals.push_back(MR.getGlobalValue());
244 } else {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000245 assert(0 && "Unhandled relocation type");
Nate Begemaneb883af2006-08-23 21:08:52 +0000246 }
Nate Begeman019f8512006-09-10 23:03:44 +0000247 MOS->Relocations.push_back(MR);
Nate Begemaneb883af2006-08-23 21:08:52 +0000248 }
249 Relocations.clear();
250
251 // Finally, add it to the symtab.
252 MOW.SymbolTable.push_back(FnSym);
253 return false;
254}
255
Nate Begeman019f8512006-09-10 23:03:44 +0000256/// emitConstantPool - For each constant pool entry, figure out which section
257/// the constant should live in, allocate space for it, and emit it to the
258/// Section data buffer.
259void MachOCodeEmitter::emitConstantPool(MachineConstantPool *MCP) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000260 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
261 if (CP.empty()) return;
262
263 // FIXME: handle PIC codegen
Bill Wendling203d3e42007-01-17 22:22:31 +0000264 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000265 assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
266
267 // Although there is no strict necessity that I am aware of, we will do what
268 // gcc for OS X does and put each constant pool entry in a section of constant
269 // objects of a certain size. That means that float constants go in the
270 // literal4 section, and double objects go in literal8, etc.
271 //
272 // FIXME: revisit this decision if we ever do the "stick everything into one
273 // "giant object for PIC" optimization.
274 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
275 const Type *Ty = CP[i].getType();
Duncan Sandsca0ed742007-11-05 00:04:43 +0000276 unsigned Size = TM.getTargetData()->getABITypeSize(Ty);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000277
Nate Begeman1257c852007-01-29 21:20:42 +0000278 MachOWriter::MachOSection *Sec = MOW.getConstSection(CP[i].Val.ConstVal);
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000279 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000280
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000281 CPLocations.push_back(Sec->SectionData.size());
282 CPSections.push_back(Sec->Index);
283
284 // FIXME: remove when we have unified size + output buffer
285 Sec->size += Size;
286
287 // Allocate space in the section for the global.
288 // FIXME: need alignment?
289 // FIXME: share between here and AddSymbolToSection?
290 for (unsigned j = 0; j < Size; ++j)
Bill Wendling203d3e42007-01-17 22:22:31 +0000291 SecDataOut.outbyte(0);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000292
293 MOW.InitMem(CP[i].Val.ConstVal, &Sec->SectionData[0], CPLocations[i],
Bill Wendling203d3e42007-01-17 22:22:31 +0000294 TM.getTargetData(), Sec->Relocations);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000295 }
Nate Begeman019f8512006-09-10 23:03:44 +0000296}
297
298/// emitJumpTables - Emit all the jump tables for a given jump table info
299/// record to the appropriate section.
300void MachOCodeEmitter::emitJumpTables(MachineJumpTableInfo *MJTI) {
301 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
302 if (JT.empty()) return;
303
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000304 // FIXME: handle PIC codegen
Bill Wendling203d3e42007-01-17 22:22:31 +0000305 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
Nate Begeman019f8512006-09-10 23:03:44 +0000306 assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
307
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000308 MachOWriter::MachOSection *Sec = MOW.getJumpTableSection();
309 unsigned TextSecIndex = MOW.getTextSection()->Index;
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000310 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
Nate Begeman019f8512006-09-10 23:03:44 +0000311
312 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
313 // For each jump table, record its offset from the start of the section,
314 // reserve space for the relocations to the MBBs, and add the relocations.
315 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000316 JTLocations.push_back(Sec->SectionData.size());
Nate Begeman019f8512006-09-10 23:03:44 +0000317 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000318 MachineRelocation MR(MOW.GetJTRelocation(Sec->SectionData.size(),
Nate Begeman019f8512006-09-10 23:03:44 +0000319 MBBs[mi]));
320 MR.setResultPointer((void *)JTLocations[i]);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000321 MR.setConstantVal(TextSecIndex);
322 Sec->Relocations.push_back(MR);
Bill Wendling203d3e42007-01-17 22:22:31 +0000323 SecDataOut.outaddr(0);
Nate Begeman019f8512006-09-10 23:03:44 +0000324 }
325 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000326 // FIXME: remove when we have unified size + output buffer
327 Sec->size = Sec->SectionData.size();
Nate Begeman019f8512006-09-10 23:03:44 +0000328}
329
Nate Begemaneb883af2006-08-23 21:08:52 +0000330//===----------------------------------------------------------------------===//
331// MachOWriter Implementation
332//===----------------------------------------------------------------------===//
333
Devang Patel19974732007-05-03 01:11:54 +0000334char MachOWriter::ID = 0;
Devang Patel794fd752007-05-01 21:15:47 +0000335MachOWriter::MachOWriter(std::ostream &o, TargetMachine &tm)
336 : MachineFunctionPass((intptr_t)&ID), O(o), TM(tm) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000337 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
338 isLittleEndian = TM.getTargetData()->isLittleEndian();
339
340 // Create the machine code emitter object for this target.
Bill Wendlinge9116152007-01-17 09:06:13 +0000341 MCE = new MachOCodeEmitter(*this);
Nate Begemaneb883af2006-08-23 21:08:52 +0000342}
343
344MachOWriter::~MachOWriter() {
345 delete MCE;
346}
347
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000348void MachOWriter::AddSymbolToSection(MachOSection *Sec, GlobalVariable *GV) {
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000349 const Type *Ty = GV->getType()->getElementType();
Duncan Sandsca0ed742007-11-05 00:04:43 +0000350 unsigned Size = TM.getTargetData()->getABITypeSize(Ty);
Duncan Sandsd1025932008-01-29 06:23:44 +0000351 unsigned Align = TM.getTargetData()->getPreferredAlignment(GV);
352
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000353 // Reserve space in the .bss section for this symbol while maintaining the
354 // desired section alignment, which must be at least as much as required by
355 // this symbol.
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000356 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000357
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000358 if (Align) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000359 uint64_t OrigSize = Sec->size;
360 Align = Log2_32(Align);
361 Sec->align = std::max(unsigned(Sec->align), Align);
362 Sec->size = (Sec->size + Align - 1) & ~(Align-1);
363
364 // Add alignment padding to buffer as well.
365 // FIXME: remove when we have unified size + output buffer
366 unsigned AlignedSize = Sec->size - OrigSize;
367 for (unsigned i = 0; i < AlignedSize; ++i)
Bill Wendling203d3e42007-01-17 22:22:31 +0000368 SecDataOut.outbyte(0);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000369 }
Nate Begemanfec910c2007-02-28 07:40:50 +0000370 // Globals without external linkage apparently do not go in the symbol table.
371 if (GV->getLinkage() != GlobalValue::InternalLinkage) {
372 MachOSym Sym(GV, Mang->getValueName(GV), Sec->Index, TM);
373 Sym.n_value = Sec->size;
374 SymbolTable.push_back(Sym);
375 }
376
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000377 // Record the offset of the symbol, and then allocate space for it.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000378 // FIXME: remove when we have unified size + output buffer
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000379 Sec->size += Size;
Nate Begemanfec910c2007-02-28 07:40:50 +0000380
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000381 // Now that we know what section the GlovalVariable is going to be emitted
382 // into, update our mappings.
383 // FIXME: We may also need to update this when outputting non-GlobalVariable
384 // GlobalValues such as functions.
385 GVSection[GV] = Sec;
386 GVOffset[GV] = Sec->SectionData.size();
387
388 // Allocate space in the section for the global.
389 for (unsigned i = 0; i < Size; ++i)
Bill Wendling203d3e42007-01-17 22:22:31 +0000390 SecDataOut.outbyte(0);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000391}
392
Nate Begemaneb883af2006-08-23 21:08:52 +0000393void MachOWriter::EmitGlobal(GlobalVariable *GV) {
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000394 const Type *Ty = GV->getType()->getElementType();
Duncan Sandsca0ed742007-11-05 00:04:43 +0000395 unsigned Size = TM.getTargetData()->getABITypeSize(Ty);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000396 bool NoInit = !GV->hasInitializer();
Nate Begemand2030e62006-08-26 15:46:34 +0000397
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000398 // If this global has a zero initializer, it is part of the .bss or common
399 // section.
400 if (NoInit || GV->getInitializer()->isNullValue()) {
401 // If this global is part of the common block, add it now. Variables are
402 // part of the common block if they are zero initialized and allowed to be
403 // merged with other symbols.
404 if (NoInit || GV->hasLinkOnceLinkage() || GV->hasWeakLinkage()) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000405 MachOSym ExtOrCommonSym(GV, Mang->getValueName(GV), MachOSym::NO_SECT,TM);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000406 // For undefined (N_UNDF) external (N_EXT) types, n_value is the size in
407 // bytes of the symbol.
408 ExtOrCommonSym.n_value = Size;
Nate Begemanfec910c2007-02-28 07:40:50 +0000409 SymbolTable.push_back(ExtOrCommonSym);
410 // Remember that we've seen this symbol
411 GVOffset[GV] = Size;
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000412 return;
413 }
414 // Otherwise, this symbol is part of the .bss section.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000415 MachOSection *BSS = getBSSSection();
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000416 AddSymbolToSection(BSS, GV);
417 return;
418 }
419
420 // Scalar read-only data goes in a literal section if the scalar is 4, 8, or
421 // 16 bytes, or a cstring. Other read only data goes into a regular const
422 // section. Read-write data goes in the data section.
Nate Begeman1257c852007-01-29 21:20:42 +0000423 MachOSection *Sec = GV->isConstant() ? getConstSection(GV->getInitializer()) :
424 getDataSection();
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000425 AddSymbolToSection(Sec, GV);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000426 InitMem(GV->getInitializer(), &Sec->SectionData[0], GVOffset[GV],
427 TM.getTargetData(), Sec->Relocations);
Nate Begemaneb883af2006-08-23 21:08:52 +0000428}
429
430
431bool MachOWriter::runOnMachineFunction(MachineFunction &MF) {
432 // Nothing to do here, this is all done through the MCE object.
433 return false;
434}
435
436bool MachOWriter::doInitialization(Module &M) {
437 // Set the magic value, now that we know the pointer size and endianness
438 Header.setMagic(isLittleEndian, is64Bit);
439
440 // Set the file type
441 // FIXME: this only works for object files, we do not support the creation
442 // of dynamic libraries or executables at this time.
443 Header.filetype = MachOHeader::MH_OBJECT;
444
445 Mang = new Mangler(M);
446 return false;
447}
448
449/// doFinalization - Now that the module has been completely processed, emit
450/// the Mach-O file to 'O'.
451bool MachOWriter::doFinalization(Module &M) {
Nate Begemand2030e62006-08-26 15:46:34 +0000452 // FIXME: we don't handle debug info yet, we should probably do that.
453
Nate Begemaneb883af2006-08-23 21:08:52 +0000454 // Okay, the.text section has been completed, build the .data, .bss, and
455 // "common" sections next.
456 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
457 I != E; ++I)
458 EmitGlobal(I);
459
460 // Emit the header and load commands.
461 EmitHeaderAndLoadCommands();
462
Nate Begeman019f8512006-09-10 23:03:44 +0000463 // Emit the various sections and their relocation info.
Nate Begemaneb883af2006-08-23 21:08:52 +0000464 EmitSections();
465
Nate Begemand2030e62006-08-26 15:46:34 +0000466 // Write the symbol table and the string table to the end of the file.
467 O.write((char*)&SymT[0], SymT.size());
468 O.write((char*)&StrT[0], StrT.size());
Nate Begemaneb883af2006-08-23 21:08:52 +0000469
470 // We are done with the abstract symbols.
471 SectionList.clear();
472 SymbolTable.clear();
473 DynamicSymbolTable.clear();
474
475 // Release the name mangler object.
476 delete Mang; Mang = 0;
477 return false;
478}
479
480void MachOWriter::EmitHeaderAndLoadCommands() {
481 // Step #0: Fill in the segment load command size, since we need it to figure
482 // out the rest of the header fields
483 MachOSegment SEG("", is64Bit);
484 SEG.nsects = SectionList.size();
485 SEG.cmdsize = SEG.cmdSize(is64Bit) +
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000486 SEG.nsects * SectionList[0]->cmdSize(is64Bit);
Nate Begemaneb883af2006-08-23 21:08:52 +0000487
488 // Step #1: calculate the number of load commands. We always have at least
489 // one, for the LC_SEGMENT load command, plus two for the normal
490 // and dynamic symbol tables, if there are any symbols.
491 Header.ncmds = SymbolTable.empty() ? 1 : 3;
492
493 // Step #2: calculate the size of the load commands
494 Header.sizeofcmds = SEG.cmdsize;
495 if (!SymbolTable.empty())
496 Header.sizeofcmds += SymTab.cmdsize + DySymTab.cmdsize;
497
498 // Step #3: write the header to the file
499 // Local alias to shortenify coming code.
500 DataBuffer &FH = Header.HeaderData;
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000501 OutputBuffer FHOut(FH, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000502
503 FHOut.outword(Header.magic);
Bill Wendling2b721822007-01-24 07:13:56 +0000504 FHOut.outword(TM.getMachOWriterInfo()->getCPUType());
505 FHOut.outword(TM.getMachOWriterInfo()->getCPUSubType());
Bill Wendling203d3e42007-01-17 22:22:31 +0000506 FHOut.outword(Header.filetype);
507 FHOut.outword(Header.ncmds);
508 FHOut.outword(Header.sizeofcmds);
509 FHOut.outword(Header.flags);
Nate Begemaneb883af2006-08-23 21:08:52 +0000510 if (is64Bit)
Bill Wendling203d3e42007-01-17 22:22:31 +0000511 FHOut.outword(Header.reserved);
Nate Begemaneb883af2006-08-23 21:08:52 +0000512
513 // Step #4: Finish filling in the segment load command and write it out
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000514 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begemaneb883af2006-08-23 21:08:52 +0000515 E = SectionList.end(); I != E; ++I)
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000516 SEG.filesize += (*I)->size;
517
Nate Begemaneb883af2006-08-23 21:08:52 +0000518 SEG.vmsize = SEG.filesize;
519 SEG.fileoff = Header.cmdSize(is64Bit) + Header.sizeofcmds;
520
Bill Wendling203d3e42007-01-17 22:22:31 +0000521 FHOut.outword(SEG.cmd);
522 FHOut.outword(SEG.cmdsize);
523 FHOut.outstring(SEG.segname, 16);
524 FHOut.outaddr(SEG.vmaddr);
525 FHOut.outaddr(SEG.vmsize);
526 FHOut.outaddr(SEG.fileoff);
527 FHOut.outaddr(SEG.filesize);
528 FHOut.outword(SEG.maxprot);
529 FHOut.outword(SEG.initprot);
530 FHOut.outword(SEG.nsects);
531 FHOut.outword(SEG.flags);
Nate Begemaneb883af2006-08-23 21:08:52 +0000532
Nate Begeman94be2482006-09-08 22:42:09 +0000533 // Step #5: Finish filling in the fields of the MachOSections
534 uint64_t currentAddr = 0;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000535 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begemaneb883af2006-08-23 21:08:52 +0000536 E = SectionList.end(); I != E; ++I) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000537 MachOSection *MOS = *I;
538 MOS->addr = currentAddr;
539 MOS->offset = currentAddr + SEG.fileoff;
Nate Begeman019f8512006-09-10 23:03:44 +0000540
Nate Begeman94be2482006-09-08 22:42:09 +0000541 // FIXME: do we need to do something with alignment here?
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000542 currentAddr += MOS->size;
Nate Begeman94be2482006-09-08 22:42:09 +0000543 }
544
Nate Begemanfec910c2007-02-28 07:40:50 +0000545 // Step #6: Emit the symbol table to temporary buffers, so that we know the
546 // size of the string table when we write the next load command. This also
547 // sorts and assigns indices to each of the symbols, which is necessary for
548 // emitting relocations to externally-defined objects.
549 BufferSymbolAndStringTable();
550
551 // Step #7: Calculate the number of relocations for each section and write out
Nate Begeman94be2482006-09-08 22:42:09 +0000552 // the section commands for each section
553 currentAddr += SEG.fileoff;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000554 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman94be2482006-09-08 22:42:09 +0000555 E = SectionList.end(); I != E; ++I) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000556 MachOSection *MOS = *I;
557 // Convert the relocations to target-specific relocations, and fill in the
558 // relocation offset for this section.
559 CalculateRelocations(*MOS);
560 MOS->reloff = MOS->nreloc ? currentAddr : 0;
561 currentAddr += MOS->nreloc * 8;
Nate Begeman94be2482006-09-08 22:42:09 +0000562
563 // write the finalized section command to the output buffer
Bill Wendling203d3e42007-01-17 22:22:31 +0000564 FHOut.outstring(MOS->sectname, 16);
565 FHOut.outstring(MOS->segname, 16);
566 FHOut.outaddr(MOS->addr);
567 FHOut.outaddr(MOS->size);
568 FHOut.outword(MOS->offset);
569 FHOut.outword(MOS->align);
570 FHOut.outword(MOS->reloff);
571 FHOut.outword(MOS->nreloc);
572 FHOut.outword(MOS->flags);
573 FHOut.outword(MOS->reserved1);
574 FHOut.outword(MOS->reserved2);
Nate Begemaneb883af2006-08-23 21:08:52 +0000575 if (is64Bit)
Bill Wendling203d3e42007-01-17 22:22:31 +0000576 FHOut.outword(MOS->reserved3);
Nate Begemaneb883af2006-08-23 21:08:52 +0000577 }
578
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000579 // Step #8: Emit LC_SYMTAB/LC_DYSYMTAB load commands
Nate Begeman94be2482006-09-08 22:42:09 +0000580 SymTab.symoff = currentAddr;
Nate Begemaneb883af2006-08-23 21:08:52 +0000581 SymTab.nsyms = SymbolTable.size();
Nate Begemand2030e62006-08-26 15:46:34 +0000582 SymTab.stroff = SymTab.symoff + SymT.size();
583 SymTab.strsize = StrT.size();
Bill Wendling203d3e42007-01-17 22:22:31 +0000584 FHOut.outword(SymTab.cmd);
585 FHOut.outword(SymTab.cmdsize);
586 FHOut.outword(SymTab.symoff);
587 FHOut.outword(SymTab.nsyms);
588 FHOut.outword(SymTab.stroff);
589 FHOut.outword(SymTab.strsize);
Nate Begemaneb883af2006-08-23 21:08:52 +0000590
591 // FIXME: set DySymTab fields appropriately
Nate Begemand2030e62006-08-26 15:46:34 +0000592 // We should probably just update these in BufferSymbolAndStringTable since
593 // thats where we're partitioning up the different kinds of symbols.
Bill Wendling203d3e42007-01-17 22:22:31 +0000594 FHOut.outword(DySymTab.cmd);
595 FHOut.outword(DySymTab.cmdsize);
596 FHOut.outword(DySymTab.ilocalsym);
597 FHOut.outword(DySymTab.nlocalsym);
598 FHOut.outword(DySymTab.iextdefsym);
599 FHOut.outword(DySymTab.nextdefsym);
600 FHOut.outword(DySymTab.iundefsym);
601 FHOut.outword(DySymTab.nundefsym);
602 FHOut.outword(DySymTab.tocoff);
603 FHOut.outword(DySymTab.ntoc);
604 FHOut.outword(DySymTab.modtaboff);
605 FHOut.outword(DySymTab.nmodtab);
606 FHOut.outword(DySymTab.extrefsymoff);
607 FHOut.outword(DySymTab.nextrefsyms);
608 FHOut.outword(DySymTab.indirectsymoff);
609 FHOut.outword(DySymTab.nindirectsyms);
610 FHOut.outword(DySymTab.extreloff);
611 FHOut.outword(DySymTab.nextrel);
612 FHOut.outword(DySymTab.locreloff);
613 FHOut.outword(DySymTab.nlocrel);
Nate Begemaneb883af2006-08-23 21:08:52 +0000614
615 O.write((char*)&FH[0], FH.size());
616}
617
618/// EmitSections - Now that we have constructed the file header and load
619/// commands, emit the data for each section to the file.
620void MachOWriter::EmitSections() {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000621 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman019f8512006-09-10 23:03:44 +0000622 E = SectionList.end(); I != E; ++I)
623 // Emit the contents of each section
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000624 O.write((char*)&(*I)->SectionData[0], (*I)->size);
625 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman019f8512006-09-10 23:03:44 +0000626 E = SectionList.end(); I != E; ++I)
627 // Emit the relocation entry data for each section.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000628 O.write((char*)&(*I)->RelocBuffer[0], (*I)->RelocBuffer.size());
Nate Begemaneb883af2006-08-23 21:08:52 +0000629}
630
Nate Begemand2030e62006-08-26 15:46:34 +0000631/// PartitionByLocal - Simple boolean predicate that returns true if Sym is
632/// a local symbol rather than an external symbol.
633bool MachOWriter::PartitionByLocal(const MachOSym &Sym) {
Nate Begemand2030e62006-08-26 15:46:34 +0000634 return (Sym.n_type & (MachOSym::N_EXT | MachOSym::N_PEXT)) == 0;
Nate Begemaneb883af2006-08-23 21:08:52 +0000635}
636
Nate Begemand2030e62006-08-26 15:46:34 +0000637/// PartitionByDefined - Simple boolean predicate that returns true if Sym is
638/// defined in this module.
639bool MachOWriter::PartitionByDefined(const MachOSym &Sym) {
640 // FIXME: Do N_ABS or N_INDR count as defined?
641 return (Sym.n_type & MachOSym::N_SECT) == MachOSym::N_SECT;
642}
Nate Begemaneb883af2006-08-23 21:08:52 +0000643
Nate Begemand2030e62006-08-26 15:46:34 +0000644/// BufferSymbolAndStringTable - Sort the symbols we encountered and assign them
645/// each a string table index so that they appear in the correct order in the
646/// output file.
647void MachOWriter::BufferSymbolAndStringTable() {
648 // The order of the symbol table is:
649 // 1. local symbols
650 // 2. defined external symbols (sorted by name)
651 // 3. undefined external symbols (sorted by name)
652
Nate Begemanfec910c2007-02-28 07:40:50 +0000653 // Before sorting the symbols, check the PendingGlobals for any undefined
654 // globals that need to be put in the symbol table.
655 for (std::vector<GlobalValue*>::iterator I = PendingGlobals.begin(),
656 E = PendingGlobals.end(); I != E; ++I) {
657 if (GVOffset[*I] == 0 && GVSection[*I] == 0) {
658 MachOSym UndfSym(*I, Mang->getValueName(*I), MachOSym::NO_SECT, TM);
659 SymbolTable.push_back(UndfSym);
660 GVOffset[*I] = -1;
661 }
662 }
663
Nate Begemand2030e62006-08-26 15:46:34 +0000664 // Sort the symbols by name, so that when we partition the symbols by scope
665 // of definition, we won't have to sort by name within each partition.
666 std::sort(SymbolTable.begin(), SymbolTable.end(), MachOSymCmp());
667
668 // Parition the symbol table entries so that all local symbols come before
669 // all symbols with external linkage. { 1 | 2 3 }
670 std::partition(SymbolTable.begin(), SymbolTable.end(), PartitionByLocal);
671
672 // Advance iterator to beginning of external symbols and partition so that
673 // all external symbols defined in this module come before all external
674 // symbols defined elsewhere. { 1 | 2 | 3 }
675 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
676 E = SymbolTable.end(); I != E; ++I) {
677 if (!PartitionByLocal(*I)) {
678 std::partition(I, E, PartitionByDefined);
679 break;
680 }
681 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000682
683 // Calculate the starting index for each of the local, extern defined, and
684 // undefined symbols, as well as the number of each to put in the LC_DYSYMTAB
685 // load command.
686 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
687 E = SymbolTable.end(); I != E; ++I) {
688 if (PartitionByLocal(*I)) {
689 ++DySymTab.nlocalsym;
690 ++DySymTab.iextdefsym;
Nate Begeman6635f352007-01-26 22:39:48 +0000691 ++DySymTab.iundefsym;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000692 } else if (PartitionByDefined(*I)) {
693 ++DySymTab.nextdefsym;
694 ++DySymTab.iundefsym;
695 } else {
696 ++DySymTab.nundefsym;
697 }
698 }
Nate Begemand2030e62006-08-26 15:46:34 +0000699
Nate Begemaneb883af2006-08-23 21:08:52 +0000700 // Write out a leading zero byte when emitting string table, for n_strx == 0
701 // which means an empty string.
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000702 OutputBuffer StrTOut(StrT, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000703 StrTOut.outbyte(0);
Nate Begemaneb883af2006-08-23 21:08:52 +0000704
Nate Begemand2030e62006-08-26 15:46:34 +0000705 // The order of the string table is:
706 // 1. strings for external symbols
707 // 2. strings for local symbols
708 // Since this is the opposite order from the symbol table, which we have just
709 // sorted, we can walk the symbol table backwards to output the string table.
710 for (std::vector<MachOSym>::reverse_iterator I = SymbolTable.rbegin(),
711 E = SymbolTable.rend(); I != E; ++I) {
712 if (I->GVName == "") {
713 I->n_strx = 0;
714 } else {
715 I->n_strx = StrT.size();
Bill Wendling203d3e42007-01-17 22:22:31 +0000716 StrTOut.outstring(I->GVName, I->GVName.length()+1);
Nate Begemand2030e62006-08-26 15:46:34 +0000717 }
Nate Begemaneb883af2006-08-23 21:08:52 +0000718 }
Nate Begemand2030e62006-08-26 15:46:34 +0000719
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000720 OutputBuffer SymTOut(SymT, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000721
Nate Begemanfec910c2007-02-28 07:40:50 +0000722 unsigned index = 0;
Nate Begemand2030e62006-08-26 15:46:34 +0000723 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
Nate Begemanfec910c2007-02-28 07:40:50 +0000724 E = SymbolTable.end(); I != E; ++I, ++index) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000725 // Add the section base address to the section offset in the n_value field
726 // to calculate the full address.
727 // FIXME: handle symbols where the n_value field is not the address
728 GlobalValue *GV = const_cast<GlobalValue*>(I->GV);
729 if (GV && GVSection[GV])
730 I->n_value += GVSection[GV]->addr;
Nate Begemanfec910c2007-02-28 07:40:50 +0000731 if (GV && (GVOffset[GV] == -1))
732 GVOffset[GV] = index;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000733
Nate Begemand2030e62006-08-26 15:46:34 +0000734 // Emit nlist to buffer
Bill Wendling203d3e42007-01-17 22:22:31 +0000735 SymTOut.outword(I->n_strx);
736 SymTOut.outbyte(I->n_type);
737 SymTOut.outbyte(I->n_sect);
738 SymTOut.outhalf(I->n_desc);
739 SymTOut.outaddr(I->n_value);
Nate Begemand2030e62006-08-26 15:46:34 +0000740 }
Nate Begemaneb883af2006-08-23 21:08:52 +0000741}
Nate Begeman94be2482006-09-08 22:42:09 +0000742
Nate Begeman019f8512006-09-10 23:03:44 +0000743/// CalculateRelocations - For each MachineRelocation in the current section,
744/// calculate the index of the section containing the object to be relocated,
745/// and the offset into that section. From this information, create the
746/// appropriate target-specific MachORelocation type and add buffer it to be
747/// written out after we are finished writing out sections.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000748void MachOWriter::CalculateRelocations(MachOSection &MOS) {
Nate Begeman019f8512006-09-10 23:03:44 +0000749 for (unsigned i = 0, e = MOS.Relocations.size(); i != e; ++i) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000750 MachineRelocation &MR = MOS.Relocations[i];
751 unsigned TargetSection = MR.getConstantVal();
Nate Begemanaf806382007-03-03 06:18:18 +0000752 unsigned TargetAddr = 0;
753 unsigned TargetIndex = 0;
Nate Begeman6635f352007-01-26 22:39:48 +0000754
755 // This is a scattered relocation entry if it points to a global value with
756 // a non-zero offset.
757 bool Scattered = false;
Nate Begemanfec910c2007-02-28 07:40:50 +0000758 bool Extern = false;
Nate Begemanaf806382007-03-03 06:18:18 +0000759
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000760 // Since we may not have seen the GlobalValue we were interested in yet at
761 // the time we emitted the relocation for it, fix it up now so that it
762 // points to the offset into the correct section.
763 if (MR.isGlobalValue()) {
764 GlobalValue *GV = MR.getGlobalValue();
765 MachOSection *MOSPtr = GVSection[GV];
Nate Begeman6635f352007-01-26 22:39:48 +0000766 intptr_t Offset = GVOffset[GV];
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000767
Nate Begemanfec910c2007-02-28 07:40:50 +0000768 // If we have never seen the global before, it must be to a symbol
769 // defined in another module (N_UNDF).
Nate Begeman1257c852007-01-29 21:20:42 +0000770 if (!MOSPtr) {
Nate Begemanfec910c2007-02-28 07:40:50 +0000771 // FIXME: need to append stub suffix
772 Extern = true;
773 TargetAddr = 0;
774 TargetIndex = GVOffset[GV];
775 } else {
776 Scattered = TargetSection != 0;
777 TargetSection = MOSPtr->Index;
Nate Begemanaf806382007-03-03 06:18:18 +0000778 }
779 MR.setResultPointer((void*)Offset);
780 }
781
782 // If the symbol is locally defined, pass in the address of the section and
783 // the section index to the code which will generate the target relocation.
784 if (!Extern) {
Nate Begemanfec910c2007-02-28 07:40:50 +0000785 MachOSection &To = *SectionList[TargetSection - 1];
786 TargetAddr = To.addr;
787 TargetIndex = To.Index;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000788 }
Bill Wendling886b4122007-02-03 02:39:40 +0000789
790 OutputBuffer RelocOut(MOS.RelocBuffer, is64Bit, isLittleEndian);
791 OutputBuffer SecOut(MOS.SectionData, is64Bit, isLittleEndian);
Nate Begemanfec910c2007-02-28 07:40:50 +0000792
793 MOS.nreloc += GetTargetRelocation(MR, MOS.Index, TargetAddr, TargetIndex,
794 RelocOut, SecOut, Scattered, Extern);
Nate Begeman019f8512006-09-10 23:03:44 +0000795 }
Nate Begeman019f8512006-09-10 23:03:44 +0000796}
797
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000798// InitMem - Write the value of a Constant to the specified memory location,
799// converting it into bytes and relocations.
800void MachOWriter::InitMem(const Constant *C, void *Addr, intptr_t Offset,
801 const TargetData *TD,
802 std::vector<MachineRelocation> &MRs) {
803 typedef std::pair<const Constant*, intptr_t> CPair;
804 std::vector<CPair> WorkList;
805
806 WorkList.push_back(CPair(C,(intptr_t)Addr + Offset));
807
Nate Begeman6635f352007-01-26 22:39:48 +0000808 intptr_t ScatteredOffset = 0;
809
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000810 while (!WorkList.empty()) {
811 const Constant *PC = WorkList.back().first;
812 intptr_t PA = WorkList.back().second;
813 WorkList.pop_back();
814
815 if (isa<UndefValue>(PC)) {
816 continue;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000817 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(PC)) {
Duncan Sandsca0ed742007-11-05 00:04:43 +0000818 unsigned ElementSize =
819 TD->getABITypeSize(CP->getType()->getElementType());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000820 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
821 WorkList.push_back(CPair(CP->getOperand(i), PA+i*ElementSize));
822 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(PC)) {
823 //
824 // FIXME: Handle ConstantExpression. See EE::getConstantValue()
825 //
826 switch (CE->getOpcode()) {
Nate Begeman6635f352007-01-26 22:39:48 +0000827 case Instruction::GetElementPtr: {
Chris Lattner7f6b9d22007-02-10 20:31:59 +0000828 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Nate Begeman6635f352007-01-26 22:39:48 +0000829 ScatteredOffset = TD->getIndexedOffset(CE->getOperand(0)->getType(),
Chris Lattner7f6b9d22007-02-10 20:31:59 +0000830 &Indices[0], Indices.size());
Nate Begeman6635f352007-01-26 22:39:48 +0000831 WorkList.push_back(CPair(CE->getOperand(0), PA));
832 break;
833 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000834 case Instruction::Add:
835 default:
836 cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
837 abort();
838 break;
839 }
840 } else if (PC->getType()->isFirstClassType()) {
841 unsigned char *ptr = (unsigned char *)PA;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000842 switch (PC->getType()->getTypeID()) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000843 case Type::IntegerTyID: {
844 unsigned NumBits = cast<IntegerType>(PC->getType())->getBitWidth();
845 uint64_t val = cast<ConstantInt>(PC)->getZExtValue();
846 if (NumBits <= 8)
847 ptr[0] = val;
848 else if (NumBits <= 16) {
849 if (TD->isBigEndian())
850 val = ByteSwap_16(val);
851 ptr[0] = val;
852 ptr[1] = val >> 8;
853 } else if (NumBits <= 32) {
854 if (TD->isBigEndian())
855 val = ByteSwap_32(val);
856 ptr[0] = val;
857 ptr[1] = val >> 8;
858 ptr[2] = val >> 16;
859 ptr[3] = val >> 24;
860 } else if (NumBits <= 64) {
861 if (TD->isBigEndian())
862 val = ByteSwap_64(val);
863 ptr[0] = val;
864 ptr[1] = val >> 8;
865 ptr[2] = val >> 16;
866 ptr[3] = val >> 24;
867 ptr[4] = val >> 32;
868 ptr[5] = val >> 40;
869 ptr[6] = val >> 48;
870 ptr[7] = val >> 56;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000871 } else {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000872 assert(0 && "Not implemented: bit widths > 64");
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000873 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000874 break;
875 }
876 case Type::FloatTyID: {
Dale Johannesen9d5f4562007-09-12 03:30:33 +0000877 uint32_t val = cast<ConstantFP>(PC)->getValueAPF().convertToAPInt().
878 getZExtValue();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000879 if (TD->isBigEndian())
880 val = ByteSwap_32(val);
881 ptr[0] = val;
882 ptr[1] = val >> 8;
883 ptr[2] = val >> 16;
884 ptr[3] = val >> 24;
885 break;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000886 }
887 case Type::DoubleTyID: {
Dale Johannesen9d5f4562007-09-12 03:30:33 +0000888 uint64_t val = cast<ConstantFP>(PC)->getValueAPF().convertToAPInt().
889 getZExtValue();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000890 if (TD->isBigEndian())
891 val = ByteSwap_64(val);
892 ptr[0] = val;
893 ptr[1] = val >> 8;
894 ptr[2] = val >> 16;
895 ptr[3] = val >> 24;
896 ptr[4] = val >> 32;
897 ptr[5] = val >> 40;
898 ptr[6] = val >> 48;
899 ptr[7] = val >> 56;
900 break;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000901 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000902 case Type::PointerTyID:
Nate Begeman6635f352007-01-26 22:39:48 +0000903 if (isa<ConstantPointerNull>(PC))
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000904 memset(ptr, 0, TD->getPointerSize());
Nate Begeman6635f352007-01-26 22:39:48 +0000905 else if (const GlobalValue* GV = dyn_cast<GlobalValue>(PC)) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000906 // FIXME: what about function stubs?
907 MRs.push_back(MachineRelocation::getGV(PA-(intptr_t)Addr,
908 MachineRelocation::VANILLA,
Nate Begeman6635f352007-01-26 22:39:48 +0000909 const_cast<GlobalValue*>(GV),
910 ScatteredOffset));
911 ScatteredOffset = 0;
912 } else
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000913 assert(0 && "Unknown constant pointer type!");
914 break;
915 default:
916 cerr << "ERROR: Constant unimp for type: " << *PC->getType() << "\n";
917 abort();
918 }
919 } else if (isa<ConstantAggregateZero>(PC)) {
Duncan Sandsca0ed742007-11-05 00:04:43 +0000920 memset((void*)PA, 0, (size_t)TD->getABITypeSize(PC->getType()));
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000921 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(PC)) {
Duncan Sandsca0ed742007-11-05 00:04:43 +0000922 unsigned ElementSize =
923 TD->getABITypeSize(CPA->getType()->getElementType());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000924 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
925 WorkList.push_back(CPair(CPA->getOperand(i), PA+i*ElementSize));
926 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(PC)) {
927 const StructLayout *SL =
928 TD->getStructLayout(cast<StructType>(CPS->getType()));
929 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
Chris Lattnerb1919e22007-02-10 19:55:17 +0000930 WorkList.push_back(CPair(CPS->getOperand(i),
931 PA+SL->getElementOffset(i)));
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000932 } else {
933 cerr << "Bad Type: " << *PC->getType() << "\n";
934 assert(0 && "Unknown constant type to initialize memory with!");
935 }
936 }
937}
938
939MachOSym::MachOSym(const GlobalValue *gv, std::string name, uint8_t sect,
940 TargetMachine &TM) :
941 GV(gv), n_strx(0), n_type(sect == NO_SECT ? N_UNDF : N_SECT), n_sect(sect),
942 n_desc(0), n_value(0) {
943
944 const TargetAsmInfo *TAI = TM.getTargetAsmInfo();
945
Nate Begeman94be2482006-09-08 22:42:09 +0000946 switch (GV->getLinkage()) {
947 default:
948 assert(0 && "Unexpected linkage type!");
949 break;
950 case GlobalValue::WeakLinkage:
951 case GlobalValue::LinkOnceLinkage:
952 assert(!isa<Function>(gv) && "Unexpected linkage type for Function!");
953 case GlobalValue::ExternalLinkage:
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000954 GVName = TAI->getGlobalPrefix() + name;
Nate Begeman6635f352007-01-26 22:39:48 +0000955 n_type |= GV->hasHiddenVisibility() ? N_PEXT : N_EXT;
Nate Begeman94be2482006-09-08 22:42:09 +0000956 break;
957 case GlobalValue::InternalLinkage:
Nate Begeman6635f352007-01-26 22:39:48 +0000958 GVName = TAI->getGlobalPrefix() + name;
Nate Begeman94be2482006-09-08 22:42:09 +0000959 break;
960 }
961}