8dcd970cfc6377cdccd00c9b10f27bc8977b40ae
[oota-llvm.git] / lib / CodeGen / ELFWriter.h
1 //===-- ELFWriter.h - Target-independent ELF writer support -----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the ELFWriter class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef ELFWRITER_H
15 #define ELFWRITER_H
16
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 #include <map>
20
21 namespace llvm {
22   class BinaryObject;
23   class Constant;
24   class ConstantStruct;
25   class ELFCodeEmitter;
26   class ELFRelocation;
27   class ELFSection;
28   struct ELFSym;
29   class GlobalVariable;
30   class Mangler;
31   class MachineCodeEmitter;
32   class MachineConstantPoolEntry;
33   class ObjectCodeEmitter;
34   class TargetAsmInfo;
35   class TargetELFWriterInfo;
36   class raw_ostream;
37   class SectionKind;
38
39   typedef std::vector<ELFSym*>::iterator ELFSymIter;
40   typedef std::vector<ELFSection*>::iterator ELFSectionIter;
41
42   /// ELFWriter - This class implements the common target-independent code for
43   /// writing ELF files.  Targets should derive a class from this to
44   /// parameterize the output format.
45   ///
46   class ELFWriter : public MachineFunctionPass {
47     friend class ELFCodeEmitter;
48   public:
49     static char ID;
50
51     /// Return the ELFCodeEmitter as an instance of ObjectCodeEmitter
52     ObjectCodeEmitter *getObjectCodeEmitter() {
53       return reinterpret_cast<ObjectCodeEmitter*>(ElfCE);
54     }
55
56     ELFWriter(raw_ostream &O, TargetMachine &TM);
57     ~ELFWriter();
58
59   protected:
60     /// Output stream to send the resultant object file to.
61     raw_ostream &O;
62
63     /// Target machine description.
64     TargetMachine &TM;
65
66     /// Target Elf Writer description.
67     const TargetELFWriterInfo *TEW;
68
69     /// Mang - The object used to perform name mangling for this module.
70     Mangler *Mang;
71
72     /// MCE - The MachineCodeEmitter object that we are exposing to emit machine
73     /// code for functions to the .o file.
74     ELFCodeEmitter *ElfCE;
75
76     /// TAI - Target Asm Info, provide information about section names for
77     /// globals and other target specific stuff.
78     const TargetAsmInfo *TAI;
79
80     //===------------------------------------------------------------------===//
81     // Properties inferred automatically from the target machine.
82     //===------------------------------------------------------------------===//
83
84     /// is64Bit/isLittleEndian - This information is inferred from the target
85     /// machine directly, indicating whether to emit a 32- or 64-bit ELF file.
86     bool is64Bit, isLittleEndian;
87
88     /// doInitialization - Emit the file header and all of the global variables
89     /// for the module to the ELF file.
90     bool doInitialization(Module &M);
91     bool runOnMachineFunction(MachineFunction &MF);
92
93     /// doFinalization - Now that the module has been completely processed, emit
94     /// the ELF file to 'O'.
95     bool doFinalization(Module &M);
96
97   private:
98     /// Blob containing the Elf header
99     BinaryObject ElfHdr;
100
101     /// SectionList - This is the list of sections that we have emitted to the
102     /// file. Once the file has been completely built, the section header table
103     /// is constructed from this info.
104     std::vector<ELFSection*> SectionList;
105     unsigned NumSections;   // Always = SectionList.size()
106
107     /// SectionLookup - This is a mapping from section name to section number in
108     /// the SectionList. Used to quickly gather the Section Index from TAI names
109     std::map<std::string, ELFSection*> SectionLookup;
110
111     /// GblSymLookup - This is a mapping from global value to a symbol index
112     /// in the symbol table or private symbols list. This is useful since reloc
113     /// symbol references must be quickly mapped to their indices on the lists
114     std::map<const GlobalValue*, uint32_t> GblSymLookup;
115
116     /// SymbolList - This is the list of symbols emitted to the symbol table.
117     /// When the SymbolList is finally built, local symbols must be placed in
118     /// the beginning while non-locals at the end.
119     std::vector<ELFSym*> SymbolList;
120
121     /// PrivateSyms - Record private symbols, every symbol here must never be
122     /// present in the SymbolList.
123     std::vector<ELFSym*> PrivateSyms;
124
125     /// PendingGlobals - List of externally defined symbols that we have been
126     /// asked to emit, but have not seen a reference to.  When a reference
127     /// is seen, the symbol will move from this list to the SymbolList.
128     SetVector<GlobalValue*> PendingGlobals;
129
130     // Remove tab from section name prefix. This is necessary becase TAI
131     // sometimes return a section name prefixed with elf unused chars. This is
132     // a little bit dirty. FIXME: find a better approach, maybe add more
133     // methods to TAI to get the clean name?
134     void fixNameForSection(std::string &Name) {
135       size_t Pos = Name.find("\t");
136       if (Pos != std::string::npos)
137         Name.erase(Pos, 1);
138
139       Pos = Name.find(".section ");
140       if (Pos != std::string::npos)
141         Name.erase(Pos, 9);
142
143       Pos = Name.find("\n");
144       if (Pos != std::string::npos)
145         Name.erase(Pos, 1);
146     }
147
148     /// getSection - Return the section with the specified name, creating a new
149     /// section if one does not already exist.
150     ELFSection &getSection(const std::string &Name, unsigned Type,
151                            unsigned Flags = 0, unsigned Align = 0) {
152       std::string SName(Name);
153       fixNameForSection(SName);
154
155       ELFSection *&SN = SectionLookup[SName];
156       if (SN) return *SN;
157
158       SectionList.push_back(new ELFSection(SName, isLittleEndian, is64Bit));
159       SN = SectionList.back();
160       SN->SectionIdx = NumSections++;
161       SN->Type = Type;
162       SN->Flags = Flags;
163       SN->Link = ELFSection::SHN_UNDEF;
164       SN->Align = Align;
165       return *SN;
166     }
167
168     /// TODO: support mangled names here to emit the right .text section
169     /// for c++ object files.
170     ELFSection &getTextSection() {
171       return getSection(".text", ELFSection::SHT_PROGBITS,
172                         ELFSection::SHF_EXECINSTR | ELFSection::SHF_ALLOC);
173     }
174
175     ELFSection &getNonExecStackSection() {
176       return getSection(".note.GNU-stack", ELFSection::SHT_PROGBITS, 0, 1);
177     }
178
179     ELFSection &getSymbolTableSection() {
180       return getSection(".symtab", ELFSection::SHT_SYMTAB, 0);
181     }
182
183     ELFSection &getStringTableSection() {
184       return getSection(".strtab", ELFSection::SHT_STRTAB, 0, 1);
185     }
186
187     ELFSection &getSectionHeaderStringTableSection() {
188       return getSection(".shstrtab", ELFSection::SHT_STRTAB, 0, 1);
189     }
190
191     ELFSection &getDataSection() {
192       return getSection(".data", ELFSection::SHT_PROGBITS,
193                         ELFSection::SHF_WRITE | ELFSection::SHF_ALLOC, 4);
194     }
195
196     ELFSection &getBSSSection() {
197       return getSection(".bss", ELFSection::SHT_NOBITS,
198                         ELFSection::SHF_WRITE | ELFSection::SHF_ALLOC, 4);
199     }
200
201     ELFSection &getNullSection() {
202       return getSection("", ELFSection::SHT_NULL, 0);
203     }
204
205     ELFSection &getJumpTableSection();
206     ELFSection &getConstantPoolSection(MachineConstantPoolEntry &CPE);
207     ELFSection &getRelocSection(ELFSection &S);
208
209     // Helpers for obtaining ELF specific info.
210     unsigned getGlobalELFBinding(const GlobalValue *GV);
211     unsigned getGlobalELFType(const GlobalValue *GV);
212     unsigned getGlobalELFVisibility(const GlobalValue *GV);
213     unsigned getElfSectionFlags(SectionKind Kind);
214
215     // setGlobalSymLookup - Set global value 'GV' with 'Index' in the lookup map
216     void setGlobalSymLookup(const GlobalValue *GV, unsigned Index) {
217       GblSymLookup[GV] = Index;
218     }
219
220     // As we complete the ELF file, we need to update fields in the ELF header
221     // (e.g. the location of the section table).  These members keep track of
222     // the offset in ELFHeader of these various pieces to update and other
223     // locations in the file.
224     unsigned ELFHdr_e_shoff_Offset;     // e_shoff    in ELF header.
225     unsigned ELFHdr_e_shstrndx_Offset;  // e_shstrndx in ELF header.
226     unsigned ELFHdr_e_shnum_Offset;     // e_shnum    in ELF header.
227
228   private:
229     void EmitGlobal(const GlobalValue *GV);
230     void EmitGlobalConstant(const Constant *C, ELFSection &GblS);
231     void EmitGlobalConstantStruct(const ConstantStruct *CVS,
232                                   ELFSection &GblS);
233     ELFSection &getGlobalSymELFSection(const GlobalVariable *GV, ELFSym &Sym);
234     void EmitRelocations();
235     void EmitRelocation(BinaryObject &RelSec, ELFRelocation &Rel, bool HasRelA);
236     void EmitSectionHeader(BinaryObject &SHdrTab, const ELFSection &SHdr);
237     void EmitSectionTableStringTable();
238     void EmitSymbol(BinaryObject &SymbolTable, ELFSym &Sym);
239     void EmitSymbolTable();
240     void EmitStringTable();
241     void OutputSectionsAndSectionTable();
242     void RelocateField(BinaryObject &BO, uint32_t Offset, int64_t Value,
243                        unsigned Size);
244     unsigned SortSymbols();
245   };
246 }
247
248 #endif