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