1 //===-- MachOWriter.cpp - Target-independent Mach-O Writer code -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Nate Begeman and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the target-independent Mach-O writer. This file writes
11 // out the Mach-O file in the following order:
13 // #1 FatHeader (universal-only)
14 // #2 FatArch (universal-only, 1 per universal arch)
23 //===----------------------------------------------------------------------===//
25 #include "MachOWriter.h"
26 #include "llvm/Constants.h"
27 #include "llvm/DerivedTypes.h"
28 #include "llvm/Module.h"
29 #include "llvm/PassManager.h"
30 #include "llvm/CodeGen/FileWriters.h"
31 #include "llvm/CodeGen/MachineCodeEmitter.h"
32 #include "llvm/CodeGen/MachineConstantPool.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/ExecutionEngine/ExecutionEngine.h"
35 #include "llvm/Target/TargetAsmInfo.h"
36 #include "llvm/Target/TargetJITInfo.h"
37 #include "llvm/Support/Mangler.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/OutputBuffer.h"
40 #include "llvm/Support/Streams.h"
44 /// AddMachOWriter - Concrete function to add the Mach-O writer to the function
46 MachineCodeEmitter *llvm::AddMachOWriter(FunctionPassManager &FPM,
49 MachOWriter *MOW = new MachOWriter(O, TM);
51 return &MOW->getMachineCodeEmitter();
54 //===----------------------------------------------------------------------===//
55 // MachOCodeEmitter Implementation
56 //===----------------------------------------------------------------------===//
59 /// MachOCodeEmitter - This class is used by the MachOWriter to emit the code
60 /// for functions to the Mach-O file.
61 class MachOCodeEmitter : public MachineCodeEmitter {
64 /// Target machine description.
67 /// is64Bit/isLittleEndian - This information is inferred from the target
68 /// machine directly, indicating what header values and flags to set.
69 bool is64Bit, isLittleEndian;
71 /// Relocations - These are the relocations that the function needs, as
73 std::vector<MachineRelocation> Relocations;
75 /// CPLocations - This is a map of constant pool indices to offsets from the
76 /// start of the section for that constant pool index.
77 std::vector<intptr_t> CPLocations;
79 /// CPSections - This is a map of constant pool indices to the MachOSection
80 /// containing the constant pool entry for that index.
81 std::vector<unsigned> CPSections;
83 /// JTLocations - This is a map of jump table indices to offsets from the
84 /// start of the section for that jump table index.
85 std::vector<intptr_t> JTLocations;
87 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
88 /// It is filled in by the StartMachineBasicBlock callback and queried by
89 /// the getMachineBasicBlockAddress callback.
90 std::vector<intptr_t> MBBLocations;
93 MachOCodeEmitter(MachOWriter &mow) : MOW(mow), TM(MOW.TM) {
94 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
95 isLittleEndian = TM.getTargetData()->isLittleEndian();
98 virtual void startFunction(MachineFunction &MF);
99 virtual bool finishFunction(MachineFunction &MF);
101 virtual void addRelocation(const MachineRelocation &MR) {
102 Relocations.push_back(MR);
105 void emitConstantPool(MachineConstantPool *MCP);
106 void emitJumpTables(MachineJumpTableInfo *MJTI);
108 virtual intptr_t getConstantPoolEntryAddress(unsigned Index) const {
109 assert(CPLocations.size() > Index && "CP not emitted!");
110 return CPLocations[Index];
112 virtual intptr_t getJumpTableEntryAddress(unsigned Index) const {
113 assert(JTLocations.size() > Index && "JT not emitted!");
114 return JTLocations[Index];
117 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
118 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
119 MBBLocations.resize((MBB->getNumber()+1)*2);
120 MBBLocations[MBB->getNumber()] = getCurrentPCOffset();
123 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
124 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
125 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
126 return MBBLocations[MBB->getNumber()];
129 /// JIT SPECIFIC FUNCTIONS - DO NOT IMPLEMENT THESE HERE!
130 virtual void startFunctionStub(unsigned StubSize, unsigned Alignment = 1) {
131 assert(0 && "JIT specific function called!");
134 virtual void *finishFunctionStub(const Function *F) {
135 assert(0 && "JIT specific function called!");
142 /// startFunction - This callback is invoked when a new machine function is
143 /// about to be emitted.
144 void MachOCodeEmitter::startFunction(MachineFunction &MF) {
145 const TargetData *TD = TM.getTargetData();
146 const Function *F = MF.getFunction();
148 // Align the output buffer to the appropriate alignment, power of 2.
149 unsigned FnAlign = F->getAlignment();
150 unsigned TDAlign = TD->getPrefTypeAlignment(F->getType());
151 unsigned Align = Log2_32(std::max(FnAlign, TDAlign));
152 assert(!(Align & (Align-1)) && "Alignment is not a power of two!");
154 // Get the Mach-O Section that this function belongs in.
155 MachOWriter::MachOSection *MOS = MOW.getTextSection();
157 // FIXME: better memory management
158 MOS->SectionData.reserve(4096);
159 BufferBegin = &MOS->SectionData[0];
160 BufferEnd = BufferBegin + MOS->SectionData.capacity();
162 // Upgrade the section alignment if required.
163 if (MOS->align < Align) MOS->align = Align;
165 // Round the size up to the correct alignment for starting the new function.
166 if ((MOS->size & ((1 << Align) - 1)) != 0) {
167 MOS->size += (1 << Align);
168 MOS->size &= ~((1 << Align) - 1);
171 // FIXME: Using MOS->size directly here instead of calculating it from the
172 // output buffer size (impossible because the code emitter deals only in raw
173 // bytes) forces us to manually synchronize size and write padding zero bytes
174 // to the output buffer for all non-text sections. For text sections, we do
175 // not synchonize the output buffer, and we just blow up if anyone tries to
176 // write non-code to it. An assert should probably be added to
177 // AddSymbolToSection to prevent calling it on the text section.
178 CurBufferPtr = BufferBegin + MOS->size;
180 // Clear per-function data structures.
184 MBBLocations.clear();
187 /// finishFunction - This callback is invoked after the function is completely
189 bool MachOCodeEmitter::finishFunction(MachineFunction &MF) {
190 // Get the Mach-O Section that this function belongs in.
191 MachOWriter::MachOSection *MOS = MOW.getTextSection();
193 // Get a symbol for the function to add to the symbol table
194 // FIXME: it seems like we should call something like AddSymbolToSection
195 // in startFunction rather than changing the section size and symbol n_value
197 const GlobalValue *FuncV = MF.getFunction();
198 MachOSym FnSym(FuncV, MOW.Mang->getValueName(FuncV), MOS->Index, TM);
199 FnSym.n_value = MOS->size;
200 MOS->size = CurBufferPtr - BufferBegin;
202 // Emit constant pool to appropriate section(s)
203 emitConstantPool(MF.getConstantPool());
205 // Emit jump tables to appropriate section
206 emitJumpTables(MF.getJumpTableInfo());
208 // If we have emitted any relocations to function-specific objects such as
209 // basic blocks, constant pools entries, or jump tables, record their
210 // addresses now so that we can rewrite them with the correct addresses
212 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
213 MachineRelocation &MR = Relocations[i];
216 if (MR.isBasicBlock()) {
217 Addr = getMachineBasicBlockAddress(MR.getBasicBlock());
218 MR.setConstantVal(MOS->Index);
219 MR.setResultPointer((void*)Addr);
220 } else if (MR.isJumpTableIndex()) {
221 Addr = getJumpTableEntryAddress(MR.getJumpTableIndex());
222 MR.setConstantVal(MOW.getJumpTableSection()->Index);
223 MR.setResultPointer((void*)Addr);
224 } else if (MR.isConstantPoolIndex()) {
225 Addr = getConstantPoolEntryAddress(MR.getConstantPoolIndex());
226 MR.setConstantVal(CPSections[MR.getConstantPoolIndex()]);
227 MR.setResultPointer((void*)Addr);
228 } else if (!MR.isGlobalValue()) {
229 assert(0 && "Unhandled relocation type");
231 MOS->Relocations.push_back(MR);
235 // Finally, add it to the symtab.
236 MOW.SymbolTable.push_back(FnSym);
240 /// emitConstantPool - For each constant pool entry, figure out which section
241 /// the constant should live in, allocate space for it, and emit it to the
242 /// Section data buffer.
243 void MachOCodeEmitter::emitConstantPool(MachineConstantPool *MCP) {
244 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
245 if (CP.empty()) return;
247 // FIXME: handle PIC codegen
248 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
249 assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
251 // Although there is no strict necessity that I am aware of, we will do what
252 // gcc for OS X does and put each constant pool entry in a section of constant
253 // objects of a certain size. That means that float constants go in the
254 // literal4 section, and double objects go in literal8, etc.
256 // FIXME: revisit this decision if we ever do the "stick everything into one
257 // "giant object for PIC" optimization.
258 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
259 const Type *Ty = CP[i].getType();
260 unsigned Size = TM.getTargetData()->getTypeSize(Ty);
262 MachOWriter::MachOSection *Sec = MOW.getConstSection(CP[i].Val.ConstVal);
263 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
265 CPLocations.push_back(Sec->SectionData.size());
266 CPSections.push_back(Sec->Index);
268 // FIXME: remove when we have unified size + output buffer
271 // Allocate space in the section for the global.
272 // FIXME: need alignment?
273 // FIXME: share between here and AddSymbolToSection?
274 for (unsigned j = 0; j < Size; ++j)
275 SecDataOut.outbyte(0);
277 MOW.InitMem(CP[i].Val.ConstVal, &Sec->SectionData[0], CPLocations[i],
278 TM.getTargetData(), Sec->Relocations);
282 /// emitJumpTables - Emit all the jump tables for a given jump table info
283 /// record to the appropriate section.
284 void MachOCodeEmitter::emitJumpTables(MachineJumpTableInfo *MJTI) {
285 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
286 if (JT.empty()) return;
288 // FIXME: handle PIC codegen
289 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
290 assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
292 MachOWriter::MachOSection *Sec = MOW.getJumpTableSection();
293 unsigned TextSecIndex = MOW.getTextSection()->Index;
294 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
296 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
297 // For each jump table, record its offset from the start of the section,
298 // reserve space for the relocations to the MBBs, and add the relocations.
299 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
300 JTLocations.push_back(Sec->SectionData.size());
301 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
302 MachineRelocation MR(MOW.GetJTRelocation(Sec->SectionData.size(),
304 MR.setResultPointer((void *)JTLocations[i]);
305 MR.setConstantVal(TextSecIndex);
306 Sec->Relocations.push_back(MR);
307 SecDataOut.outaddr(0);
310 // FIXME: remove when we have unified size + output buffer
311 Sec->size = Sec->SectionData.size();
314 //===----------------------------------------------------------------------===//
315 // MachOWriter Implementation
316 //===----------------------------------------------------------------------===//
318 MachOWriter::MachOWriter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) {
319 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
320 isLittleEndian = TM.getTargetData()->isLittleEndian();
322 // Create the machine code emitter object for this target.
323 MCE = new MachOCodeEmitter(*this);
326 MachOWriter::~MachOWriter() {
330 void MachOWriter::AddSymbolToSection(MachOSection *Sec, GlobalVariable *GV) {
331 const Type *Ty = GV->getType()->getElementType();
332 unsigned Size = TM.getTargetData()->getTypeSize(Ty);
333 unsigned Align = GV->getAlignment();
335 Align = TM.getTargetData()->getPrefTypeAlignment(Ty);
337 MachOSym Sym(GV, Mang->getValueName(GV), Sec->Index, TM);
339 // Reserve space in the .bss section for this symbol while maintaining the
340 // desired section alignment, which must be at least as much as required by
342 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
345 uint64_t OrigSize = Sec->size;
346 Align = Log2_32(Align);
347 Sec->align = std::max(unsigned(Sec->align), Align);
348 Sec->size = (Sec->size + Align - 1) & ~(Align-1);
350 // Add alignment padding to buffer as well.
351 // FIXME: remove when we have unified size + output buffer
352 unsigned AlignedSize = Sec->size - OrigSize;
353 for (unsigned i = 0; i < AlignedSize; ++i)
354 SecDataOut.outbyte(0);
356 // Record the offset of the symbol, and then allocate space for it.
357 // FIXME: remove when we have unified size + output buffer
358 Sym.n_value = Sec->size;
360 SymbolTable.push_back(Sym);
362 // Now that we know what section the GlovalVariable is going to be emitted
363 // into, update our mappings.
364 // FIXME: We may also need to update this when outputting non-GlobalVariable
365 // GlobalValues such as functions.
367 GVOffset[GV] = Sec->SectionData.size();
369 // Allocate space in the section for the global.
370 for (unsigned i = 0; i < Size; ++i)
371 SecDataOut.outbyte(0);
374 void MachOWriter::EmitGlobal(GlobalVariable *GV) {
375 const Type *Ty = GV->getType()->getElementType();
376 unsigned Size = TM.getTargetData()->getTypeSize(Ty);
377 bool NoInit = !GV->hasInitializer();
379 // If this global has a zero initializer, it is part of the .bss or common
381 if (NoInit || GV->getInitializer()->isNullValue()) {
382 // If this global is part of the common block, add it now. Variables are
383 // part of the common block if they are zero initialized and allowed to be
384 // merged with other symbols.
385 if (NoInit || GV->hasLinkOnceLinkage() || GV->hasWeakLinkage()) {
386 MachOSym ExtOrCommonSym(GV, Mang->getValueName(GV), MachOSym::NO_SECT,TM);
387 // For undefined (N_UNDF) external (N_EXT) types, n_value is the size in
388 // bytes of the symbol.
389 ExtOrCommonSym.n_value = Size;
390 // If the symbol is external, we'll put it on a list of symbols whose
391 // addition to the symbol table is being pended until we find a reference
393 PendingSyms.push_back(ExtOrCommonSym);
395 SymbolTable.push_back(ExtOrCommonSym);
398 // Otherwise, this symbol is part of the .bss section.
399 MachOSection *BSS = getBSSSection();
400 AddSymbolToSection(BSS, GV);
404 // Scalar read-only data goes in a literal section if the scalar is 4, 8, or
405 // 16 bytes, or a cstring. Other read only data goes into a regular const
406 // section. Read-write data goes in the data section.
407 MachOSection *Sec = GV->isConstant() ? getConstSection(GV->getInitializer()) :
409 AddSymbolToSection(Sec, GV);
410 InitMem(GV->getInitializer(), &Sec->SectionData[0], GVOffset[GV],
411 TM.getTargetData(), Sec->Relocations);
415 bool MachOWriter::runOnMachineFunction(MachineFunction &MF) {
416 // Nothing to do here, this is all done through the MCE object.
420 bool MachOWriter::doInitialization(Module &M) {
421 // Set the magic value, now that we know the pointer size and endianness
422 Header.setMagic(isLittleEndian, is64Bit);
425 // FIXME: this only works for object files, we do not support the creation
426 // of dynamic libraries or executables at this time.
427 Header.filetype = MachOHeader::MH_OBJECT;
429 Mang = new Mangler(M);
433 /// doFinalization - Now that the module has been completely processed, emit
434 /// the Mach-O file to 'O'.
435 bool MachOWriter::doFinalization(Module &M) {
436 // FIXME: we don't handle debug info yet, we should probably do that.
438 // Okay, the.text section has been completed, build the .data, .bss, and
439 // "common" sections next.
440 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
444 // Emit the header and load commands.
445 EmitHeaderAndLoadCommands();
447 // Emit the various sections and their relocation info.
450 // Write the symbol table and the string table to the end of the file.
451 O.write((char*)&SymT[0], SymT.size());
452 O.write((char*)&StrT[0], StrT.size());
454 // We are done with the abstract symbols.
457 DynamicSymbolTable.clear();
459 // Release the name mangler object.
460 delete Mang; Mang = 0;
464 void MachOWriter::EmitHeaderAndLoadCommands() {
465 // Step #0: Fill in the segment load command size, since we need it to figure
466 // out the rest of the header fields
467 MachOSegment SEG("", is64Bit);
468 SEG.nsects = SectionList.size();
469 SEG.cmdsize = SEG.cmdSize(is64Bit) +
470 SEG.nsects * SectionList[0]->cmdSize(is64Bit);
472 // Step #1: calculate the number of load commands. We always have at least
473 // one, for the LC_SEGMENT load command, plus two for the normal
474 // and dynamic symbol tables, if there are any symbols.
475 Header.ncmds = SymbolTable.empty() ? 1 : 3;
477 // Step #2: calculate the size of the load commands
478 Header.sizeofcmds = SEG.cmdsize;
479 if (!SymbolTable.empty())
480 Header.sizeofcmds += SymTab.cmdsize + DySymTab.cmdsize;
482 // Step #3: write the header to the file
483 // Local alias to shortenify coming code.
484 DataBuffer &FH = Header.HeaderData;
485 OutputBuffer FHOut(FH, is64Bit, isLittleEndian);
487 FHOut.outword(Header.magic);
488 FHOut.outword(TM.getMachOWriterInfo()->getCPUType());
489 FHOut.outword(TM.getMachOWriterInfo()->getCPUSubType());
490 FHOut.outword(Header.filetype);
491 FHOut.outword(Header.ncmds);
492 FHOut.outword(Header.sizeofcmds);
493 FHOut.outword(Header.flags);
495 FHOut.outword(Header.reserved);
497 // Step #4: Finish filling in the segment load command and write it out
498 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
499 E = SectionList.end(); I != E; ++I)
500 SEG.filesize += (*I)->size;
502 SEG.vmsize = SEG.filesize;
503 SEG.fileoff = Header.cmdSize(is64Bit) + Header.sizeofcmds;
505 FHOut.outword(SEG.cmd);
506 FHOut.outword(SEG.cmdsize);
507 FHOut.outstring(SEG.segname, 16);
508 FHOut.outaddr(SEG.vmaddr);
509 FHOut.outaddr(SEG.vmsize);
510 FHOut.outaddr(SEG.fileoff);
511 FHOut.outaddr(SEG.filesize);
512 FHOut.outword(SEG.maxprot);
513 FHOut.outword(SEG.initprot);
514 FHOut.outword(SEG.nsects);
515 FHOut.outword(SEG.flags);
517 // Step #5: Finish filling in the fields of the MachOSections
518 uint64_t currentAddr = 0;
519 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
520 E = SectionList.end(); I != E; ++I) {
521 MachOSection *MOS = *I;
522 MOS->addr = currentAddr;
523 MOS->offset = currentAddr + SEG.fileoff;
525 // FIXME: do we need to do something with alignment here?
526 currentAddr += MOS->size;
529 // Step #6: Calculate the number of relocations for each section and write out
530 // the section commands for each section
531 currentAddr += SEG.fileoff;
532 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
533 E = SectionList.end(); I != E; ++I) {
534 MachOSection *MOS = *I;
535 // Convert the relocations to target-specific relocations, and fill in the
536 // relocation offset for this section.
537 CalculateRelocations(*MOS);
538 MOS->reloff = MOS->nreloc ? currentAddr : 0;
539 currentAddr += MOS->nreloc * 8;
541 // write the finalized section command to the output buffer
542 FHOut.outstring(MOS->sectname, 16);
543 FHOut.outstring(MOS->segname, 16);
544 FHOut.outaddr(MOS->addr);
545 FHOut.outaddr(MOS->size);
546 FHOut.outword(MOS->offset);
547 FHOut.outword(MOS->align);
548 FHOut.outword(MOS->reloff);
549 FHOut.outword(MOS->nreloc);
550 FHOut.outword(MOS->flags);
551 FHOut.outword(MOS->reserved1);
552 FHOut.outword(MOS->reserved2);
554 FHOut.outword(MOS->reserved3);
557 // Step #7: Emit the symbol table to temporary buffers, so that we know the
558 // size of the string table when we write the next load command.
559 BufferSymbolAndStringTable();
561 // Step #8: Emit LC_SYMTAB/LC_DYSYMTAB load commands
562 SymTab.symoff = currentAddr;
563 SymTab.nsyms = SymbolTable.size();
564 SymTab.stroff = SymTab.symoff + SymT.size();
565 SymTab.strsize = StrT.size();
566 FHOut.outword(SymTab.cmd);
567 FHOut.outword(SymTab.cmdsize);
568 FHOut.outword(SymTab.symoff);
569 FHOut.outword(SymTab.nsyms);
570 FHOut.outword(SymTab.stroff);
571 FHOut.outword(SymTab.strsize);
573 // FIXME: set DySymTab fields appropriately
574 // We should probably just update these in BufferSymbolAndStringTable since
575 // thats where we're partitioning up the different kinds of symbols.
576 FHOut.outword(DySymTab.cmd);
577 FHOut.outword(DySymTab.cmdsize);
578 FHOut.outword(DySymTab.ilocalsym);
579 FHOut.outword(DySymTab.nlocalsym);
580 FHOut.outword(DySymTab.iextdefsym);
581 FHOut.outword(DySymTab.nextdefsym);
582 FHOut.outword(DySymTab.iundefsym);
583 FHOut.outword(DySymTab.nundefsym);
584 FHOut.outword(DySymTab.tocoff);
585 FHOut.outword(DySymTab.ntoc);
586 FHOut.outword(DySymTab.modtaboff);
587 FHOut.outword(DySymTab.nmodtab);
588 FHOut.outword(DySymTab.extrefsymoff);
589 FHOut.outword(DySymTab.nextrefsyms);
590 FHOut.outword(DySymTab.indirectsymoff);
591 FHOut.outword(DySymTab.nindirectsyms);
592 FHOut.outword(DySymTab.extreloff);
593 FHOut.outword(DySymTab.nextrel);
594 FHOut.outword(DySymTab.locreloff);
595 FHOut.outword(DySymTab.nlocrel);
597 O.write((char*)&FH[0], FH.size());
600 /// EmitSections - Now that we have constructed the file header and load
601 /// commands, emit the data for each section to the file.
602 void MachOWriter::EmitSections() {
603 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
604 E = SectionList.end(); I != E; ++I)
605 // Emit the contents of each section
606 O.write((char*)&(*I)->SectionData[0], (*I)->size);
607 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
608 E = SectionList.end(); I != E; ++I)
609 // Emit the relocation entry data for each section.
610 O.write((char*)&(*I)->RelocBuffer[0], (*I)->RelocBuffer.size());
613 /// PartitionByLocal - Simple boolean predicate that returns true if Sym is
614 /// a local symbol rather than an external symbol.
615 bool MachOWriter::PartitionByLocal(const MachOSym &Sym) {
616 return (Sym.n_type & (MachOSym::N_EXT | MachOSym::N_PEXT)) == 0;
619 /// PartitionByDefined - Simple boolean predicate that returns true if Sym is
620 /// defined in this module.
621 bool MachOWriter::PartitionByDefined(const MachOSym &Sym) {
622 // FIXME: Do N_ABS or N_INDR count as defined?
623 return (Sym.n_type & MachOSym::N_SECT) == MachOSym::N_SECT;
626 /// BufferSymbolAndStringTable - Sort the symbols we encountered and assign them
627 /// each a string table index so that they appear in the correct order in the
629 void MachOWriter::BufferSymbolAndStringTable() {
630 // The order of the symbol table is:
632 // 2. defined external symbols (sorted by name)
633 // 3. undefined external symbols (sorted by name)
635 // Sort the symbols by name, so that when we partition the symbols by scope
636 // of definition, we won't have to sort by name within each partition.
637 std::sort(SymbolTable.begin(), SymbolTable.end(), MachOSymCmp());
639 // Parition the symbol table entries so that all local symbols come before
640 // all symbols with external linkage. { 1 | 2 3 }
641 std::partition(SymbolTable.begin(), SymbolTable.end(), PartitionByLocal);
643 // Advance iterator to beginning of external symbols and partition so that
644 // all external symbols defined in this module come before all external
645 // symbols defined elsewhere. { 1 | 2 | 3 }
646 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
647 E = SymbolTable.end(); I != E; ++I) {
648 if (!PartitionByLocal(*I)) {
649 std::partition(I, E, PartitionByDefined);
654 // Calculate the starting index for each of the local, extern defined, and
655 // undefined symbols, as well as the number of each to put in the LC_DYSYMTAB
657 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
658 E = SymbolTable.end(); I != E; ++I) {
659 if (PartitionByLocal(*I)) {
660 ++DySymTab.nlocalsym;
661 ++DySymTab.iextdefsym;
662 ++DySymTab.iundefsym;
663 } else if (PartitionByDefined(*I)) {
664 ++DySymTab.nextdefsym;
665 ++DySymTab.iundefsym;
667 ++DySymTab.nundefsym;
671 // Write out a leading zero byte when emitting string table, for n_strx == 0
672 // which means an empty string.
673 OutputBuffer StrTOut(StrT, is64Bit, isLittleEndian);
676 // The order of the string table is:
677 // 1. strings for external symbols
678 // 2. strings for local symbols
679 // Since this is the opposite order from the symbol table, which we have just
680 // sorted, we can walk the symbol table backwards to output the string table.
681 for (std::vector<MachOSym>::reverse_iterator I = SymbolTable.rbegin(),
682 E = SymbolTable.rend(); I != E; ++I) {
683 if (I->GVName == "") {
686 I->n_strx = StrT.size();
687 StrTOut.outstring(I->GVName, I->GVName.length()+1);
691 OutputBuffer SymTOut(SymT, is64Bit, isLittleEndian);
693 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
694 E = SymbolTable.end(); I != E; ++I) {
695 // Add the section base address to the section offset in the n_value field
696 // to calculate the full address.
697 // FIXME: handle symbols where the n_value field is not the address
698 GlobalValue *GV = const_cast<GlobalValue*>(I->GV);
699 if (GV && GVSection[GV])
700 I->n_value += GVSection[GV]->addr;
702 // Emit nlist to buffer
703 SymTOut.outword(I->n_strx);
704 SymTOut.outbyte(I->n_type);
705 SymTOut.outbyte(I->n_sect);
706 SymTOut.outhalf(I->n_desc);
707 SymTOut.outaddr(I->n_value);
711 /// CalculateRelocations - For each MachineRelocation in the current section,
712 /// calculate the index of the section containing the object to be relocated,
713 /// and the offset into that section. From this information, create the
714 /// appropriate target-specific MachORelocation type and add buffer it to be
715 /// written out after we are finished writing out sections.
716 void MachOWriter::CalculateRelocations(MachOSection &MOS) {
717 for (unsigned i = 0, e = MOS.Relocations.size(); i != e; ++i) {
718 MachineRelocation &MR = MOS.Relocations[i];
719 unsigned TargetSection = MR.getConstantVal();
721 // This is a scattered relocation entry if it points to a global value with
722 // a non-zero offset.
723 bool Scattered = false;
725 // Since we may not have seen the GlobalValue we were interested in yet at
726 // the time we emitted the relocation for it, fix it up now so that it
727 // points to the offset into the correct section.
728 if (MR.isGlobalValue()) {
729 GlobalValue *GV = MR.getGlobalValue();
730 MachOSection *MOSPtr = GVSection[GV];
731 intptr_t Offset = GVOffset[GV];
732 Scattered = TargetSection != 0;
735 cerr << "Trying to relocate unknown global " << *GV << '\n';
740 TargetSection = MOSPtr->Index;
741 MR.setResultPointer((void*)Offset);
744 OutputBuffer RelocOut(MOS.RelocBuffer, is64Bit, isLittleEndian);
745 OutputBuffer SecOut(MOS.SectionData, is64Bit, isLittleEndian);
746 MachOSection &To = *SectionList[TargetSection - 1];
748 MOS.nreloc += GetTargetRelocation(MR, MOS.Index, To.addr, To.Index,
749 RelocOut, SecOut, Scattered);
753 // InitMem - Write the value of a Constant to the specified memory location,
754 // converting it into bytes and relocations.
755 void MachOWriter::InitMem(const Constant *C, void *Addr, intptr_t Offset,
756 const TargetData *TD,
757 std::vector<MachineRelocation> &MRs) {
758 typedef std::pair<const Constant*, intptr_t> CPair;
759 std::vector<CPair> WorkList;
761 WorkList.push_back(CPair(C,(intptr_t)Addr + Offset));
763 intptr_t ScatteredOffset = 0;
765 while (!WorkList.empty()) {
766 const Constant *PC = WorkList.back().first;
767 intptr_t PA = WorkList.back().second;
770 if (isa<UndefValue>(PC)) {
772 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(PC)) {
773 unsigned ElementSize = TD->getTypeSize(CP->getType()->getElementType());
774 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
775 WorkList.push_back(CPair(CP->getOperand(i), PA+i*ElementSize));
776 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(PC)) {
778 // FIXME: Handle ConstantExpression. See EE::getConstantValue()
780 switch (CE->getOpcode()) {
781 case Instruction::GetElementPtr: {
782 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
783 ScatteredOffset = TD->getIndexedOffset(CE->getOperand(0)->getType(),
784 &Indices[0], Indices.size());
785 WorkList.push_back(CPair(CE->getOperand(0), PA));
788 case Instruction::Add:
790 cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
794 } else if (PC->getType()->isFirstClassType()) {
795 unsigned char *ptr = (unsigned char *)PA;
796 switch (PC->getType()->getTypeID()) {
797 case Type::IntegerTyID: {
798 unsigned NumBits = cast<IntegerType>(PC->getType())->getBitWidth();
799 uint64_t val = cast<ConstantInt>(PC)->getZExtValue();
802 else if (NumBits <= 16) {
803 if (TD->isBigEndian())
804 val = ByteSwap_16(val);
807 } else if (NumBits <= 32) {
808 if (TD->isBigEndian())
809 val = ByteSwap_32(val);
814 } else if (NumBits <= 64) {
815 if (TD->isBigEndian())
816 val = ByteSwap_64(val);
826 assert(0 && "Not implemented: bit widths > 64");
830 case Type::FloatTyID: {
831 uint64_t val = FloatToBits(cast<ConstantFP>(PC)->getValue());
832 if (TD->isBigEndian())
833 val = ByteSwap_32(val);
840 case Type::DoubleTyID: {
841 uint64_t val = DoubleToBits(cast<ConstantFP>(PC)->getValue());
842 if (TD->isBigEndian())
843 val = ByteSwap_64(val);
854 case Type::PointerTyID:
855 if (isa<ConstantPointerNull>(PC))
856 memset(ptr, 0, TD->getPointerSize());
857 else if (const GlobalValue* GV = dyn_cast<GlobalValue>(PC)) {
858 // FIXME: what about function stubs?
859 MRs.push_back(MachineRelocation::getGV(PA-(intptr_t)Addr,
860 MachineRelocation::VANILLA,
861 const_cast<GlobalValue*>(GV),
865 assert(0 && "Unknown constant pointer type!");
868 cerr << "ERROR: Constant unimp for type: " << *PC->getType() << "\n";
871 } else if (isa<ConstantAggregateZero>(PC)) {
872 memset((void*)PA, 0, (size_t)TD->getTypeSize(PC->getType()));
873 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(PC)) {
874 unsigned ElementSize = TD->getTypeSize(CPA->getType()->getElementType());
875 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
876 WorkList.push_back(CPair(CPA->getOperand(i), PA+i*ElementSize));
877 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(PC)) {
878 const StructLayout *SL =
879 TD->getStructLayout(cast<StructType>(CPS->getType()));
880 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
881 WorkList.push_back(CPair(CPS->getOperand(i),
882 PA+SL->getElementOffset(i)));
884 cerr << "Bad Type: " << *PC->getType() << "\n";
885 assert(0 && "Unknown constant type to initialize memory with!");
890 MachOSym::MachOSym(const GlobalValue *gv, std::string name, uint8_t sect,
892 GV(gv), n_strx(0), n_type(sect == NO_SECT ? N_UNDF : N_SECT), n_sect(sect),
893 n_desc(0), n_value(0) {
895 const TargetAsmInfo *TAI = TM.getTargetAsmInfo();
897 switch (GV->getLinkage()) {
899 assert(0 && "Unexpected linkage type!");
901 case GlobalValue::WeakLinkage:
902 case GlobalValue::LinkOnceLinkage:
903 assert(!isa<Function>(gv) && "Unexpected linkage type for Function!");
904 case GlobalValue::ExternalLinkage:
905 GVName = TAI->getGlobalPrefix() + name;
906 n_type |= GV->hasHiddenVisibility() ? N_PEXT : N_EXT;
908 case GlobalValue::InternalLinkage:
909 GVName = TAI->getGlobalPrefix() + name;