For PR950:
[oota-llvm.git] / lib / CodeGen / MachOWriter.cpp
1 //===-- MachOWriter.cpp - Target-independent Mach-O Writer code -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
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
25 #include "llvm/Constants.h"
26 #include "llvm/DerivedTypes.h"
27 #include "llvm/Module.h"
28 #include "llvm/CodeGen/MachineCodeEmitter.h"
29 #include "llvm/CodeGen/MachineConstantPool.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachOWriter.h"
32 #include "llvm/ExecutionEngine/ExecutionEngine.h"
33 #include "llvm/Target/TargetAsmInfo.h"
34 #include "llvm/Target/TargetJITInfo.h"
35 #include "llvm/Support/Mangler.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/Streams.h"
38 #include <algorithm>
39
40 using namespace llvm;
41
42 //===----------------------------------------------------------------------===//
43 //                       MachOCodeEmitter Implementation
44 //===----------------------------------------------------------------------===//
45
46 namespace llvm {
47   /// MachOCodeEmitter - This class is used by the MachOWriter to emit the code 
48   /// for functions to the Mach-O file.
49   class MachOCodeEmitter : public MachineCodeEmitter {
50     MachOWriter &MOW;
51
52     /// Relocations - These are the relocations that the function needs, as
53     /// emitted.
54     std::vector<MachineRelocation> Relocations;
55     
56     /// CPLocations - This is a map of constant pool indices to offsets from the
57     /// start of the section for that constant pool index.
58     std::vector<intptr_t> CPLocations;
59
60     /// CPSections - This is a map of constant pool indices to the MachOSection
61     /// containing the constant pool entry for that index.
62     std::vector<unsigned> CPSections;
63
64     /// JTLocations - This is a map of jump table indices to offsets from the
65     /// start of the section for that jump table index.
66     std::vector<intptr_t> JTLocations;
67
68     /// MBBLocations - This vector is a mapping from MBB ID's to their address.
69     /// It is filled in by the StartMachineBasicBlock callback and queried by
70     /// the getMachineBasicBlockAddress callback.
71     std::vector<intptr_t> MBBLocations;
72     
73   public:
74     MachOCodeEmitter(MachOWriter &mow) : MOW(mow) {}
75
76     virtual void startFunction(MachineFunction &F);
77     virtual bool finishFunction(MachineFunction &F);
78
79     virtual void addRelocation(const MachineRelocation &MR) {
80       Relocations.push_back(MR);
81     }
82     
83     void emitConstantPool(MachineConstantPool *MCP);
84     void emitJumpTables(MachineJumpTableInfo *MJTI);
85     
86     virtual intptr_t getConstantPoolEntryAddress(unsigned Index) const {
87       assert(CPLocations.size() > Index && "CP not emitted!");
88       return CPLocations[Index];
89     }
90     virtual intptr_t getJumpTableEntryAddress(unsigned Index) const {
91       assert(JTLocations.size() > Index && "JT not emitted!");
92       return JTLocations[Index];
93     }
94
95     virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
96       if (MBBLocations.size() <= (unsigned)MBB->getNumber())
97         MBBLocations.resize((MBB->getNumber()+1)*2);
98       MBBLocations[MBB->getNumber()] = getCurrentPCOffset();
99     }
100
101     virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
102       assert(MBBLocations.size() > (unsigned)MBB->getNumber() && 
103              MBBLocations[MBB->getNumber()] && "MBB not emitted!");
104       return MBBLocations[MBB->getNumber()];
105     }
106
107     /// JIT SPECIFIC FUNCTIONS - DO NOT IMPLEMENT THESE HERE!
108     virtual void startFunctionStub(unsigned StubSize, unsigned Alignment = 1) {
109       assert(0 && "JIT specific function called!");
110       abort();
111     }
112     virtual void *finishFunctionStub(const Function *F) {
113       assert(0 && "JIT specific function called!");
114       abort();
115       return 0;
116     }
117   };
118 }
119
120 /// startFunction - This callback is invoked when a new machine function is
121 /// about to be emitted.
122 void MachOCodeEmitter::startFunction(MachineFunction &F) {
123   // Align the output buffer to the appropriate alignment, power of 2.
124   // FIXME: MachineFunction or TargetData should probably carry an alignment
125   // field for functions that we can query here instead of hard coding 4 in both
126   // the object writer and asm printer.
127   unsigned Align = 4;
128
129   // Get the Mach-O Section that this function belongs in.
130   MachOWriter::MachOSection *MOS = MOW.getTextSection();
131   
132   // FIXME: better memory management
133   MOS->SectionData.reserve(4096);
134   BufferBegin = &MOS->SectionData[0];
135   BufferEnd = BufferBegin + MOS->SectionData.capacity();
136
137   // FIXME: Using MOS->size directly here instead of calculating it from the
138   // output buffer size (impossible because the code emitter deals only in raw
139   // bytes) forces us to manually synchronize size and write padding zero bytes
140   // to the output buffer for all non-text sections.  For text sections, we do
141   // not synchonize the output buffer, and we just blow up if anyone tries to
142   // write non-code to it.  An assert should probably be added to
143   // AddSymbolToSection to prevent calling it on the text section.
144   CurBufferPtr = BufferBegin + MOS->size;
145
146   // Upgrade the section alignment if required.
147   if (MOS->align < Align) MOS->align = Align;
148
149   // Clear per-function data structures.
150   CPLocations.clear();
151   CPSections.clear();
152   JTLocations.clear();
153   MBBLocations.clear();
154 }
155
156 /// finishFunction - This callback is invoked after the function is completely
157 /// finished.
158 bool MachOCodeEmitter::finishFunction(MachineFunction &F) {
159   // Get the Mach-O Section that this function belongs in.
160   MachOWriter::MachOSection *MOS = MOW.getTextSection();
161
162   MOS->size += CurBufferPtr - BufferBegin;
163   
164   // Get a symbol for the function to add to the symbol table
165   const GlobalValue *FuncV = F.getFunction();
166   MachOSym FnSym(FuncV, MOW.Mang->getValueName(FuncV), MOS->Index, MOW.TM);
167
168   // Emit constant pool to appropriate section(s)
169   emitConstantPool(F.getConstantPool());
170
171   // Emit jump tables to appropriate section
172   emitJumpTables(F.getJumpTableInfo());
173   
174   // If we have emitted any relocations to function-specific objects such as 
175   // basic blocks, constant pools entries, or jump tables, record their
176   // addresses now so that we can rewrite them with the correct addresses
177   // later.
178   for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
179     MachineRelocation &MR = Relocations[i];
180     intptr_t Addr;
181
182     if (MR.isBasicBlock()) {
183       Addr = getMachineBasicBlockAddress(MR.getBasicBlock());
184       MR.setConstantVal(MOS->Index);
185       MR.setResultPointer((void*)Addr);
186     } else if (MR.isJumpTableIndex()) {
187       Addr = getJumpTableEntryAddress(MR.getJumpTableIndex());
188       MR.setConstantVal(MOW.getJumpTableSection()->Index);
189       MR.setResultPointer((void*)Addr);
190     } else if (MR.isConstantPoolIndex()) {
191       Addr = getConstantPoolEntryAddress(MR.getConstantPoolIndex());
192       MR.setConstantVal(CPSections[MR.getConstantPoolIndex()]);
193       MR.setResultPointer((void*)Addr);
194     } else if (!MR.isGlobalValue()) {
195       assert(0 && "Unhandled relocation type");
196     }
197     MOS->Relocations.push_back(MR);
198   }
199   Relocations.clear();
200   
201   // Finally, add it to the symtab.
202   MOW.SymbolTable.push_back(FnSym);
203   return false;
204 }
205
206 /// emitConstantPool - For each constant pool entry, figure out which section
207 /// the constant should live in, allocate space for it, and emit it to the 
208 /// Section data buffer.
209 void MachOCodeEmitter::emitConstantPool(MachineConstantPool *MCP) {
210   const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
211   if (CP.empty()) return;
212
213   // FIXME: handle PIC codegen
214   bool isPIC = MOW.TM.getRelocationModel() == Reloc::PIC_;
215   assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
216
217   // Although there is no strict necessity that I am aware of, we will do what
218   // gcc for OS X does and put each constant pool entry in a section of constant
219   // objects of a certain size.  That means that float constants go in the
220   // literal4 section, and double objects go in literal8, etc.
221   //
222   // FIXME: revisit this decision if we ever do the "stick everything into one
223   // "giant object for PIC" optimization.
224   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
225     const Type *Ty = CP[i].getType();
226     unsigned Size = MOW.TM.getTargetData()->getTypeSize(Ty);
227
228     MachOWriter::MachOSection *Sec = MOW.getConstSection(Ty);
229     CPLocations.push_back(Sec->SectionData.size());
230     CPSections.push_back(Sec->Index);
231     
232     // FIXME: remove when we have unified size + output buffer
233     Sec->size += Size;
234
235     // Allocate space in the section for the global.
236     // FIXME: need alignment?
237     // FIXME: share between here and AddSymbolToSection?
238     for (unsigned j = 0; j < Size; ++j)
239       MOW.outbyte(Sec->SectionData, 0);
240
241     MOW.InitMem(CP[i].Val.ConstVal, &Sec->SectionData[0], CPLocations[i],
242                 MOW.TM.getTargetData(), Sec->Relocations);
243   }
244 }
245
246 /// emitJumpTables - Emit all the jump tables for a given jump table info
247 /// record to the appropriate section.
248 void MachOCodeEmitter::emitJumpTables(MachineJumpTableInfo *MJTI) {
249   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
250   if (JT.empty()) return;
251
252   // FIXME: handle PIC codegen
253   bool isPIC = MOW.TM.getRelocationModel() == Reloc::PIC_;
254   assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
255
256   MachOWriter::MachOSection *Sec = MOW.getJumpTableSection();
257   unsigned TextSecIndex = MOW.getTextSection()->Index;
258
259   for (unsigned i = 0, e = JT.size(); i != e; ++i) {
260     // For each jump table, record its offset from the start of the section,
261     // reserve space for the relocations to the MBBs, and add the relocations.
262     const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
263     JTLocations.push_back(Sec->SectionData.size());
264     for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
265       MachineRelocation MR(MOW.GetJTRelocation(Sec->SectionData.size(),
266                                                MBBs[mi]));
267       MR.setResultPointer((void *)JTLocations[i]);
268       MR.setConstantVal(TextSecIndex);
269       Sec->Relocations.push_back(MR);
270       MOW.outaddr(Sec->SectionData, 0);
271     }
272   }
273   // FIXME: remove when we have unified size + output buffer
274   Sec->size = Sec->SectionData.size();
275 }
276
277 //===----------------------------------------------------------------------===//
278 //                          MachOWriter Implementation
279 //===----------------------------------------------------------------------===//
280
281 MachOWriter::MachOWriter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) {
282   is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
283   isLittleEndian = TM.getTargetData()->isLittleEndian();
284
285   // Create the machine code emitter object for this target.
286   MCE = new MachOCodeEmitter(*this);
287 }
288
289 MachOWriter::~MachOWriter() {
290   delete MCE;
291 }
292
293 void MachOWriter::AddSymbolToSection(MachOSection *Sec, GlobalVariable *GV) {
294   const Type *Ty = GV->getType()->getElementType();
295   unsigned Size = TM.getTargetData()->getTypeSize(Ty);
296   unsigned Align = GV->getAlignment();
297   if (Align == 0)
298     Align = TM.getTargetData()->getTypeAlignment(Ty);
299   
300   MachOSym Sym(GV, Mang->getValueName(GV), Sec->Index, TM);
301   
302   // Reserve space in the .bss section for this symbol while maintaining the
303   // desired section alignment, which must be at least as much as required by
304   // this symbol.
305   if (Align) {
306     uint64_t OrigSize = Sec->size;
307     Align = Log2_32(Align);
308     Sec->align = std::max(unsigned(Sec->align), Align);
309     Sec->size = (Sec->size + Align - 1) & ~(Align-1);
310     
311     // Add alignment padding to buffer as well.
312     // FIXME: remove when we have unified size + output buffer
313     unsigned AlignedSize = Sec->size - OrigSize;
314     for (unsigned i = 0; i < AlignedSize; ++i)
315       outbyte(Sec->SectionData, 0);
316   }
317   // Record the offset of the symbol, and then allocate space for it.
318   // FIXME: remove when we have unified size + output buffer
319   Sym.n_value = Sec->size;
320   Sec->size += Size;
321   SymbolTable.push_back(Sym);
322
323   // Now that we know what section the GlovalVariable is going to be emitted 
324   // into, update our mappings.
325   // FIXME: We may also need to update this when outputting non-GlobalVariable
326   // GlobalValues such as functions.
327   GVSection[GV] = Sec;
328   GVOffset[GV] = Sec->SectionData.size();
329   
330   // Allocate space in the section for the global.
331   for (unsigned i = 0; i < Size; ++i)
332     outbyte(Sec->SectionData, 0);
333 }
334
335 void MachOWriter::EmitGlobal(GlobalVariable *GV) {
336   const Type *Ty = GV->getType()->getElementType();
337   unsigned Size = TM.getTargetData()->getTypeSize(Ty);
338   bool NoInit = !GV->hasInitializer();
339   
340   // If this global has a zero initializer, it is part of the .bss or common
341   // section.
342   if (NoInit || GV->getInitializer()->isNullValue()) {
343     // If this global is part of the common block, add it now.  Variables are
344     // part of the common block if they are zero initialized and allowed to be
345     // merged with other symbols.
346     if (NoInit || GV->hasLinkOnceLinkage() || GV->hasWeakLinkage()) {
347       MachOSym ExtOrCommonSym(GV, Mang->getValueName(GV), MachOSym::NO_SECT,TM);
348       // For undefined (N_UNDF) external (N_EXT) types, n_value is the size in
349       // bytes of the symbol.
350       ExtOrCommonSym.n_value = Size;
351       // If the symbol is external, we'll put it on a list of symbols whose
352       // addition to the symbol table is being pended until we find a reference
353       if (NoInit)
354         PendingSyms.push_back(ExtOrCommonSym);
355       else
356         SymbolTable.push_back(ExtOrCommonSym);
357       return;
358     }
359     // Otherwise, this symbol is part of the .bss section.
360     MachOSection *BSS = getBSSSection();
361     AddSymbolToSection(BSS, GV);
362     return;
363   }
364   
365   // Scalar read-only data goes in a literal section if the scalar is 4, 8, or
366   // 16 bytes, or a cstring.  Other read only data goes into a regular const
367   // section.  Read-write data goes in the data section.
368   MachOSection *Sec = GV->isConstant() ? getConstSection(Ty) : getDataSection();
369   AddSymbolToSection(Sec, GV);
370   InitMem(GV->getInitializer(), &Sec->SectionData[0], GVOffset[GV],
371           TM.getTargetData(), Sec->Relocations);
372 }
373
374
375 bool MachOWriter::runOnMachineFunction(MachineFunction &MF) {
376   // Nothing to do here, this is all done through the MCE object.
377   return false;
378 }
379
380 bool MachOWriter::doInitialization(Module &M) {
381   // Set the magic value, now that we know the pointer size and endianness
382   Header.setMagic(isLittleEndian, is64Bit);
383
384   // Set the file type
385   // FIXME: this only works for object files, we do not support the creation
386   //        of dynamic libraries or executables at this time.
387   Header.filetype = MachOHeader::MH_OBJECT;
388
389   Mang = new Mangler(M);
390   return false;
391 }
392
393 /// doFinalization - Now that the module has been completely processed, emit
394 /// the Mach-O file to 'O'.
395 bool MachOWriter::doFinalization(Module &M) {
396   // FIXME: we don't handle debug info yet, we should probably do that.
397
398   // Okay, the.text section has been completed, build the .data, .bss, and 
399   // "common" sections next.
400   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
401        I != E; ++I)
402     EmitGlobal(I);
403   
404   // Emit the header and load commands.
405   EmitHeaderAndLoadCommands();
406
407   // Emit the various sections and their relocation info.
408   EmitSections();
409
410   // Write the symbol table and the string table to the end of the file.
411   O.write((char*)&SymT[0], SymT.size());
412   O.write((char*)&StrT[0], StrT.size());
413
414   // We are done with the abstract symbols.
415   SectionList.clear();
416   SymbolTable.clear();
417   DynamicSymbolTable.clear();
418
419   // Release the name mangler object.
420   delete Mang; Mang = 0;
421   return false;
422 }
423
424 void MachOWriter::EmitHeaderAndLoadCommands() {
425   // Step #0: Fill in the segment load command size, since we need it to figure
426   //          out the rest of the header fields
427   MachOSegment SEG("", is64Bit);
428   SEG.nsects  = SectionList.size();
429   SEG.cmdsize = SEG.cmdSize(is64Bit) + 
430                 SEG.nsects * SectionList[0]->cmdSize(is64Bit);
431   
432   // Step #1: calculate the number of load commands.  We always have at least
433   //          one, for the LC_SEGMENT load command, plus two for the normal
434   //          and dynamic symbol tables, if there are any symbols.
435   Header.ncmds = SymbolTable.empty() ? 1 : 3;
436   
437   // Step #2: calculate the size of the load commands
438   Header.sizeofcmds = SEG.cmdsize;
439   if (!SymbolTable.empty())
440     Header.sizeofcmds += SymTab.cmdsize + DySymTab.cmdsize;
441     
442   // Step #3: write the header to the file
443   // Local alias to shortenify coming code.
444   DataBuffer &FH = Header.HeaderData;
445   outword(FH, Header.magic);
446   outword(FH, Header.cputype);
447   outword(FH, Header.cpusubtype);
448   outword(FH, Header.filetype);
449   outword(FH, Header.ncmds);
450   outword(FH, Header.sizeofcmds);
451   outword(FH, Header.flags);
452   if (is64Bit)
453     outword(FH, Header.reserved);
454   
455   // Step #4: Finish filling in the segment load command and write it out
456   for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
457          E = SectionList.end(); I != E; ++I)
458     SEG.filesize += (*I)->size;
459
460   SEG.vmsize = SEG.filesize;
461   SEG.fileoff = Header.cmdSize(is64Bit) + Header.sizeofcmds;
462   
463   outword(FH, SEG.cmd);
464   outword(FH, SEG.cmdsize);
465   outstring(FH, SEG.segname, 16);
466   outaddr(FH, SEG.vmaddr);
467   outaddr(FH, SEG.vmsize);
468   outaddr(FH, SEG.fileoff);
469   outaddr(FH, SEG.filesize);
470   outword(FH, SEG.maxprot);
471   outword(FH, SEG.initprot);
472   outword(FH, SEG.nsects);
473   outword(FH, SEG.flags);
474   
475   // Step #5: Finish filling in the fields of the MachOSections 
476   uint64_t currentAddr = 0;
477   for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
478          E = SectionList.end(); I != E; ++I) {
479     MachOSection *MOS = *I;
480     MOS->addr = currentAddr;
481     MOS->offset = currentAddr + SEG.fileoff;
482
483     // FIXME: do we need to do something with alignment here?
484     currentAddr += MOS->size;
485   }
486   
487   // Step #6: Calculate the number of relocations for each section and write out
488   // the section commands for each section
489   currentAddr += SEG.fileoff;
490   for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
491          E = SectionList.end(); I != E; ++I) {
492     MachOSection *MOS = *I;
493     // Convert the relocations to target-specific relocations, and fill in the
494     // relocation offset for this section.
495     CalculateRelocations(*MOS);
496     MOS->reloff = MOS->nreloc ? currentAddr : 0;
497     currentAddr += MOS->nreloc * 8;
498     
499     // write the finalized section command to the output buffer
500     outstring(FH, MOS->sectname, 16);
501     outstring(FH, MOS->segname, 16);
502     outaddr(FH, MOS->addr);
503     outaddr(FH, MOS->size);
504     outword(FH, MOS->offset);
505     outword(FH, MOS->align);
506     outword(FH, MOS->reloff);
507     outword(FH, MOS->nreloc);
508     outword(FH, MOS->flags);
509     outword(FH, MOS->reserved1);
510     outword(FH, MOS->reserved2);
511     if (is64Bit)
512       outword(FH, MOS->reserved3);
513   }
514   
515   // Step #7: Emit the symbol table to temporary buffers, so that we know the
516   // size of the string table when we write the next load command.
517   BufferSymbolAndStringTable();
518   
519   // Step #8: Emit LC_SYMTAB/LC_DYSYMTAB load commands
520   SymTab.symoff  = currentAddr;
521   SymTab.nsyms   = SymbolTable.size();
522   SymTab.stroff  = SymTab.symoff + SymT.size();
523   SymTab.strsize = StrT.size();
524   outword(FH, SymTab.cmd);
525   outword(FH, SymTab.cmdsize);
526   outword(FH, SymTab.symoff);
527   outword(FH, SymTab.nsyms);
528   outword(FH, SymTab.stroff);
529   outword(FH, SymTab.strsize);
530
531   // FIXME: set DySymTab fields appropriately
532   // We should probably just update these in BufferSymbolAndStringTable since
533   // thats where we're partitioning up the different kinds of symbols.
534   outword(FH, DySymTab.cmd);
535   outword(FH, DySymTab.cmdsize);
536   outword(FH, DySymTab.ilocalsym);
537   outword(FH, DySymTab.nlocalsym);
538   outword(FH, DySymTab.iextdefsym);
539   outword(FH, DySymTab.nextdefsym);
540   outword(FH, DySymTab.iundefsym);
541   outword(FH, DySymTab.nundefsym);
542   outword(FH, DySymTab.tocoff);
543   outword(FH, DySymTab.ntoc);
544   outword(FH, DySymTab.modtaboff);
545   outword(FH, DySymTab.nmodtab);
546   outword(FH, DySymTab.extrefsymoff);
547   outword(FH, DySymTab.nextrefsyms);
548   outword(FH, DySymTab.indirectsymoff);
549   outword(FH, DySymTab.nindirectsyms);
550   outword(FH, DySymTab.extreloff);
551   outword(FH, DySymTab.nextrel);
552   outword(FH, DySymTab.locreloff);
553   outword(FH, DySymTab.nlocrel);
554   
555   O.write((char*)&FH[0], FH.size());
556 }
557
558 /// EmitSections - Now that we have constructed the file header and load
559 /// commands, emit the data for each section to the file.
560 void MachOWriter::EmitSections() {
561   for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
562          E = SectionList.end(); I != E; ++I)
563     // Emit the contents of each section
564     O.write((char*)&(*I)->SectionData[0], (*I)->size);
565   for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
566          E = SectionList.end(); I != E; ++I)
567     // Emit the relocation entry data for each section.
568     O.write((char*)&(*I)->RelocBuffer[0], (*I)->RelocBuffer.size());
569 }
570
571 /// PartitionByLocal - Simple boolean predicate that returns true if Sym is
572 /// a local symbol rather than an external symbol.
573 bool MachOWriter::PartitionByLocal(const MachOSym &Sym) {
574   return (Sym.n_type & (MachOSym::N_EXT | MachOSym::N_PEXT)) == 0;
575 }
576
577 /// PartitionByDefined - Simple boolean predicate that returns true if Sym is
578 /// defined in this module.
579 bool MachOWriter::PartitionByDefined(const MachOSym &Sym) {
580   // FIXME: Do N_ABS or N_INDR count as defined?
581   return (Sym.n_type & MachOSym::N_SECT) == MachOSym::N_SECT;
582 }
583
584 /// BufferSymbolAndStringTable - Sort the symbols we encountered and assign them
585 /// each a string table index so that they appear in the correct order in the
586 /// output file.
587 void MachOWriter::BufferSymbolAndStringTable() {
588   // The order of the symbol table is:
589   // 1. local symbols
590   // 2. defined external symbols (sorted by name)
591   // 3. undefined external symbols (sorted by name)
592   
593   // Sort the symbols by name, so that when we partition the symbols by scope
594   // of definition, we won't have to sort by name within each partition.
595   std::sort(SymbolTable.begin(), SymbolTable.end(), MachOSymCmp());
596
597   // Parition the symbol table entries so that all local symbols come before 
598   // all symbols with external linkage. { 1 | 2 3 }
599   std::partition(SymbolTable.begin(), SymbolTable.end(), PartitionByLocal);
600   
601   // Advance iterator to beginning of external symbols and partition so that
602   // all external symbols defined in this module come before all external
603   // symbols defined elsewhere. { 1 | 2 | 3 }
604   for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
605          E = SymbolTable.end(); I != E; ++I) {
606     if (!PartitionByLocal(*I)) {
607       std::partition(I, E, PartitionByDefined);
608       break;
609     }
610   }
611
612   // Calculate the starting index for each of the local, extern defined, and 
613   // undefined symbols, as well as the number of each to put in the LC_DYSYMTAB
614   // load command.
615   for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
616          E = SymbolTable.end(); I != E; ++I) {
617     if (PartitionByLocal(*I)) {
618       ++DySymTab.nlocalsym;
619       ++DySymTab.iextdefsym;
620     } else if (PartitionByDefined(*I)) {
621       ++DySymTab.nextdefsym;
622       ++DySymTab.iundefsym;
623     } else {
624       ++DySymTab.nundefsym;
625     }
626   }
627   
628   // Write out a leading zero byte when emitting string table, for n_strx == 0
629   // which means an empty string.
630   outbyte(StrT, 0);
631
632   // The order of the string table is:
633   // 1. strings for external symbols
634   // 2. strings for local symbols
635   // Since this is the opposite order from the symbol table, which we have just
636   // sorted, we can walk the symbol table backwards to output the string table.
637   for (std::vector<MachOSym>::reverse_iterator I = SymbolTable.rbegin(),
638         E = SymbolTable.rend(); I != E; ++I) {
639     if (I->GVName == "") {
640       I->n_strx = 0;
641     } else {
642       I->n_strx = StrT.size();
643       outstring(StrT, I->GVName, I->GVName.length()+1);
644     }
645   }
646
647   for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
648          E = SymbolTable.end(); I != E; ++I) {
649     // Add the section base address to the section offset in the n_value field
650     // to calculate the full address.
651     // FIXME: handle symbols where the n_value field is not the address
652     GlobalValue *GV = const_cast<GlobalValue*>(I->GV);
653     if (GV && GVSection[GV])
654       I->n_value += GVSection[GV]->addr;
655          
656     // Emit nlist to buffer
657     outword(SymT, I->n_strx);
658     outbyte(SymT, I->n_type);
659     outbyte(SymT, I->n_sect);
660     outhalf(SymT, I->n_desc);
661     outaddr(SymT, I->n_value);
662   }
663 }
664
665 /// CalculateRelocations - For each MachineRelocation in the current section,
666 /// calculate the index of the section containing the object to be relocated,
667 /// and the offset into that section.  From this information, create the
668 /// appropriate target-specific MachORelocation type and add buffer it to be
669 /// written out after we are finished writing out sections.
670 void MachOWriter::CalculateRelocations(MachOSection &MOS) {
671   for (unsigned i = 0, e = MOS.Relocations.size(); i != e; ++i) {
672     MachineRelocation &MR = MOS.Relocations[i];
673     unsigned TargetSection = MR.getConstantVal();
674     
675     // Since we may not have seen the GlobalValue we were interested in yet at
676     // the time we emitted the relocation for it, fix it up now so that it
677     // points to the offset into the correct section.
678     if (MR.isGlobalValue()) {
679       GlobalValue *GV = MR.getGlobalValue();
680       MachOSection *MOSPtr = GVSection[GV];
681       intptr_t offset = GVOffset[GV];
682       
683       assert(MOSPtr && "Trying to relocate unknown global!");
684       
685       TargetSection = MOSPtr->Index;
686       MR.setResultPointer((void*)offset);
687     }
688     
689     GetTargetRelocation(MR, MOS, *SectionList[TargetSection-1]);
690   }
691 }
692
693 // InitMem - Write the value of a Constant to the specified memory location,
694 // converting it into bytes and relocations.
695 void MachOWriter::InitMem(const Constant *C, void *Addr, intptr_t Offset,
696                           const TargetData *TD, 
697                           std::vector<MachineRelocation> &MRs) {
698   typedef std::pair<const Constant*, intptr_t> CPair;
699   std::vector<CPair> WorkList;
700   
701   WorkList.push_back(CPair(C,(intptr_t)Addr + Offset));
702   
703   while (!WorkList.empty()) {
704     const Constant *PC = WorkList.back().first;
705     intptr_t PA = WorkList.back().second;
706     WorkList.pop_back();
707     
708     if (isa<UndefValue>(PC)) {
709       continue;
710     } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(PC)) {
711       unsigned ElementSize = 
712         CP->getType()->getElementType()->getPrimitiveSize();
713       for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
714         WorkList.push_back(CPair(CP->getOperand(i), PA+i*ElementSize));
715     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(PC)) {
716       //
717       // FIXME: Handle ConstantExpression.  See EE::getConstantValue()
718       //
719       switch (CE->getOpcode()) {
720       case Instruction::GetElementPtr:
721       case Instruction::Add:
722       default:
723         cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
724         abort();
725         break;
726       }
727     } else if (PC->getType()->isFirstClassType()) {
728       unsigned char *ptr = (unsigned char *)PA;
729       uint64_t val;
730       
731       switch (PC->getType()->getTypeID()) {
732       case Type::BoolTyID:
733       case Type::Int8TyID:
734         ptr[0] = cast<ConstantInt>(PC)->getZExtValue();
735         break;
736       case Type::Int16TyID:
737         val = cast<ConstantInt>(PC)->getZExtValue();
738         if (TD->isBigEndian())
739           val = ByteSwap_16(val);
740         ptr[0] = val;
741         ptr[1] = val >> 8;
742         break;
743       case Type::Int32TyID:
744       case Type::FloatTyID:
745         if (PC->getType()->getTypeID() == Type::FloatTyID) {
746           val = FloatToBits(cast<ConstantFP>(PC)->getValue());
747         } else {
748           val = cast<ConstantInt>(PC)->getZExtValue();
749         }
750         if (TD->isBigEndian())
751           val = ByteSwap_32(val);
752         ptr[0] = val;
753         ptr[1] = val >> 8;
754         ptr[2] = val >> 16;
755         ptr[3] = val >> 24;
756         break;
757       case Type::DoubleTyID:
758       case Type::Int64TyID:
759         if (PC->getType()->getTypeID() == Type::DoubleTyID) {
760           val = DoubleToBits(cast<ConstantFP>(PC)->getValue());
761         } else {
762           val = cast<ConstantInt>(PC)->getZExtValue();
763         }
764         if (TD->isBigEndian())
765           val = ByteSwap_64(val);
766         ptr[0] = val;
767         ptr[1] = val >> 8;
768         ptr[2] = val >> 16;
769         ptr[3] = val >> 24;
770         ptr[4] = val >> 32;
771         ptr[5] = val >> 40;
772         ptr[6] = val >> 48;
773         ptr[7] = val >> 56;
774         break;
775       case Type::PointerTyID:
776         if (isa<ConstantPointerNull>(C))
777           memset(ptr, 0, TD->getPointerSize());
778         else if (const GlobalValue* GV = dyn_cast<GlobalValue>(C))
779           // FIXME: what about function stubs?
780           MRs.push_back(MachineRelocation::getGV(PA-(intptr_t)Addr, 
781                                                  MachineRelocation::VANILLA,
782                                                  const_cast<GlobalValue*>(GV)));
783         else
784           assert(0 && "Unknown constant pointer type!");
785         break;
786       default:
787         cerr << "ERROR: Constant unimp for type: " << *PC->getType() << "\n";
788         abort();
789       }
790     } else if (isa<ConstantAggregateZero>(PC)) {
791       memset((void*)PA, 0, (size_t)TD->getTypeSize(PC->getType()));
792     } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(PC)) {
793       unsigned ElementSize = 
794         CPA->getType()->getElementType()->getPrimitiveSize();
795       for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
796         WorkList.push_back(CPair(CPA->getOperand(i), PA+i*ElementSize));
797     } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(PC)) {
798       const StructLayout *SL =
799         TD->getStructLayout(cast<StructType>(CPS->getType()));
800       for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
801         WorkList.push_back(CPair(CPS->getOperand(i), PA+SL->MemberOffsets[i]));
802     } else {
803       cerr << "Bad Type: " << *PC->getType() << "\n";
804       assert(0 && "Unknown constant type to initialize memory with!");
805     }
806   }
807 }
808
809 MachOSym::MachOSym(const GlobalValue *gv, std::string name, uint8_t sect,
810                    TargetMachine &TM) :
811   GV(gv), n_strx(0), n_type(sect == NO_SECT ? N_UNDF : N_SECT), n_sect(sect),
812   n_desc(0), n_value(0) {
813
814   const TargetAsmInfo *TAI = TM.getTargetAsmInfo();  
815   
816   switch (GV->getLinkage()) {
817   default:
818     assert(0 && "Unexpected linkage type!");
819     break;
820   case GlobalValue::WeakLinkage:
821   case GlobalValue::LinkOnceLinkage:
822     assert(!isa<Function>(gv) && "Unexpected linkage type for Function!");
823   case GlobalValue::ExternalLinkage:
824     GVName = TAI->getGlobalPrefix() + name;
825     n_type |= N_EXT;
826     break;
827   case GlobalValue::InternalLinkage:
828     GVName = TAI->getPrivateGlobalPrefix() + name;
829     break;
830   }
831 }