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