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