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