41efe4e441c7ca999905de8907d6c3afa8d308da
[oota-llvm.git] / lib / CodeGen / ELFWriter.cpp
1 //===-- ELFWriter.cpp - Target-independent ELF Writer code ----------------===//
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 implements the target-independent ELF writer.  This file writes out
11 // the ELF file in the following order:
12 //
13 //  #1. ELF Header
14 //  #2. '.text' section
15 //  #3. '.data' section
16 //  #4. '.bss' section  (conceptual position in file)
17 //  ...
18 //  #X. '.shstrtab' section
19 //  #Y. Section Table
20 //
21 // The entries in the section table are laid out as:
22 //  #0. Null entry [required]
23 //  #1. ".text" entry - the program code
24 //  #2. ".data" entry - global variables with initializers.     [ if needed ]
25 //  #3. ".bss" entry  - global variables without initializers.  [ if needed ]
26 //  ...
27 //  #N. ".shstrtab" entry - String table for the section names.
28 //
29 //===----------------------------------------------------------------------===//
30
31 #define DEBUG_TYPE "elfwriter"
32 #include "ELF.h"
33 #include "ELFWriter.h"
34 #include "ELFCodeEmitter.h"
35 #include "llvm/Constants.h"
36 #include "llvm/Module.h"
37 #include "llvm/PassManager.h"
38 #include "llvm/DerivedTypes.h"
39 #include "llvm/CodeGen/BinaryObject.h"
40 #include "llvm/CodeGen/MachineCodeEmitter.h"
41 #include "llvm/CodeGen/ObjectCodeEmitter.h"
42 #include "llvm/CodeGen/MachineCodeEmitter.h"
43 #include "llvm/CodeGen/MachineConstantPool.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCSectionELF.h"
46 #include "llvm/MC/MCAsmInfo.h"
47 #include "llvm/Target/Mangler.h"
48 #include "llvm/Target/TargetAsmInfo.h"
49 #include "llvm/Target/TargetData.h"
50 #include "llvm/Target/TargetELFWriterInfo.h"
51 #include "llvm/Target/TargetLowering.h"
52 #include "llvm/Target/TargetLoweringObjectFile.h"
53 #include "llvm/Target/TargetMachine.h"
54 #include "llvm/Target/TargetRegisterInfo.h"
55 #include "llvm/Support/Debug.h"
56 #include "llvm/Support/ErrorHandling.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include "llvm/ADT/SmallString.h"
59 using namespace llvm;
60
61 char ELFWriter::ID = 0;
62
63 //===----------------------------------------------------------------------===//
64 //                          ELFWriter Implementation
65 //===----------------------------------------------------------------------===//
66
67 ELFWriter::ELFWriter(raw_ostream &o, TargetMachine &tm)
68   : MachineFunctionPass(ID), O(o), TM(tm),
69     OutContext(*new MCContext(*TM.getMCAsmInfo(), *TM.getRegisterInfo(),
70                               new TargetAsmInfo(tm))),
71     TLOF(TM.getTargetLowering()->getObjFileLowering()),
72     is64Bit(TM.getTargetData()->getPointerSizeInBits() == 64),
73     isLittleEndian(TM.getTargetData()->isLittleEndian()),
74     ElfHdr(isLittleEndian, is64Bit) {
75
76   MAI = TM.getMCAsmInfo();
77   TEW = TM.getELFWriterInfo();
78
79   // Create the object code emitter object for this target.
80   ElfCE = new ELFCodeEmitter(*this);
81
82   // Initial number of sections
83   NumSections = 0;
84 }
85
86 ELFWriter::~ELFWriter() {
87   delete ElfCE;
88   delete &OutContext;
89
90   while(!SymbolList.empty()) {
91     delete SymbolList.back(); 
92     SymbolList.pop_back();
93   }
94
95   while(!PrivateSyms.empty()) {
96     delete PrivateSyms.back(); 
97     PrivateSyms.pop_back();
98   }
99
100   while(!SectionList.empty()) {
101     delete SectionList.back(); 
102     SectionList.pop_back();
103   }
104
105   // Release the name mangler object.
106   delete Mang; Mang = 0;
107 }
108
109 // doInitialization - Emit the file header and all of the global variables for
110 // the module to the ELF file.
111 bool ELFWriter::doInitialization(Module &M) {
112   // Initialize TargetLoweringObjectFile.
113   const_cast<TargetLoweringObjectFile&>(TLOF).Initialize(OutContext, TM);
114   
115   Mang = new Mangler(OutContext, *TM.getTargetData());
116
117   // ELF Header
118   // ----------
119   // Fields e_shnum e_shstrndx are only known after all section have
120   // been emitted. They locations in the ouput buffer are recorded so
121   // to be patched up later.
122   //
123   // Note
124   // ----
125   // emitWord method behaves differently for ELF32 and ELF64, writing
126   // 4 bytes in the former and 8 in the last for *_off and *_addr elf types
127
128   ElfHdr.emitByte(0x7f); // e_ident[EI_MAG0]
129   ElfHdr.emitByte('E');  // e_ident[EI_MAG1]
130   ElfHdr.emitByte('L');  // e_ident[EI_MAG2]
131   ElfHdr.emitByte('F');  // e_ident[EI_MAG3]
132
133   ElfHdr.emitByte(TEW->getEIClass()); // e_ident[EI_CLASS]
134   ElfHdr.emitByte(TEW->getEIData());  // e_ident[EI_DATA]
135   ElfHdr.emitByte(ELF::EV_CURRENT);   // e_ident[EI_VERSION]
136   ElfHdr.emitAlignment(16);           // e_ident[EI_NIDENT-EI_PAD]
137
138   ElfHdr.emitWord16(ELF::ET_REL);        // e_type
139   ElfHdr.emitWord16(TEW->getEMachine()); // e_machine = target
140   ElfHdr.emitWord32(ELF::EV_CURRENT);    // e_version
141   ElfHdr.emitWord(0);                    // e_entry, no entry point in .o file
142   ElfHdr.emitWord(0);                    // e_phoff, no program header for .o
143   ELFHdr_e_shoff_Offset = ElfHdr.size();
144   ElfHdr.emitWord(0);                    // e_shoff = sec hdr table off in bytes
145   ElfHdr.emitWord32(TEW->getEFlags());   // e_flags = whatever the target wants
146   ElfHdr.emitWord16(TEW->getHdrSize());  // e_ehsize = ELF header size
147   ElfHdr.emitWord16(0);                  // e_phentsize = prog header entry size
148   ElfHdr.emitWord16(0);                  // e_phnum = # prog header entries = 0
149
150   // e_shentsize = Section header entry size
151   ElfHdr.emitWord16(TEW->getSHdrSize());
152
153   // e_shnum     = # of section header ents
154   ELFHdr_e_shnum_Offset = ElfHdr.size();
155   ElfHdr.emitWord16(0); // Placeholder
156
157   // e_shstrndx  = Section # of '.shstrtab'
158   ELFHdr_e_shstrndx_Offset = ElfHdr.size();
159   ElfHdr.emitWord16(0); // Placeholder
160
161   // Add the null section, which is required to be first in the file.
162   getNullSection();
163
164   // The first entry in the symtab is the null symbol and the second
165   // is a local symbol containing the module/file name
166   SymbolList.push_back(new ELFSym());
167   SymbolList.push_back(ELFSym::getFileSym());
168
169   return false;
170 }
171
172 // AddPendingGlobalSymbol - Add a global to be processed and to
173 // the global symbol lookup, use a zero index because the table
174 // index will be determined later.
175 void ELFWriter::AddPendingGlobalSymbol(const GlobalValue *GV, 
176                                        bool AddToLookup /* = false */) {
177   PendingGlobals.insert(GV);
178   if (AddToLookup) 
179     GblSymLookup[GV] = 0;
180 }
181
182 // AddPendingExternalSymbol - Add the external to be processed
183 // and to the external symbol lookup, use a zero index because
184 // the symbol table index will be determined later.
185 void ELFWriter::AddPendingExternalSymbol(const char *External) {
186   PendingExternals.insert(External);
187   ExtSymLookup[External] = 0;
188 }
189
190 ELFSection &ELFWriter::getDataSection() {
191   const MCSectionELF *Data = (const MCSectionELF *)TLOF.getDataSection();
192   return getSection(Data->getSectionName(), Data->getType(), 
193                     Data->getFlags(), 4);
194 }
195
196 ELFSection &ELFWriter::getBSSSection() {
197   const MCSectionELF *BSS = (const MCSectionELF *)TLOF.getBSSSection();
198   return getSection(BSS->getSectionName(), BSS->getType(), BSS->getFlags(), 4);
199 }
200
201 // getCtorSection - Get the static constructor section
202 ELFSection &ELFWriter::getCtorSection() {
203   const MCSectionELF *Ctor = (const MCSectionELF *)TLOF.getStaticCtorSection();
204   return getSection(Ctor->getSectionName(), Ctor->getType(), Ctor->getFlags()); 
205 }
206
207 // getDtorSection - Get the static destructor section
208 ELFSection &ELFWriter::getDtorSection() {
209   const MCSectionELF *Dtor = (const MCSectionELF *)TLOF.getStaticDtorSection();
210   return getSection(Dtor->getSectionName(), Dtor->getType(), Dtor->getFlags());
211 }
212
213 // getTextSection - Get the text section for the specified function
214 ELFSection &ELFWriter::getTextSection(const Function *F) {
215   const MCSectionELF *Text = 
216     (const MCSectionELF *)TLOF.SectionForGlobal(F, Mang, TM);
217   return getSection(Text->getSectionName(), Text->getType(), Text->getFlags());
218 }
219
220 // getJumpTableSection - Get a read only section for constants when 
221 // emitting jump tables. TODO: add PIC support
222 ELFSection &ELFWriter::getJumpTableSection() {
223   const MCSectionELF *JT = 
224     (const MCSectionELF *)TLOF.getSectionForConstant(SectionKind::getReadOnly());
225   return getSection(JT->getSectionName(), JT->getType(), JT->getFlags(),
226                     TM.getTargetData()->getPointerABIAlignment());
227 }
228
229 // getConstantPoolSection - Get a constant pool section based on the machine 
230 // constant pool entry type and relocation info.
231 ELFSection &ELFWriter::getConstantPoolSection(MachineConstantPoolEntry &CPE) {
232   SectionKind Kind;
233   switch (CPE.getRelocationInfo()) {
234   default: llvm_unreachable("Unknown section kind");
235   case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
236   case 1:
237     Kind = SectionKind::getReadOnlyWithRelLocal();
238     break;
239   case 0:
240     switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
241     case 4:  Kind = SectionKind::getMergeableConst4(); break;
242     case 8:  Kind = SectionKind::getMergeableConst8(); break;
243     case 16: Kind = SectionKind::getMergeableConst16(); break;
244     default: Kind = SectionKind::getMergeableConst(); break;
245     }
246   }
247
248   const MCSectionELF *CPSect = 
249     (const MCSectionELF *)TLOF.getSectionForConstant(Kind);
250   return getSection(CPSect->getSectionName(), CPSect->getType(), 
251                     CPSect->getFlags(), CPE.getAlignment());
252 }
253
254 // getRelocSection - Return the relocation section of section 'S'. 'RelA' 
255 // is true if the relocation section contains entries with addends.
256 ELFSection &ELFWriter::getRelocSection(ELFSection &S) {
257   unsigned SectionType = TEW->hasRelocationAddend() ?
258                 ELF::SHT_RELA : ELF::SHT_REL;
259
260   std::string SectionName(".rel");
261   if (TEW->hasRelocationAddend())
262     SectionName.append("a");
263   SectionName.append(S.getName());
264
265   return getSection(SectionName, SectionType, 0, TEW->getPrefELFAlignment());
266 }
267
268 // getGlobalELFVisibility - Returns the ELF specific visibility type
269 unsigned ELFWriter::getGlobalELFVisibility(const GlobalValue *GV) {
270   switch (GV->getVisibility()) {
271   default:
272     llvm_unreachable("unknown visibility type");
273   case GlobalValue::DefaultVisibility:
274     return ELF::STV_DEFAULT;
275   case GlobalValue::HiddenVisibility:
276     return ELF::STV_HIDDEN;
277   case GlobalValue::ProtectedVisibility:
278     return ELF::STV_PROTECTED;
279   }
280   return 0;
281 }
282
283 // getGlobalELFBinding - Returns the ELF specific binding type
284 unsigned ELFWriter::getGlobalELFBinding(const GlobalValue *GV) {
285   if (GV->hasInternalLinkage())
286     return ELF::STB_LOCAL;
287
288   if (GV->isWeakForLinker() && !GV->hasCommonLinkage())
289     return ELF::STB_WEAK;
290
291   return ELF::STB_GLOBAL;
292 }
293
294 // getGlobalELFType - Returns the ELF specific type for a global
295 unsigned ELFWriter::getGlobalELFType(const GlobalValue *GV) {
296   if (GV->isDeclaration())
297     return ELF::STT_NOTYPE;
298
299   if (isa<Function>(GV))
300     return ELF::STT_FUNC;
301
302   return ELF::STT_OBJECT;
303 }
304
305 // IsELFUndefSym - True if the global value must be marked as a symbol
306 // which points to a SHN_UNDEF section. This means that the symbol has
307 // no definition on the module.
308 static bool IsELFUndefSym(const GlobalValue *GV) {
309   return GV->isDeclaration() || (isa<Function>(GV));
310 }
311
312 // AddToSymbolList - Update the symbol lookup and If the symbol is 
313 // private add it to PrivateSyms list, otherwise to SymbolList. 
314 void ELFWriter::AddToSymbolList(ELFSym *GblSym) {
315   assert(GblSym->isGlobalValue() && "Symbol must be a global value");
316
317   const GlobalValue *GV = GblSym->getGlobalValue(); 
318   if (GV->hasPrivateLinkage()) {
319     // For a private symbols, keep track of the index inside 
320     // the private list since it will never go to the symbol 
321     // table and won't be patched up later.
322     PrivateSyms.push_back(GblSym);
323     GblSymLookup[GV] = PrivateSyms.size()-1;
324   } else {
325     // Non private symbol are left with zero indices until 
326     // they are patched up during the symbol table emition 
327     // (where the indicies are created).
328     SymbolList.push_back(GblSym);
329     GblSymLookup[GV] = 0;
330   }
331 }
332
333 /// HasCommonSymbols - True if this section holds common symbols, this is
334 /// indicated on the ELF object file by a symbol with SHN_COMMON section
335 /// header index.
336 static bool HasCommonSymbols(const MCSectionELF &S) {
337   // FIXME: this is wrong, a common symbol can be in .data for example.
338   if (StringRef(S.getSectionName()).startswith(".gnu.linkonce."))
339     return true;
340
341   return false;
342 }
343
344
345 // EmitGlobal - Choose the right section for global and emit it
346 void ELFWriter::EmitGlobal(const GlobalValue *GV) {
347
348   // Check if the referenced symbol is already emitted
349   if (GblSymLookup.find(GV) != GblSymLookup.end())
350     return;
351
352   // Handle ELF Bind, Visibility and Type for the current symbol
353   unsigned SymBind = getGlobalELFBinding(GV);
354   unsigned SymType = getGlobalELFType(GV);
355   bool IsUndefSym = IsELFUndefSym(GV);
356
357   ELFSym *GblSym = IsUndefSym ? ELFSym::getUndefGV(GV, SymBind)
358     : ELFSym::getGV(GV, SymBind, SymType, getGlobalELFVisibility(GV));
359
360   if (!IsUndefSym) {
361     assert(isa<GlobalVariable>(GV) && "GV not a global variable!");
362     const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
363
364     // Handle special llvm globals
365     if (EmitSpecialLLVMGlobal(GVar))
366       return;
367
368     // Get the ELF section where this global belongs from TLOF
369     const MCSectionELF *S = 
370       (const MCSectionELF *)TLOF.SectionForGlobal(GV, Mang, TM);
371     ELFSection &ES = 
372       getSection(S->getSectionName(), S->getType(), S->getFlags());
373     SectionKind Kind = S->getKind();
374
375     // The symbol align should update the section alignment if needed
376     const TargetData *TD = TM.getTargetData();
377     unsigned Align = TD->getPreferredAlignment(GVar);
378     unsigned Size = TD->getTypeAllocSize(GVar->getInitializer()->getType());
379     GblSym->Size = Size;
380
381     if (HasCommonSymbols(*S)) { // Symbol must go to a common section
382       GblSym->SectionIdx = ELF::SHN_COMMON;
383
384       // A new linkonce section is created for each global in the
385       // common section, the default alignment is 1 and the symbol
386       // value contains its alignment.
387       ES.Align = 1;
388       GblSym->Value = Align;
389
390     } else if (Kind.isBSS() || Kind.isThreadBSS()) { // Symbol goes to BSS.
391       GblSym->SectionIdx = ES.SectionIdx;
392
393       // Update the size with alignment and the next object can
394       // start in the right offset in the section
395       if (Align) ES.Size = (ES.Size + Align-1) & ~(Align-1);
396       ES.Align = std::max(ES.Align, Align);
397
398       // GblSym->Value should contain the virtual offset inside the section.
399       // Virtual because the BSS space is not allocated on ELF objects
400       GblSym->Value = ES.Size;
401       ES.Size += Size;
402
403     } else { // The symbol must go to some kind of data section
404       GblSym->SectionIdx = ES.SectionIdx;
405
406       // GblSym->Value should contain the symbol offset inside the section,
407       // and all symbols should start on their required alignment boundary
408       ES.Align = std::max(ES.Align, Align);
409       ES.emitAlignment(Align);
410       GblSym->Value = ES.size();
411
412       // Emit the global to the data section 'ES'
413       EmitGlobalConstant(GVar->getInitializer(), ES);
414     }
415   }
416
417   AddToSymbolList(GblSym);
418 }
419
420 void ELFWriter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
421                                          ELFSection &GblS) {
422
423   // Print the fields in successive locations. Pad to align if needed!
424   const TargetData *TD = TM.getTargetData();
425   unsigned Size = TD->getTypeAllocSize(CVS->getType());
426   const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
427   uint64_t sizeSoFar = 0;
428   for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
429     const Constant* field = CVS->getOperand(i);
430
431     // Check if padding is needed and insert one or more 0s.
432     uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
433     uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
434                         - cvsLayout->getElementOffset(i)) - fieldSize;
435     sizeSoFar += fieldSize + padSize;
436
437     // Now print the actual field value.
438     EmitGlobalConstant(field, GblS);
439
440     // Insert padding - this may include padding to increase the size of the
441     // current field up to the ABI size (if the struct is not packed) as well
442     // as padding to ensure that the next field starts at the right offset.
443     GblS.emitZeros(padSize);
444   }
445   assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
446          "Layout of constant struct may be incorrect!");
447 }
448
449 void ELFWriter::EmitGlobalConstant(const Constant *CV, ELFSection &GblS) {
450   const TargetData *TD = TM.getTargetData();
451   unsigned Size = TD->getTypeAllocSize(CV->getType());
452
453   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
454     for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
455       EmitGlobalConstant(CVA->getOperand(i), GblS);
456     return;
457   } else if (isa<ConstantAggregateZero>(CV)) {
458     GblS.emitZeros(Size);
459     return;
460   } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
461     EmitGlobalConstantStruct(CVS, GblS);
462     return;
463   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
464     APInt Val = CFP->getValueAPF().bitcastToAPInt();
465     if (CFP->getType()->isDoubleTy())
466       GblS.emitWord64(Val.getZExtValue());
467     else if (CFP->getType()->isFloatTy())
468       GblS.emitWord32(Val.getZExtValue());
469     else if (CFP->getType()->isX86_FP80Ty()) {
470       unsigned PadSize = TD->getTypeAllocSize(CFP->getType())-
471                          TD->getTypeStoreSize(CFP->getType());
472       GblS.emitWordFP80(Val.getRawData(), PadSize);
473     } else if (CFP->getType()->isPPC_FP128Ty())
474       llvm_unreachable("PPC_FP128Ty global emission not implemented");
475     return;
476   } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
477     if (Size == 1)
478       GblS.emitByte(CI->getZExtValue());
479     else if (Size == 2) 
480       GblS.emitWord16(CI->getZExtValue());
481     else if (Size == 4)
482       GblS.emitWord32(CI->getZExtValue());
483     else 
484       EmitGlobalConstantLargeInt(CI, GblS);
485     return;
486   } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
487     VectorType *PTy = CP->getType();
488     for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
489       EmitGlobalConstant(CP->getOperand(I), GblS);
490     return;
491   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
492     // Resolve a constant expression which returns a (Constant, Offset)
493     // pair. If 'Res.first' is a GlobalValue, emit a relocation with 
494     // the offset 'Res.second', otherwise emit a global constant like
495     // it is always done for not contant expression types.
496     CstExprResTy Res = ResolveConstantExpr(CE);
497     const Constant *Op = Res.first;
498
499     if (isa<GlobalValue>(Op))
500       EmitGlobalDataRelocation(cast<const GlobalValue>(Op), 
501                                TD->getTypeAllocSize(Op->getType()), 
502                                GblS, Res.second);
503     else
504       EmitGlobalConstant(Op, GblS);
505
506     return;
507   } else if (CV->getType()->getTypeID() == Type::PointerTyID) {
508     // Fill the data entry with zeros or emit a relocation entry
509     if (isa<ConstantPointerNull>(CV))
510       GblS.emitZeros(Size);
511     else 
512       EmitGlobalDataRelocation(cast<const GlobalValue>(CV), 
513                                Size, GblS);
514     return;
515   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
516     // This is a constant address for a global variable or function and
517     // therefore must be referenced using a relocation entry.
518     EmitGlobalDataRelocation(GV, Size, GblS);
519     return;
520   }
521
522   std::string msg;
523   raw_string_ostream ErrorMsg(msg);
524   ErrorMsg << "Constant unimp for type: " << *CV->getType();
525   report_fatal_error(ErrorMsg.str());
526 }
527
528 // ResolveConstantExpr - Resolve the constant expression until it stop
529 // yielding other constant expressions.
530 CstExprResTy ELFWriter::ResolveConstantExpr(const Constant *CV) {
531   const TargetData *TD = TM.getTargetData();
532   
533   // There ins't constant expression inside others anymore
534   if (!isa<ConstantExpr>(CV))
535     return std::make_pair(CV, 0);
536
537   const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
538   switch (CE->getOpcode()) {
539   case Instruction::BitCast:
540     return ResolveConstantExpr(CE->getOperand(0));
541   
542   case Instruction::GetElementPtr: {
543     const Constant *ptrVal = CE->getOperand(0);
544     SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
545     int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), idxVec);
546     return std::make_pair(ptrVal, Offset);
547   }
548   case Instruction::IntToPtr: {
549     Constant *Op = CE->getOperand(0);
550     Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()),
551                                       false/*ZExt*/);
552     return ResolveConstantExpr(Op);
553   }
554   case Instruction::PtrToInt: {
555     Constant *Op = CE->getOperand(0);
556     Type *Ty = CE->getType();
557
558     // We can emit the pointer value into this slot if the slot is an
559     // integer slot greater or equal to the size of the pointer.
560     if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))
561       return ResolveConstantExpr(Op);
562
563     llvm_unreachable("Integer size less then pointer size");
564   }
565   case Instruction::Add:
566   case Instruction::Sub: {
567     // Only handle cases where there's a constant expression with GlobalValue
568     // as first operand and ConstantInt as second, which are the cases we can
569     // solve direclty using a relocation entry. GlobalValue=Op0, CstInt=Op1
570     // 1)  Instruction::Add  => (global) + CstInt
571     // 2)  Instruction::Sub  => (global) + -CstInt
572     const Constant *Op0 = CE->getOperand(0); 
573     const Constant *Op1 = CE->getOperand(1); 
574     assert(isa<ConstantInt>(Op1) && "Op1 must be a ConstantInt");
575
576     CstExprResTy Res = ResolveConstantExpr(Op0);
577     assert(isa<GlobalValue>(Res.first) && "Op0 must be a GlobalValue");
578
579     const APInt &RHS = cast<ConstantInt>(Op1)->getValue();
580     switch (CE->getOpcode()) {
581     case Instruction::Add: 
582       return std::make_pair(Res.first, RHS.getSExtValue());
583     case Instruction::Sub:
584       return std::make_pair(Res.first, (-RHS).getSExtValue());
585     }
586   }
587   }
588
589   report_fatal_error(CE->getOpcodeName() +
590                      StringRef(": Unsupported ConstantExpr type"));
591
592   return std::make_pair(CV, 0); // silence warning
593 }
594
595 void ELFWriter::EmitGlobalDataRelocation(const GlobalValue *GV, unsigned Size,
596                                          ELFSection &GblS, int64_t Offset) {
597   // Create the relocation entry for the global value
598   MachineRelocation MR =
599     MachineRelocation::getGV(GblS.getCurrentPCOffset(),
600                              TEW->getAbsoluteLabelMachineRelTy(),
601                              const_cast<GlobalValue*>(GV),
602                              Offset);
603
604   // Fill the data entry with zeros
605   GblS.emitZeros(Size);
606
607   // Add the relocation entry for the current data section
608   GblS.addRelocation(MR);
609 }
610
611 void ELFWriter::EmitGlobalConstantLargeInt(const ConstantInt *CI, 
612                                            ELFSection &S) {
613   const TargetData *TD = TM.getTargetData();
614   unsigned BitWidth = CI->getBitWidth();
615   assert(isPowerOf2_32(BitWidth) &&
616          "Non-power-of-2-sized integers not handled!");
617
618   const uint64_t *RawData = CI->getValue().getRawData();
619   uint64_t Val = 0;
620   for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
621     Val = (TD->isBigEndian()) ? RawData[e - i - 1] : RawData[i];
622     S.emitWord64(Val);
623   }
624 }
625
626 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
627 /// special global used by LLVM.  If so, emit it and return true, otherwise
628 /// do nothing and return false.
629 bool ELFWriter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
630   if (GV->getName() == "llvm.used")
631     llvm_unreachable("not implemented yet");
632
633   // Ignore debug and non-emitted data.  This handles llvm.compiler.used.
634   if (GV->getSection() == "llvm.metadata" ||
635       GV->hasAvailableExternallyLinkage())
636     return true;
637   
638   if (!GV->hasAppendingLinkage()) return false;
639
640   assert(GV->hasInitializer() && "Not a special LLVM global!");
641   
642   const TargetData *TD = TM.getTargetData();
643   unsigned Align = TD->getPointerPrefAlignment();
644   if (GV->getName() == "llvm.global_ctors") {
645     ELFSection &Ctor = getCtorSection();
646     Ctor.emitAlignment(Align);
647     EmitXXStructorList(GV->getInitializer(), Ctor);
648     return true;
649   } 
650   
651   if (GV->getName() == "llvm.global_dtors") {
652     ELFSection &Dtor = getDtorSection();
653     Dtor.emitAlignment(Align);
654     EmitXXStructorList(GV->getInitializer(), Dtor);
655     return true;
656   }
657   
658   return false;
659 }
660
661 /// EmitXXStructorList - Emit the ctor or dtor list.  This just emits out the 
662 /// function pointers, ignoring the init priority.
663 void ELFWriter::EmitXXStructorList(const Constant *List, ELFSection &Xtor) {
664   // Should be an array of '{ i32, void ()* }' structs.  The first value is the
665   // init priority, which we ignore.
666   if (List->isNullValue()) return;
667   const ConstantArray *InitList = cast<ConstantArray>(List);
668   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
669     if (InitList->getOperand(i)->isNullValue())
670       continue;
671     ConstantStruct *CS = cast<ConstantStruct>(InitList->getOperand(i));
672
673     if (CS->getOperand(1)->isNullValue())
674       continue;
675
676     // Emit the function pointer.
677     EmitGlobalConstant(CS->getOperand(1), Xtor);
678   }
679 }
680
681 bool ELFWriter::runOnMachineFunction(MachineFunction &MF) {
682   // Nothing to do here, this is all done through the ElfCE object above.
683   return false;
684 }
685
686 /// doFinalization - Now that the module has been completely processed, emit
687 /// the ELF file to 'O'.
688 bool ELFWriter::doFinalization(Module &M) {
689   // Emit .data section placeholder
690   getDataSection();
691
692   // Emit .bss section placeholder
693   getBSSSection();
694
695   // Build and emit data, bss and "common" sections.
696   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
697        I != E; ++I)
698     EmitGlobal(I);
699
700   // Emit all pending globals
701   for (PendingGblsIter I = PendingGlobals.begin(), E = PendingGlobals.end();
702        I != E; ++I)
703     EmitGlobal(*I);
704
705   // Emit all pending externals
706   for (PendingExtsIter I = PendingExternals.begin(), E = PendingExternals.end();
707        I != E; ++I)
708     SymbolList.push_back(ELFSym::getExtSym(*I));
709
710   // Emit a symbol for each section created until now, skip null section
711   for (unsigned i = 1, e = SectionList.size(); i < e; ++i) {
712     ELFSection &ES = *SectionList[i];
713     ELFSym *SectionSym = ELFSym::getSectionSym();
714     SectionSym->SectionIdx = ES.SectionIdx;
715     SymbolList.push_back(SectionSym);
716     ES.Sym = SymbolList.back();
717   }
718
719   // Emit string table
720   EmitStringTable(M.getModuleIdentifier());
721
722   // Emit the symbol table now, if non-empty.
723   EmitSymbolTable();
724
725   // Emit the relocation sections.
726   EmitRelocations();
727
728   // Emit the sections string table.
729   EmitSectionTableStringTable();
730
731   // Dump the sections and section table to the .o file.
732   OutputSectionsAndSectionTable();
733
734   return false;
735 }
736
737 // RelocateField - Patch relocatable field with 'Offset' in 'BO'
738 // using a 'Value' of known 'Size'
739 void ELFWriter::RelocateField(BinaryObject &BO, uint32_t Offset,
740                               int64_t Value, unsigned Size) {
741   if (Size == 32)
742     BO.fixWord32(Value, Offset);
743   else if (Size == 64)
744     BO.fixWord64(Value, Offset);
745   else
746     llvm_unreachable("don't know howto patch relocatable field");
747 }
748
749 /// EmitRelocations - Emit relocations
750 void ELFWriter::EmitRelocations() {
751
752   // True if the target uses the relocation entry to hold the addend,
753   // otherwise the addend is written directly to the relocatable field.
754   bool HasRelA = TEW->hasRelocationAddend();
755
756   // Create Relocation sections for each section which needs it.
757   for (unsigned i=0, e=SectionList.size(); i != e; ++i) {
758     ELFSection &S = *SectionList[i];
759
760     // This section does not have relocations
761     if (!S.hasRelocations()) continue;
762     ELFSection &RelSec = getRelocSection(S);
763
764     // 'Link' - Section hdr idx of the associated symbol table
765     // 'Info' - Section hdr idx of the section to which the relocation applies
766     ELFSection &SymTab = getSymbolTableSection();
767     RelSec.Link = SymTab.SectionIdx;
768     RelSec.Info = S.SectionIdx;
769     RelSec.EntSize = TEW->getRelocationEntrySize();
770
771     // Get the relocations from Section
772     std::vector<MachineRelocation> Relos = S.getRelocations();
773     for (std::vector<MachineRelocation>::iterator MRI = Relos.begin(),
774          MRE = Relos.end(); MRI != MRE; ++MRI) {
775       MachineRelocation &MR = *MRI;
776
777       // Relocatable field offset from the section start
778       unsigned RelOffset = MR.getMachineCodeOffset();
779
780       // Symbol index in the symbol table
781       unsigned SymIdx = 0;
782
783       // Target specific relocation field type and size
784       unsigned RelType = TEW->getRelocationType(MR.getRelocationType());
785       unsigned RelTySize = TEW->getRelocationTySize(RelType);
786       int64_t Addend = 0;
787
788       // There are several machine relocations types, and each one of
789       // them needs a different approach to retrieve the symbol table index.
790       if (MR.isGlobalValue()) {
791         const GlobalValue *G = MR.getGlobalValue();
792         int64_t GlobalOffset = MR.getConstantVal();
793         SymIdx = GblSymLookup[G];
794         if (G->hasPrivateLinkage()) {
795           // If the target uses a section offset in the relocation:
796           // SymIdx + Addend = section sym for global + section offset
797           unsigned SectionIdx = PrivateSyms[SymIdx]->SectionIdx;
798           Addend = PrivateSyms[SymIdx]->Value + GlobalOffset;
799           SymIdx = SectionList[SectionIdx]->getSymbolTableIndex();
800         } else {
801           Addend = TEW->getDefaultAddendForRelTy(RelType, GlobalOffset);
802         }
803       } else if (MR.isExternalSymbol()) {
804         const char *ExtSym = MR.getExternalSymbol();
805         SymIdx = ExtSymLookup[ExtSym];
806         Addend = TEW->getDefaultAddendForRelTy(RelType);
807       } else {
808         // Get the symbol index for the section symbol
809         unsigned SectionIdx = MR.getConstantVal();
810         SymIdx = SectionList[SectionIdx]->getSymbolTableIndex();
811
812         // The symbol offset inside the section
813         int64_t SymOffset = (int64_t)MR.getResultPointer();
814
815         // For pc relative relocations where symbols are defined in the same
816         // section they are referenced, ignore the relocation entry and patch
817         // the relocatable field with the symbol offset directly.
818         if (S.SectionIdx == SectionIdx && TEW->isPCRelativeRel(RelType)) {
819           int64_t Value = TEW->computeRelocation(SymOffset, RelOffset, RelType);
820           RelocateField(S, RelOffset, Value, RelTySize);
821           continue;
822         }
823
824         Addend = TEW->getDefaultAddendForRelTy(RelType, SymOffset);
825       }
826
827       // The target without addend on the relocation symbol must be
828       // patched in the relocation place itself to contain the addend
829       // otherwise write zeros to make sure there is no garbage there
830       RelocateField(S, RelOffset, HasRelA ? 0 : Addend, RelTySize);
831
832       // Get the relocation entry and emit to the relocation section
833       ELFRelocation Rel(RelOffset, SymIdx, RelType, HasRelA, Addend);
834       EmitRelocation(RelSec, Rel, HasRelA);
835     }
836   }
837 }
838
839 /// EmitRelocation - Write relocation 'Rel' to the relocation section 'Rel'
840 void ELFWriter::EmitRelocation(BinaryObject &RelSec, ELFRelocation &Rel,
841                                bool HasRelA) {
842   RelSec.emitWord(Rel.getOffset());
843   RelSec.emitWord(Rel.getInfo(is64Bit));
844   if (HasRelA)
845     RelSec.emitWord(Rel.getAddend());
846 }
847
848 /// EmitSymbol - Write symbol 'Sym' to the symbol table 'SymbolTable'
849 void ELFWriter::EmitSymbol(BinaryObject &SymbolTable, ELFSym &Sym) {
850   if (is64Bit) {
851     SymbolTable.emitWord32(Sym.NameIdx);
852     SymbolTable.emitByte(Sym.Info);
853     SymbolTable.emitByte(Sym.Other);
854     SymbolTable.emitWord16(Sym.SectionIdx);
855     SymbolTable.emitWord64(Sym.Value);
856     SymbolTable.emitWord64(Sym.Size);
857   } else {
858     SymbolTable.emitWord32(Sym.NameIdx);
859     SymbolTable.emitWord32(Sym.Value);
860     SymbolTable.emitWord32(Sym.Size);
861     SymbolTable.emitByte(Sym.Info);
862     SymbolTable.emitByte(Sym.Other);
863     SymbolTable.emitWord16(Sym.SectionIdx);
864   }
865 }
866
867 /// EmitSectionHeader - Write section 'Section' header in 'SHdrTab'
868 /// Section Header Table
869 void ELFWriter::EmitSectionHeader(BinaryObject &SHdrTab,
870                                   const ELFSection &SHdr) {
871   SHdrTab.emitWord32(SHdr.NameIdx);
872   SHdrTab.emitWord32(SHdr.Type);
873   if (is64Bit) {
874     SHdrTab.emitWord64(SHdr.Flags);
875     SHdrTab.emitWord(SHdr.Addr);
876     SHdrTab.emitWord(SHdr.Offset);
877     SHdrTab.emitWord64(SHdr.Size);
878     SHdrTab.emitWord32(SHdr.Link);
879     SHdrTab.emitWord32(SHdr.Info);
880     SHdrTab.emitWord64(SHdr.Align);
881     SHdrTab.emitWord64(SHdr.EntSize);
882   } else {
883     SHdrTab.emitWord32(SHdr.Flags);
884     SHdrTab.emitWord(SHdr.Addr);
885     SHdrTab.emitWord(SHdr.Offset);
886     SHdrTab.emitWord32(SHdr.Size);
887     SHdrTab.emitWord32(SHdr.Link);
888     SHdrTab.emitWord32(SHdr.Info);
889     SHdrTab.emitWord32(SHdr.Align);
890     SHdrTab.emitWord32(SHdr.EntSize);
891   }
892 }
893
894 /// EmitStringTable - If the current symbol table is non-empty, emit the string
895 /// table for it
896 void ELFWriter::EmitStringTable(const std::string &ModuleName) {
897   if (!SymbolList.size()) return;  // Empty symbol table.
898   ELFSection &StrTab = getStringTableSection();
899
900   // Set the zero'th symbol to a null byte, as required.
901   StrTab.emitByte(0);
902
903   // Walk on the symbol list and write symbol names into the string table.
904   unsigned Index = 1;
905   for (ELFSymIter I=SymbolList.begin(), E=SymbolList.end(); I != E; ++I) {
906     ELFSym &Sym = *(*I);
907
908     std::string Name;
909     if (Sym.isGlobalValue()) {
910       SmallString<40> NameStr;
911       Mang->getNameWithPrefix(NameStr, Sym.getGlobalValue(), false);
912       Name.append(NameStr.begin(), NameStr.end());
913     } else if (Sym.isExternalSym())
914       Name.append(Sym.getExternalSymbol());
915     else if (Sym.isFileType())
916       Name.append(ModuleName);
917
918     if (Name.empty()) {
919       Sym.NameIdx = 0;
920     } else {
921       Sym.NameIdx = Index;
922       StrTab.emitString(Name);
923
924       // Keep track of the number of bytes emitted to this section.
925       Index += Name.size()+1;
926     }
927   }
928   assert(Index == StrTab.size());
929   StrTab.Size = Index;
930 }
931
932 // SortSymbols - On the symbol table local symbols must come before
933 // all other symbols with non-local bindings. The return value is
934 // the position of the first non local symbol.
935 unsigned ELFWriter::SortSymbols() {
936   unsigned FirstNonLocalSymbol;
937   std::vector<ELFSym*> LocalSyms, OtherSyms;
938
939   for (ELFSymIter I=SymbolList.begin(), E=SymbolList.end(); I != E; ++I) {
940     if ((*I)->isLocalBind())
941       LocalSyms.push_back(*I);
942     else
943       OtherSyms.push_back(*I);
944   }
945   SymbolList.clear();
946   FirstNonLocalSymbol = LocalSyms.size();
947
948   for (unsigned i = 0; i < FirstNonLocalSymbol; ++i)
949     SymbolList.push_back(LocalSyms[i]);
950
951   for (ELFSymIter I=OtherSyms.begin(), E=OtherSyms.end(); I != E; ++I)
952     SymbolList.push_back(*I);
953
954   LocalSyms.clear();
955   OtherSyms.clear();
956
957   return FirstNonLocalSymbol;
958 }
959
960 /// EmitSymbolTable - Emit the symbol table itself.
961 void ELFWriter::EmitSymbolTable() {
962   if (!SymbolList.size()) return;  // Empty symbol table.
963
964   // Now that we have emitted the string table and know the offset into the
965   // string table of each symbol, emit the symbol table itself.
966   ELFSection &SymTab = getSymbolTableSection();
967   SymTab.Align = TEW->getPrefELFAlignment();
968
969   // Section Index of .strtab.
970   SymTab.Link = getStringTableSection().SectionIdx;
971
972   // Size of each symtab entry.
973   SymTab.EntSize = TEW->getSymTabEntrySize();
974
975   // Reorder the symbol table with local symbols first!
976   unsigned FirstNonLocalSymbol = SortSymbols();
977
978   // Emit all the symbols to the symbol table.
979   for (unsigned i = 0, e = SymbolList.size(); i < e; ++i) {
980     ELFSym &Sym = *SymbolList[i];
981
982     // Emit symbol to the symbol table
983     EmitSymbol(SymTab, Sym);
984
985     // Record the symbol table index for each symbol
986     if (Sym.isGlobalValue())
987       GblSymLookup[Sym.getGlobalValue()] = i;
988     else if (Sym.isExternalSym())
989       ExtSymLookup[Sym.getExternalSymbol()] = i;
990
991     // Keep track on the symbol index into the symbol table
992     Sym.SymTabIdx = i;
993   }
994
995   // One greater than the symbol table index of the last local symbol
996   SymTab.Info = FirstNonLocalSymbol;
997   SymTab.Size = SymTab.size();
998 }
999
1000 /// EmitSectionTableStringTable - This method adds and emits a section for the
1001 /// ELF Section Table string table: the string table that holds all of the
1002 /// section names.
1003 void ELFWriter::EmitSectionTableStringTable() {
1004   // First step: add the section for the string table to the list of sections:
1005   ELFSection &SHStrTab = getSectionHeaderStringTableSection();
1006
1007   // Now that we know which section number is the .shstrtab section, update the
1008   // e_shstrndx entry in the ELF header.
1009   ElfHdr.fixWord16(SHStrTab.SectionIdx, ELFHdr_e_shstrndx_Offset);
1010
1011   // Set the NameIdx of each section in the string table and emit the bytes for
1012   // the string table.
1013   unsigned Index = 0;
1014
1015   for (ELFSectionIter I=SectionList.begin(), E=SectionList.end(); I != E; ++I) {
1016     ELFSection &S = *(*I);
1017     // Set the index into the table.  Note if we have lots of entries with
1018     // common suffixes, we could memoize them here if we cared.
1019     S.NameIdx = Index;
1020     SHStrTab.emitString(S.getName());
1021
1022     // Keep track of the number of bytes emitted to this section.
1023     Index += S.getName().size()+1;
1024   }
1025
1026   // Set the size of .shstrtab now that we know what it is.
1027   assert(Index == SHStrTab.size());
1028   SHStrTab.Size = Index;
1029 }
1030
1031 /// OutputSectionsAndSectionTable - Now that we have constructed the file header
1032 /// and all of the sections, emit these to the ostream destination and emit the
1033 /// SectionTable.
1034 void ELFWriter::OutputSectionsAndSectionTable() {
1035   // Pass #1: Compute the file offset for each section.
1036   size_t FileOff = ElfHdr.size();   // File header first.
1037
1038   // Adjust alignment of all section if needed, skip the null section.
1039   for (unsigned i=1, e=SectionList.size(); i < e; ++i) {
1040     ELFSection &ES = *SectionList[i];
1041     if (!ES.size()) {
1042       ES.Offset = FileOff;
1043       continue;
1044     }
1045
1046     // Update Section size
1047     if (!ES.Size)
1048       ES.Size = ES.size();
1049
1050     // Align FileOff to whatever the alignment restrictions of the section are.
1051     if (ES.Align)
1052       FileOff = (FileOff+ES.Align-1) & ~(ES.Align-1);
1053
1054     ES.Offset = FileOff;
1055     FileOff += ES.Size;
1056   }
1057
1058   // Align Section Header.
1059   unsigned TableAlign = TEW->getPrefELFAlignment();
1060   FileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
1061
1062   // Now that we know where all of the sections will be emitted, set the e_shnum
1063   // entry in the ELF header.
1064   ElfHdr.fixWord16(NumSections, ELFHdr_e_shnum_Offset);
1065
1066   // Now that we know the offset in the file of the section table, update the
1067   // e_shoff address in the ELF header.
1068   ElfHdr.fixWord(FileOff, ELFHdr_e_shoff_Offset);
1069
1070   // Now that we know all of the data in the file header, emit it and all of the
1071   // sections!
1072   O.write((char *)&ElfHdr.getData()[0], ElfHdr.size());
1073   FileOff = ElfHdr.size();
1074
1075   // Section Header Table blob
1076   BinaryObject SHdrTable(isLittleEndian, is64Bit);
1077
1078   // Emit all of sections to the file and build the section header table.
1079   for (ELFSectionIter I=SectionList.begin(), E=SectionList.end(); I != E; ++I) {
1080     ELFSection &S = *(*I);
1081     DEBUG(dbgs() << "SectionIdx: " << S.SectionIdx << ", Name: " << S.getName()
1082                  << ", Size: " << S.Size << ", Offset: " << S.Offset
1083                  << ", SectionData Size: " << S.size() << "\n");
1084
1085     // Align FileOff to whatever the alignment restrictions of the section are.
1086     if (S.size()) {
1087       if (S.Align)  {
1088         for (size_t NewFileOff = (FileOff+S.Align-1) & ~(S.Align-1);
1089              FileOff != NewFileOff; ++FileOff)
1090           O << (char)0xAB;
1091       }
1092       O.write((char *)&S.getData()[0], S.Size);
1093       FileOff += S.Size;
1094     }
1095
1096     EmitSectionHeader(SHdrTable, S);
1097   }
1098
1099   // Align output for the section table.
1100   for (size_t NewFileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
1101        FileOff != NewFileOff; ++FileOff)
1102     O << (char)0xAB;
1103
1104   // Emit the section table itself.
1105   O.write((char *)&SHdrTable.getData()[0], SHdrTable.size());
1106 }