Get closer to handling globals correctly. We now generally get them in the
[oota-llvm.git] / include / llvm / CodeGen / MachOWriter.h
1 //=== MachOWriter.h - Target-independent Mach-O writer support --*- C++ -*-===//
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 defines the MachOWriter class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_CODEGEN_MACHOWRITER_H
15 #define LLVM_CODEGEN_MACHOWRITER_H
16
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 #include "llvm/Target/TargetData.h"
20 #include "llvm/Target/TargetMachine.h"
21 #include <list>
22
23 namespace llvm {
24   class GlobalVariable;
25   class Mangler;
26   class MachineCodeEmitter;
27   class MachOCodeEmitter;
28
29   /// MachOWriter - This class implements the common target-independent code for
30   /// writing Mach-O files.  Targets should derive a class from this to
31   /// parameterize the output format.
32   ///
33   class MachOWriter : public MachineFunctionPass {
34     friend class MachOCodeEmitter;
35   public:
36     MachineCodeEmitter &getMachineCodeEmitter() const {
37       return *(MachineCodeEmitter*)MCE;
38     }
39
40     ~MachOWriter();
41
42     typedef std::vector<unsigned char> DataBuffer;
43
44   protected:
45     MachOWriter(std::ostream &O, TargetMachine &TM);
46
47     /// Output stream to send the resultant object file to.
48     ///
49     std::ostream &O;
50
51     /// Target machine description.
52     ///
53     TargetMachine &TM;
54
55     /// Mang - The object used to perform name mangling for this module.
56     ///
57     Mangler *Mang;
58
59     /// MCE - The MachineCodeEmitter object that we are exposing to emit machine
60     /// code for functions to the .o file.
61     MachOCodeEmitter *MCE;
62
63     /// is64Bit/isLittleEndian - This information is inferred from the target
64     /// machine directly, indicating what header values and flags to set.
65     bool is64Bit, isLittleEndian;
66
67     /// doInitialization - Emit the file header and all of the global variables
68     /// for the module to the Mach-O file.
69     bool doInitialization(Module &M);
70
71     bool runOnMachineFunction(MachineFunction &MF);
72
73     /// doFinalization - Now that the module has been completely processed, emit
74     /// the Mach-O file to 'O'.
75     bool doFinalization(Module &M);
76
77     /// MachOHeader - This struct contains the header information about a
78     /// specific architecture type/subtype pair that is emitted to the file.
79     struct MachOHeader {
80       uint32_t  magic;      // mach magic number identifier
81       uint32_t  cputype;    // cpu specifier
82       uint32_t  cpusubtype; // machine specifier
83       uint32_t  filetype;   // type of file
84       uint32_t  ncmds;      // number of load commands
85       uint32_t  sizeofcmds; // the size of all the load commands
86       uint32_t  flags;      // flags
87       uint32_t  reserved;   // 64-bit only
88       
89       /// HeaderData - The actual data for the header which we are building
90       /// up for emission to the file.
91       DataBuffer HeaderData;
92
93       // Constants for the cputype field
94       // see <mach/machine.h>
95       enum { CPU_TYPE_I386      = 7,
96              CPU_TYPE_X86_64    = 7 | 0x1000000,
97              CPU_TYPE_ARM       = 12,
98              CPU_TYPE_SPARC     = 14,
99              CPU_TYPE_POWERPC   = 18,
100              CPU_TYPE_POWERPC64 = 18 | 0x1000000
101       };
102       
103       // Constants for the cpusubtype field
104       // see <mach/machine.h>
105       enum { CPU_SUBTYPE_I386_ALL    = 3,
106              CPU_SUBTYPE_X86_64_ALL  = 3,
107              CPU_SUBTYPE_ARM_ALL     = 0,
108              CPU_SUBTYPE_SPARC_ALL   = 0,
109              CPU_SUBTYPE_POWERPC_ALL = 0
110       };
111              
112       // Constants for the filetype field
113       // see <mach-o/loader.h> for additional info on the various types
114       enum { MH_OBJECT     = 1, // relocatable object file
115              MH_EXECUTE    = 2, // demand paged executable file
116              MH_FVMLIB     = 3, // fixed VM shared library file
117              MH_CORE       = 4, // core file
118              MH_PRELOAD    = 5, // preloaded executable file
119              MH_DYLIB      = 6, // dynamically bound shared library
120              MH_DYLINKER   = 7, // dynamic link editor
121              MH_BUNDLE     = 8, // dynamically bound bundle file
122              MH_DYLIB_STUB = 9, // shared library stub for static linking only
123              MH_DSYM       = 10 // companion file wiht only debug sections
124       };
125       
126       // Constants for the flags field
127       enum { MH_NOUNDEFS                = 1 << 0,
128                 // the object file has no undefined references
129              MH_INCRLINK                = 1 << 1,
130                 // the object file is the output of an incremental link against
131                 // a base file and cannot be link edited again
132              MH_DYLDLINK                = 1 << 2,
133                 // the object file is input for the dynamic linker and cannot be
134                 // statically link edited again.
135              MH_BINDATLOAD              = 1 << 3,
136                 // the object file's undefined references are bound by the
137                 // dynamic linker when loaded.
138              MH_PREBOUND                = 1 << 4,
139                 // the file has its dynamic undefined references prebound
140              MH_SPLIT_SEGS              = 1 << 5,
141                 // the file has its read-only and read-write segments split
142                 // see <mach/shared_memory_server.h>
143              MH_LAZY_INIT               = 1 << 6,
144                 // the shared library init routine is to be run lazily via
145                 // catching memory faults to its writable segments (obsolete)
146              MH_TWOLEVEL                = 1 << 7,
147                 // the image is using two-level namespace bindings
148              MH_FORCE_FLAT              = 1 << 8,
149                 // the executable is forcing all images to use flat namespace
150                 // bindings.
151              MH_NOMULTIDEFS             = 1 << 8,
152                 // this umbrella guarantees no multiple definitions of symbols
153                 // in its sub-images so the two-level namespace hints can
154                 // always be used.
155              MH_NOFIXPREBINDING         = 1 << 10,
156                 // do not have dyld notify the prebidning agent about this
157                 // executable.
158              MH_PREBINDABLE             = 1 << 11,
159                 // the binary is not prebound but can have its prebinding
160                 // redone.  only used when MH_PREBOUND is not set.
161              MH_ALLMODSBOUND            = 1 << 12,
162                 // indicates that this binary binds to all two-level namespace
163                 // modules of its dependent libraries.  Only used when
164                 // MH_PREBINDABLE and MH_TWOLEVEL are both set.
165              MH_SUBSECTIONS_VIA_SYMBOLS = 1 << 13,
166                 // safe to divide up the sections into sub-sections via symbols
167                 // for dead code stripping.
168              MH_CANONICAL               = 1 << 14,
169                 // the binary has been canonicalized via the unprebind operation
170              MH_WEAK_DEFINES            = 1 << 15,
171                 // the final linked image contains external weak symbols
172              MH_BINDS_TO_WEAK           = 1 << 16,
173                 // the final linked image uses weak symbols
174              MH_ALLOW_STACK_EXECUTION   = 1 << 17
175                 // When this bit is set, all stacks in the task will be given
176                 // stack execution privilege.  Only used in MH_EXECUTE filetype
177       };
178
179       MachOHeader() : magic(0), cputype(0), cpusubtype(0), filetype(0),
180                       ncmds(0), sizeofcmds(0), flags(0), reserved(0) { }
181       
182       /// cmdSize - This routine returns the size of the MachOSection as written
183       /// to disk, depending on whether the destination is a 64 bit Mach-O file.
184       unsigned cmdSize(bool is64Bit) const {
185         if (is64Bit)
186           return 8 * sizeof(uint32_t);
187         else
188           return 7 * sizeof(uint32_t);
189       }
190
191       /// setMagic - This routine sets the appropriate value for the 'magic'
192       /// field based on pointer size and endianness.
193       void setMagic(bool isLittleEndian, bool is64Bit) {
194         if (isLittleEndian)
195           if (is64Bit) magic = 0xcffaedfe;
196           else         magic = 0xcefaedfe;
197         else
198           if (is64Bit) magic = 0xfeedfacf;
199           else         magic = 0xfeedface;
200       }
201     };
202     
203     /// Header - An instance of MachOHeader that we will update while we build
204     /// the file, and then emit during finalization.
205     MachOHeader Header;
206     
207   private:
208
209     /// MachOSegment - This struct contains the necessary information to
210     /// emit the load commands for each section in the file.
211     struct MachOSegment {
212       uint32_t    cmd;      // LC_SEGMENT or LC_SEGMENT_64
213       uint32_t    cmdsize;  // Total size of this struct and section commands
214       std::string segname;  // segment name
215       uint64_t    vmaddr;   // address of this segment
216       uint64_t    vmsize;   // size of this segment, may be larger than filesize
217       uint64_t    fileoff;  // offset in file
218       uint64_t    filesize; // amount to read from file
219       uint32_t    maxprot;  // maximum VM protection
220       uint32_t    initprot; // initial VM protection
221       uint32_t    nsects;   // number of sections in this segment
222       uint32_t    flags;    // flags
223       
224       // Constants for the vm protection fields
225       // see <mach-o/vm_prot.h>
226       enum { VM_PROT_NONE    = 0x00, 
227              VM_PROT_READ    = 0x01, // read permission
228              VM_PROT_WRITE   = 0x02, // write permission
229              VM_PROT_EXECUTE = 0x04, // execute permission,
230              VM_PROT_ALL     = 0x07
231       };
232       
233       // Constants for the cmd field
234       // see <mach-o/loader.h>
235       enum { LC_SEGMENT    = 0x01,  // segment of this file to be mapped
236              LC_SEGMENT_64 = 0x19   // 64-bit segment of this file to be mapped
237       };
238       
239       /// cmdSize - This routine returns the size of the MachOSection as written
240       /// to disk, depending on whether the destination is a 64 bit Mach-O file.
241       unsigned cmdSize(bool is64Bit) const {
242         if (is64Bit)
243           return 6 * sizeof(uint32_t) + 4 * sizeof(uint64_t) + 16;
244         else
245           return 10 * sizeof(uint32_t) + 16;  // addresses only 32 bits
246       }
247
248       MachOSegment(const std::string &seg, bool is64Bit)
249         : cmd(is64Bit ? LC_SEGMENT_64 : LC_SEGMENT), cmdsize(0), segname(seg),
250           vmaddr(0), vmsize(0), fileoff(0), filesize(0), maxprot(VM_PROT_ALL),
251           initprot(VM_PROT_ALL), nsects(0), flags(0) { }
252     };
253
254     /// MachOSection - This struct contains information about each section in a 
255     /// particular segment that is emitted to the file.  This is eventually
256     /// turned into the SectionCommand in the load command for a particlar
257     /// segment.
258     struct MachOSection { 
259       std::string  sectname; // name of this section, 
260       std::string  segname;  // segment this section goes in
261       uint64_t  addr;        // memory address of this section
262       uint64_t  size;        // size in bytes of this section
263       uint32_t  offset;      // file offset of this section
264       uint32_t  align;       // section alignment (power of 2)
265       uint32_t  reloff;      // file offset of relocation entries
266       uint32_t  nreloc;      // number of relocation entries
267       uint32_t  flags;       // flags (section type and attributes)
268       uint32_t  reserved1;   // reserved (for offset or index)
269       uint32_t  reserved2;   // reserved (for count or sizeof)
270       uint32_t  reserved3;   // reserved (64 bit only)
271       
272       /// A unique number for this section, which will be used to match symbols
273       /// to the correct section.
274       uint32_t Index;
275       
276       /// SectionData - The actual data for this section which we are building
277       /// up for emission to the file.
278       DataBuffer SectionData;
279       
280       // Constants for the section types (low 8 bits of flags field)
281       // see <mach-o/loader.h>
282       enum { S_REGULAR = 0,
283                 // regular section
284              S_ZEROFILL = 1,
285                 // zero fill on demand section
286              S_CSTRING_LITERALS = 2,
287                 // section with only literal C strings
288              S_4BYTE_LITERALS = 3,
289                 // section with only 4 byte literals
290              S_8BYTE_LITERALS = 4,
291                 // section with only 8 byte literals
292              S_LITERAL_POINTERS = 5, 
293                 // section with only pointers to literals
294              S_NON_LAZY_SYMBOL_POINTERS = 6,
295                 // section with only non-lazy symbol pointers
296              S_LAZY_SYMBOL_POINTERS = 7,
297                 // section with only lazy symbol pointers
298              S_SYMBOL_STUBS = 8,
299                 // section with only symbol stubs
300                 // byte size of stub in the reserved2 field
301              S_MOD_INIT_FUNC_POINTERS = 9,
302                 // section with only function pointers for initialization
303              S_MOD_TERM_FUNC_POINTERS = 10,
304                 // section with only function pointers for termination
305              S_COALESCED = 11,
306                 // section contains symbols that are coalesced
307              S_GB_ZEROFILL = 12,
308                 // zero fill on demand section (that can be larger than 4GB)
309              S_INTERPOSING = 13,
310                 // section with only pairs of function pointers for interposing
311              S_16BYTE_LITERALS = 14
312                 // section with only 16 byte literals
313       };
314       
315       // Constants for the section flags (high 24 bits of flags field)
316       // see <mach-o/loader.h>
317       enum { S_ATTR_PURE_INSTRUCTIONS   = 1 << 31,
318                 // section contains only true machine instructions
319              S_ATTR_NO_TOC              = 1 << 30,
320                 // section contains coalesced symbols that are not to be in a 
321                 // ranlib table of contents
322              S_ATTR_STRIP_STATIC_SYMS   = 1 << 29,
323                 // ok to strip static symbols in this section in files with the
324                 // MY_DYLDLINK flag
325              S_ATTR_NO_DEAD_STRIP       = 1 << 28,
326                 // no dead stripping
327              S_ATTR_LIVE_SUPPORT        = 1 << 27,
328                 // blocks are live if they reference live blocks
329              S_ATTR_SELF_MODIFYING_CODE = 1 << 26,
330                 // used with i386 code stubs written on by dyld
331              S_ATTR_DEBUG               = 1 << 25,
332                 // a debug section
333              S_ATTR_SOME_INSTRUCTIONS   = 1 << 10,
334                 // section contains some machine instructions
335              S_ATTR_EXT_RELOC           = 1 << 9,
336                 // section has external relocation entries
337              S_ATTR_LOC_RELOC           = 1 << 8
338                 // section has local relocation entries
339       };
340
341       /// cmdSize - This routine returns the size of the MachOSection as written
342       /// to disk, depending on whether the destination is a 64 bit Mach-O file.
343       unsigned cmdSize(bool is64Bit) const {
344         if (is64Bit)
345           return 7 * sizeof(uint32_t) + 2 * sizeof(uint64_t) + 32;
346         else
347           return 9 * sizeof(uint32_t) + 32;  // addresses only 32 bits
348       }
349
350       MachOSection(const std::string &seg, const std::string &sect)
351         : sectname(sect), segname(seg), addr(0), size(0), offset(0), align(0),
352           reloff(0), nreloc(0), flags(0), reserved1(0), reserved2(0),
353           reserved3(0) { }
354     };
355
356     /// SectionList - This is the list of sections that we have emitted to the
357     /// file.  Once the file has been completely built, the segment load command
358     /// SectionCommands are constructed from this info.
359     std::list<MachOSection> SectionList;
360
361     /// SectionLookup - This is a mapping from section name to SectionList entry
362     std::map<std::string, MachOSection*> SectionLookup;
363
364     /// getSection - Return the section with the specified name, creating a new
365     /// section if one does not already exist.
366     MachOSection &getSection(const std::string &seg, const std::string &sect,
367                              unsigned Flags = 0) {
368       MachOSection *&SN = SectionLookup[seg+sect];
369       if (SN) return *SN;
370
371       SectionList.push_back(MachOSection(seg, sect));
372       SN = &SectionList.back();
373       SN->Index = SectionList.size();
374       SN->flags = MachOSection::S_REGULAR | Flags;
375       return *SN;
376     }
377     MachOSection &getTextSection() {
378       return getSection("__TEXT", "__text", 
379                         MachOSection::S_ATTR_PURE_INSTRUCTIONS |
380                         MachOSection::S_ATTR_SOME_INSTRUCTIONS);
381     }
382     MachOSection &getBSSSection() {
383       return getSection("__DATA", "__bss", MachOSection::S_ZEROFILL);
384     }
385     MachOSection &getDataSection() {
386       return getSection("__DATA", "__data");
387     }
388     MachOSection &getConstSection(const Type *Ty) {
389       // FIXME: support cstring literals and pointer literal
390       if (Ty->isPrimitiveType()) {
391         unsigned Size = TM.getTargetData()->getTypeSize(Ty);
392         switch(Size) {
393         default: break; // Fall through to __TEXT,__const
394         case 4:
395           return getSection("__TEXT", "__literal4",
396                             MachOSection::S_4BYTE_LITERALS);
397         case 8:
398           return getSection("__TEXT", "__literal8",
399                             MachOSection::S_8BYTE_LITERALS);
400         case 16:
401           return getSection("__TEXT", "__literal16",
402                             MachOSection::S_16BYTE_LITERALS);
403         }
404       }
405       return getSection("__TEXT", "__const");
406     }
407     
408     /// MachOSymTab - This struct contains information about the offsets and 
409     /// size of symbol table information.
410     /// segment.
411     struct MachOSymTab {
412       uint32_t cmd;     // LC_SYMTAB
413       uint32_t cmdsize; // sizeof( MachOSymTab )
414       uint32_t symoff;  // symbol table offset
415       uint32_t nsyms;   // number of symbol table entries
416       uint32_t stroff;  // string table offset
417       uint32_t strsize; // string table size in bytes
418
419       // Constants for the cmd field
420       // see <mach-o/loader.h>
421       enum { LC_SYMTAB = 0x02  // link-edit stab symbol table info
422       };
423       
424       MachOSymTab() : cmd(LC_SYMTAB), cmdsize(6 * sizeof(uint32_t)), symoff(0),
425         nsyms(0), stroff(0), strsize(0) { }
426     };
427     
428     /// MachOSymTab - This struct contains information about the offsets and 
429     /// size of symbol table information.
430     /// segment.
431     struct MachODySymTab {
432       uint32_t cmd;             // LC_DYSYMTAB
433       uint32_t cmdsize;         // sizeof( MachODySymTab )
434       uint32_t ilocalsym;       // index to local symbols
435       uint32_t nlocalsym;       // number of local symbols
436       uint32_t iextdefsym;      // index to externally defined symbols
437       uint32_t nextdefsym;      // number of externally defined symbols
438       uint32_t iundefsym;       // index to undefined symbols
439       uint32_t nundefsym;       // number of undefined symbols
440       uint32_t tocoff;          // file offset to table of contents
441       uint32_t ntoc;            // number of entries in table of contents
442       uint32_t modtaboff;       // file offset to module table
443       uint32_t nmodtab;         // number of module table entries
444       uint32_t extrefsymoff;    // offset to referenced symbol table
445       uint32_t nextrefsyms;     // number of referenced symbol table entries
446       uint32_t indirectsymoff;  // file offset to the indirect symbol table
447       uint32_t nindirectsyms;   // number of indirect symbol table entries
448       uint32_t extreloff;       // offset to external relocation entries
449       uint32_t nextrel;         // number of external relocation entries
450       uint32_t locreloff;       // offset to local relocation entries
451       uint32_t nlocrel;         // number of local relocation entries
452
453       // Constants for the cmd field
454       // see <mach-o/loader.h>
455       enum { LC_DYSYMTAB = 0x0B  // dynamic link-edit symbol table info
456       };
457       
458       MachODySymTab() : cmd(LC_DYSYMTAB), cmdsize(20 * sizeof(uint32_t)),
459         ilocalsym(0), nlocalsym(0), iextdefsym(0), nextdefsym(0),
460         iundefsym(0), nundefsym(0), tocoff(0), ntoc(0), modtaboff(0),
461         nmodtab(0), extrefsymoff(0), nextrefsyms(0), indirectsymoff(0),
462         nindirectsyms(0), extreloff(0), nextrel(0), locreloff(0), nlocrel(0) { }
463     };
464     
465     /// SymTab - The "stab" style symbol table information
466     MachOSymTab   SymTab;     
467     /// DySymTab - symbol table info for the dynamic link editor
468     MachODySymTab DySymTab;
469
470     /// MachOSym - This struct contains information about each symbol that is
471     /// added to logical symbol table for the module.  This is eventually
472     /// turned into a real symbol table in the file.
473     struct MachOSym {
474       const GlobalValue *GV;    // The global value this corresponds to.
475       uint32_t  n_strx;         // index into the string table
476       uint8_t   n_type;         // type flag
477       uint8_t   n_sect;         // section number or NO_SECT
478       int16_t   n_desc;         // see <mach-o/stab.h>
479       uint64_t  n_value;        // value for this symbol (or stab offset)
480       
481       // Constants for the n_sect field
482       // see <mach-o/nlist.h>
483       enum { NO_SECT = 0 };   // symbol is not in any section
484
485       // Constants for the n_type field
486       // see <mach-o/nlist.h>
487       enum { N_UNDF  = 0x0,  // undefined, n_sect == NO_SECT
488              N_ABS   = 0x2,  // absolute, n_sect == NO_SECT
489              N_SECT  = 0xe,  // defined in section number n_sect
490              N_PBUD  = 0xc,  // prebound undefined (defined in a dylib)
491              N_INDR  = 0xa   // indirect
492       };
493       // The following bits are OR'd into the types above. For example, a type
494       // of 0x0f would be an external N_SECT symbol (0x0e | 0x01).
495       enum { N_EXT  = 0x01,   // external symbol bit
496              N_PEXT = 0x10    // private external symbol bit
497       };
498       
499       // Constants for the n_desc field
500       // see <mach-o/loader.h>
501       enum { REFERENCE_FLAG_UNDEFINED_NON_LAZY          = 0,
502              REFERENCE_FLAG_UNDEFINED_LAZY              = 1,
503              REFERENCE_FLAG_DEFINED                     = 2,
504              REFERENCE_FLAG_PRIVATE_DEFINED             = 3,
505              REFERENCE_FLAG_PRIVATE_UNDEFINED_NON_LAZY  = 4,
506              REFERENCE_FLAG_PRIVATE_UNDEFINED_LAZY      = 5
507       };
508       enum { N_NO_DEAD_STRIP = 0x0020, // symbol is not to be dead stripped
509              N_WEAK_REF      = 0x0040, // symbol is weak referenced
510              N_WEAK_DEF      = 0x0080  // coalesced symbol is a weak definition
511       };
512       
513       /// entrySize - This routine returns the size of a symbol table entry as
514       /// written to disk.
515       static unsigned entrySize() { return 12; }
516
517       MachOSym(const GlobalValue *gv, uint8_t sect) : GV(gv), n_strx(0), 
518         n_type(sect == NO_SECT ? N_UNDF : N_SECT), n_sect(sect), n_desc(0),
519         n_value(0) {}
520     };
521
522     /// SymbolTable - This is the list of symbols we have emitted to the file.
523     /// This actually gets rearranged before emission to the file (to put the
524     /// local symbols first in the list).
525     std::vector<MachOSym> SymbolTable;
526     
527     /// PendingSyms - This is a list of externally defined symbols that we have
528     /// been asked to emit, but have not seen a reference to.  When a reference
529     /// is seen, the symbol will move from this list to the SymbolTable.
530     std::vector<MachOSym> PendingSyms;
531     
532     /// DynamicSymbolTable - This is just a vector of indices into
533     /// SymbolTable to aid in emitting the DYSYMTAB load command.
534     std::vector<unsigned> DynamicSymbolTable;
535     
536     /// StringTable - The table of strings referenced by SymbolTable entries
537     std::vector<std::string> StringTable;
538
539     // align - Emit padding into the file until the current output position is
540     // aligned to the specified power of two boundary.
541     static void align(DataBuffer &Output, unsigned Boundary) {
542       assert(Boundary && (Boundary & (Boundary-1)) == 0 &&
543              "Must align to 2^k boundary");
544       size_t Size = Output.size();
545       if (Size & (Boundary-1)) {
546         // Add padding to get alignment to the correct place.
547         size_t Pad = Boundary-(Size & (Boundary-1));
548         Output.resize(Size+Pad);
549       }
550     }
551
552     void outbyte(DataBuffer &Output, unsigned char X) {
553       Output.push_back(X);
554     }
555     void outhalf(DataBuffer &Output, unsigned short X) {
556       if (isLittleEndian) {
557         Output.push_back(X&255);
558         Output.push_back(X >> 8);
559       } else {
560         Output.push_back(X >> 8);
561         Output.push_back(X&255);
562       }
563     }
564     void outword(DataBuffer &Output, unsigned X) {
565       if (isLittleEndian) {
566         Output.push_back((X >>  0) & 255);
567         Output.push_back((X >>  8) & 255);
568         Output.push_back((X >> 16) & 255);
569         Output.push_back((X >> 24) & 255);
570       } else {
571         Output.push_back((X >> 24) & 255);
572         Output.push_back((X >> 16) & 255);
573         Output.push_back((X >>  8) & 255);
574         Output.push_back((X >>  0) & 255);
575       }
576     }
577     void outxword(DataBuffer &Output, uint64_t X) {
578       if (isLittleEndian) {
579         Output.push_back(unsigned(X >>  0) & 255);
580         Output.push_back(unsigned(X >>  8) & 255);
581         Output.push_back(unsigned(X >> 16) & 255);
582         Output.push_back(unsigned(X >> 24) & 255);
583         Output.push_back(unsigned(X >> 32) & 255);
584         Output.push_back(unsigned(X >> 40) & 255);
585         Output.push_back(unsigned(X >> 48) & 255);
586         Output.push_back(unsigned(X >> 56) & 255);
587       } else {
588         Output.push_back(unsigned(X >> 56) & 255);
589         Output.push_back(unsigned(X >> 48) & 255);
590         Output.push_back(unsigned(X >> 40) & 255);
591         Output.push_back(unsigned(X >> 32) & 255);
592         Output.push_back(unsigned(X >> 24) & 255);
593         Output.push_back(unsigned(X >> 16) & 255);
594         Output.push_back(unsigned(X >>  8) & 255);
595         Output.push_back(unsigned(X >>  0) & 255);
596       }
597     }
598     void outaddr32(DataBuffer &Output, unsigned X) {
599       outword(Output, X);
600     }
601     void outaddr64(DataBuffer &Output, uint64_t X) {
602       outxword(Output, X);
603     }
604     void outaddr(DataBuffer &Output, uint64_t X) {
605       if (!is64Bit)
606         outword(Output, (unsigned)X);
607       else
608         outxword(Output, X);
609     }
610     void outstring(DataBuffer &Output, std::string &S, unsigned Length) {
611       unsigned len_to_copy = S.length() < Length ? S.length() : Length;
612       unsigned len_to_fill = S.length() < Length ? Length-S.length() : 0;
613       
614       for (unsigned i = 0; i < len_to_copy; ++i)
615         outbyte(Output, S[i]);
616
617       for (unsigned i = 0; i < len_to_fill; ++i)
618         outbyte(Output, 0);
619       
620     }
621   private:
622     void AddSymbolToSection(MachOSection &MOS, GlobalVariable *GV);
623     void EmitGlobal(GlobalVariable *GV);
624     void EmitHeaderAndLoadCommands();
625     void EmitSections();
626     void EmitRelocations();
627     void EmitSymbolTable();
628     void EmitStringTable();
629   };
630 }
631
632 #endif