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