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