7488b1b6c2a634959b94c1a31d07f20cc3d41fd6
[oota-llvm.git] / lib / MC / ELFObjectWriter.cpp
1 //===- lib/MC/ELFObjectWriter.cpp - ELF File Writer -------------------===//
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 ELF object file writer information.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "MCELF.h"
15 #include "llvm/ADT/OwningPtr.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/MC/MCAssembler.h"
21 #include "llvm/MC/MCAsmLayout.h"
22 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCELFSymbolFlags.h"
24 #include "llvm/MC/MCExpr.h"
25 #include "llvm/MC/MCELFObjectWriter.h"
26 #include "llvm/MC/MCObjectWriter.h"
27 #include "llvm/MC/MCSectionELF.h"
28 #include "llvm/MC/MCSymbol.h"
29 #include "llvm/MC/MCValue.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/ELF.h"
33 #include "llvm/Target/TargetAsmBackend.h"
34 #include "llvm/ADT/StringSwitch.h"
35
36 #include "../Target/X86/X86FixupKinds.h"
37 #include "../Target/ARM/ARMFixupKinds.h"
38
39 #include <vector>
40 using namespace llvm;
41
42 namespace {
43   class ELFObjectWriter : public MCObjectWriter {
44   protected:
45
46     static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
47     static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
48     static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
49     static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
50                            bool Used, bool Renamed);
51     static bool isLocal(const MCSymbolData &Data, bool isSignature,
52                         bool isUsedInReloc);
53     static bool IsELFMetaDataSection(const MCSectionData &SD);
54     static uint64_t DataSectionSize(const MCSectionData &SD);
55     static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
56                                        const MCSectionData &SD);
57     static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
58                                           const MCSectionData &SD);
59     static void WriteDataSectionData(ELFObjectWriter *W,
60                                      const MCSectionData &SD);
61
62     /*static bool isFixupKindX86RIPRel(unsigned Kind) {
63       return Kind == X86::reloc_riprel_4byte ||
64         Kind == X86::reloc_riprel_4byte_movq_load;
65     }*/
66
67     /// ELFSymbolData - Helper struct for containing some precomputed
68     /// information on symbols.
69     struct ELFSymbolData {
70       MCSymbolData *SymbolData;
71       uint64_t StringIndex;
72       uint32_t SectionIndex;
73
74       // Support lexicographic sorting.
75       bool operator<(const ELFSymbolData &RHS) const {
76         if (MCELF::GetType(*SymbolData) == ELF::STT_FILE)
77           return true;
78         if (MCELF::GetType(*RHS.SymbolData) == ELF::STT_FILE)
79           return false;
80         return SymbolData->getSymbol().getName() <
81                RHS.SymbolData->getSymbol().getName();
82       }
83     };
84
85     /// @name Relocation Data
86     /// @{
87
88     struct ELFRelocationEntry {
89       // Make these big enough for both 32-bit and 64-bit
90       uint64_t r_offset;
91       int Index;
92       unsigned Type;
93       const MCSymbol *Symbol;
94       uint64_t r_addend;
95
96       ELFRelocationEntry()
97         : r_offset(0), Index(0), Type(0), Symbol(0), r_addend(0) {}
98
99       ELFRelocationEntry(uint64_t RelocOffset, int Idx,
100                          unsigned RelType, const MCSymbol *Sym,
101                          uint64_t Addend)
102         : r_offset(RelocOffset), Index(Idx), Type(RelType),
103           Symbol(Sym), r_addend(Addend) {}
104
105       // Support lexicographic sorting.
106       bool operator<(const ELFRelocationEntry &RE) const {
107         return RE.r_offset < r_offset;
108       }
109     };
110
111     /// The target specific ELF writer instance.
112     llvm::OwningPtr<MCELFObjectTargetWriter> TargetObjectWriter;
113
114     SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
115     SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
116     DenseMap<const MCSymbol *, const MCSymbol *> Renames;
117
118     llvm::DenseMap<const MCSectionData*,
119                    std::vector<ELFRelocationEntry> > Relocations;
120     DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
121
122     /// @}
123     /// @name Symbol Table Data
124     /// @{
125
126     SmallString<256> StringTable;
127     std::vector<ELFSymbolData> LocalSymbolData;
128     std::vector<ELFSymbolData> ExternalSymbolData;
129     std::vector<ELFSymbolData> UndefinedSymbolData;
130
131     /// @}
132
133     bool NeedsGOT;
134
135     bool NeedsSymtabShndx;
136
137     // This holds the symbol table index of the last local symbol.
138     unsigned LastLocalSymbolIndex;
139     // This holds the .strtab section index.
140     unsigned StringTableIndex;
141     // This holds the .symtab section index.
142     unsigned SymbolTableIndex;
143
144     unsigned ShstrtabIndex;
145
146
147     const MCSymbol *SymbolToReloc(const MCAssembler &Asm,
148                                   const MCValue &Target,
149                                   const MCFragment &F) const;
150
151     // For arch-specific emission of explicit reloc symbol
152     virtual const MCSymbol *ExplicitRelSym(const MCAssembler &Asm,
153                                            const MCValue &Target,
154                                            const MCFragment &F,
155                                            bool IsBSS) const {
156       return NULL;
157     }
158
159     bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
160     bool hasRelocationAddend() const {
161       return TargetObjectWriter->hasRelocationAddend();
162     }
163
164   public:
165     ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
166                     raw_ostream &_OS, bool IsLittleEndian)
167       : MCObjectWriter(_OS, IsLittleEndian),
168         TargetObjectWriter(MOTW),
169         NeedsGOT(false), NeedsSymtabShndx(false){
170     }
171
172     virtual ~ELFObjectWriter();
173
174     void WriteWord(uint64_t W) {
175       if (is64Bit())
176         Write64(W);
177       else
178         Write32(W);
179     }
180
181     void StringLE16(char *buf, uint16_t Value) {
182       buf[0] = char(Value >> 0);
183       buf[1] = char(Value >> 8);
184     }
185
186     void StringLE32(char *buf, uint32_t Value) {
187       StringLE16(buf, uint16_t(Value >> 0));
188       StringLE16(buf + 2, uint16_t(Value >> 16));
189     }
190
191     void StringLE64(char *buf, uint64_t Value) {
192       StringLE32(buf, uint32_t(Value >> 0));
193       StringLE32(buf + 4, uint32_t(Value >> 32));
194     }
195
196     void StringBE16(char *buf ,uint16_t Value) {
197       buf[0] = char(Value >> 8);
198       buf[1] = char(Value >> 0);
199     }
200
201     void StringBE32(char *buf, uint32_t Value) {
202       StringBE16(buf, uint16_t(Value >> 16));
203       StringBE16(buf + 2, uint16_t(Value >> 0));
204     }
205
206     void StringBE64(char *buf, uint64_t Value) {
207       StringBE32(buf, uint32_t(Value >> 32));
208       StringBE32(buf + 4, uint32_t(Value >> 0));
209     }
210
211     void String8(MCDataFragment &F, uint8_t Value) {
212       char buf[1];
213       buf[0] = Value;
214       F.getContents() += StringRef(buf, 1);
215     }
216
217     void String16(MCDataFragment &F, uint16_t Value) {
218       char buf[2];
219       if (isLittleEndian())
220         StringLE16(buf, Value);
221       else
222         StringBE16(buf, Value);
223       F.getContents() += StringRef(buf, 2);
224     }
225
226     void String32(MCDataFragment &F, uint32_t Value) {
227       char buf[4];
228       if (isLittleEndian())
229         StringLE32(buf, Value);
230       else
231         StringBE32(buf, Value);
232       F.getContents() += StringRef(buf, 4);
233     }
234
235     void String64(MCDataFragment &F, uint64_t Value) {
236       char buf[8];
237       if (isLittleEndian())
238         StringLE64(buf, Value);
239       else
240         StringBE64(buf, Value);
241       F.getContents() += StringRef(buf, 8);
242     }
243
244     virtual void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
245
246     /// Default e_flags = 0
247     virtual void WriteEFlags() { Write32(0); }
248
249     virtual void WriteSymbolEntry(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
250                           uint64_t name, uint8_t info,
251                           uint64_t value, uint64_t size,
252                           uint8_t other, uint32_t shndx,
253                           bool Reserved);
254
255     virtual void WriteSymbol(MCDataFragment *SymtabF,  MCDataFragment *ShndxF,
256                      ELFSymbolData &MSD,
257                      const MCAsmLayout &Layout);
258
259     typedef DenseMap<const MCSectionELF*, uint32_t> SectionIndexMapTy;
260     virtual void WriteSymbolTable(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
261                           const MCAssembler &Asm,
262                           const MCAsmLayout &Layout,
263                           const SectionIndexMapTy &SectionIndexMap);
264
265     virtual void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
266                                   const MCFragment *Fragment, const MCFixup &Fixup,
267                                   MCValue Target, uint64_t &FixedValue);
268
269     virtual uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
270                                          const MCSymbol *S);
271
272     // Map from a group section to the signature symbol
273     typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
274     // Map from a signature symbol to the group section
275     typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
276
277     /// ComputeSymbolTable - Compute the symbol table data
278     ///
279     /// \param StringTable [out] - The string table data.
280     /// \param StringIndexMap [out] - Map from symbol names to offsets in the
281     /// string table.
282     virtual void ComputeSymbolTable(MCAssembler &Asm,
283                             const SectionIndexMapTy &SectionIndexMap,
284                             RevGroupMapTy RevGroupMap);
285
286     virtual void ComputeIndexMap(MCAssembler &Asm,
287                          SectionIndexMapTy &SectionIndexMap);
288
289     virtual void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
290                          const MCSectionData &SD);
291
292     virtual void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
293       for (MCAssembler::const_iterator it = Asm.begin(),
294              ie = Asm.end(); it != ie; ++it) {
295         WriteRelocation(Asm, Layout, *it);
296       }
297     }
298
299     virtual void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
300                                 const SectionIndexMapTy &SectionIndexMap);
301
302     // Create the sections that show up in the symbol table. Currently
303     // those are the .note.GNU-stack section and the group sections.
304     virtual void CreateIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
305                                        GroupMapTy &GroupMap,
306                                        RevGroupMapTy &RevGroupMap);
307
308     virtual void ExecutePostLayoutBinding(MCAssembler &Asm,
309                                           const MCAsmLayout &Layout);
310
311     virtual void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
312                           uint64_t Address, uint64_t Offset,
313                           uint64_t Size, uint32_t Link, uint32_t Info,
314                           uint64_t Alignment, uint64_t EntrySize);
315
316     virtual void WriteRelocationsFragment(const MCAssembler &Asm,
317                                           MCDataFragment *F,
318                                           const MCSectionData *SD);
319
320     virtual bool
321     IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
322                                            const MCSymbolData &DataA,
323                                            const MCFragment &FB,
324                                            bool InSet,
325                                            bool IsPCRel) const;
326
327     virtual void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
328     virtual void WriteSection(MCAssembler &Asm,
329                       const SectionIndexMapTy &SectionIndexMap,
330                       uint32_t GroupSymbolIndex,
331                       uint64_t Offset, uint64_t Size, uint64_t Alignment,
332                       const MCSectionELF &Section);
333
334   protected:
335     virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
336                                   bool IsPCRel, bool IsRelocWithSymbol,
337                                   int64_t Addend) = 0;
338   };
339
340   //===- X86ELFObjectWriter -------------------------------------------===//
341
342   class X86ELFObjectWriter : public ELFObjectWriter {
343   public:
344     X86ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
345                        raw_ostream &_OS,
346                        bool IsLittleEndian);
347
348     virtual ~X86ELFObjectWriter();
349   protected:
350     virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
351                                   bool IsPCRel, bool IsRelocWithSymbol,
352                                   int64_t Addend);
353   };
354
355
356   //===- ARMELFObjectWriter -------------------------------------------===//
357
358   class ARMELFObjectWriter : public ELFObjectWriter {
359   public:
360     // FIXME: MCAssembler can't yet return the Subtarget,
361     enum { DefaultEABIVersion = 0x05000000U };
362
363     ARMELFObjectWriter(MCELFObjectTargetWriter *MOTW,
364                        raw_ostream &_OS,
365                        bool IsLittleEndian);
366
367     virtual ~ARMELFObjectWriter();
368
369     virtual void WriteEFlags();
370   protected:
371     virtual const MCSymbol *ExplicitRelSym(const MCAssembler &Asm,
372                                            const MCValue &Target,
373                                            const MCFragment &F,
374                                            bool IsBSS) const;
375
376     virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
377                                   bool IsPCRel, bool IsRelocWithSymbol,
378                                   int64_t Addend);
379   };
380
381   //===- MBlazeELFObjectWriter -------------------------------------------===//
382
383   class MBlazeELFObjectWriter : public ELFObjectWriter {
384   public:
385     MBlazeELFObjectWriter(MCELFObjectTargetWriter *MOTW,
386                           raw_ostream &_OS,
387                           bool IsLittleEndian);
388
389     virtual ~MBlazeELFObjectWriter();
390   protected:
391     virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
392                                   bool IsPCRel, bool IsRelocWithSymbol,
393                                   int64_t Addend);
394   };
395 }
396
397 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
398   const MCFixupKindInfo &FKI =
399     Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
400
401   return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
402 }
403
404 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
405   switch (Variant) {
406   default:
407     return false;
408   case MCSymbolRefExpr::VK_GOT:
409   case MCSymbolRefExpr::VK_PLT:
410   case MCSymbolRefExpr::VK_GOTPCREL:
411   case MCSymbolRefExpr::VK_TPOFF:
412   case MCSymbolRefExpr::VK_TLSGD:
413   case MCSymbolRefExpr::VK_GOTTPOFF:
414   case MCSymbolRefExpr::VK_INDNTPOFF:
415   case MCSymbolRefExpr::VK_NTPOFF:
416   case MCSymbolRefExpr::VK_GOTNTPOFF:
417   case MCSymbolRefExpr::VK_TLSLDM:
418   case MCSymbolRefExpr::VK_DTPOFF:
419   case MCSymbolRefExpr::VK_TLSLD:
420     return true;
421   }
422 }
423
424 ELFObjectWriter::~ELFObjectWriter()
425 {}
426
427 // Emit the ELF header.
428 void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
429                                   unsigned NumberOfSections) {
430   // ELF Header
431   // ----------
432   //
433   // Note
434   // ----
435   // emitWord method behaves differently for ELF32 and ELF64, writing
436   // 4 bytes in the former and 8 in the latter.
437
438   Write8(0x7f); // e_ident[EI_MAG0]
439   Write8('E');  // e_ident[EI_MAG1]
440   Write8('L');  // e_ident[EI_MAG2]
441   Write8('F');  // e_ident[EI_MAG3]
442
443   Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
444
445   // e_ident[EI_DATA]
446   Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
447
448   Write8(ELF::EV_CURRENT);        // e_ident[EI_VERSION]
449   // e_ident[EI_OSABI]
450   switch (TargetObjectWriter->getOSType()) {
451     case Triple::FreeBSD:  Write8(ELF::ELFOSABI_FREEBSD); break;
452     case Triple::Linux:    Write8(ELF::ELFOSABI_LINUX); break;
453     default:               Write8(ELF::ELFOSABI_NONE); break;
454   }
455   Write8(0);                  // e_ident[EI_ABIVERSION]
456
457   WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
458
459   Write16(ELF::ET_REL);             // e_type
460
461   Write16(TargetObjectWriter->getEMachine()); // e_machine = target
462
463   Write32(ELF::EV_CURRENT);         // e_version
464   WriteWord(0);                    // e_entry, no entry point in .o file
465   WriteWord(0);                    // e_phoff, no program header for .o
466   WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
467             sizeof(ELF::Elf32_Ehdr)));  // e_shoff = sec hdr table off in bytes
468
469   // e_flags = whatever the target wants
470   WriteEFlags();
471
472   // e_ehsize = ELF header size
473   Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
474
475   Write16(0);                  // e_phentsize = prog header entry size
476   Write16(0);                  // e_phnum = # prog header entries = 0
477
478   // e_shentsize = Section header entry size
479   Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
480
481   // e_shnum     = # of section header ents
482   if (NumberOfSections >= ELF::SHN_LORESERVE)
483     Write16(0);
484   else
485     Write16(NumberOfSections);
486
487   // e_shstrndx  = Section # of '.shstrtab'
488   if (NumberOfSections >= ELF::SHN_LORESERVE)
489     Write16(ELF::SHN_XINDEX);
490   else
491     Write16(ShstrtabIndex);
492 }
493
494 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
495                                        MCDataFragment *ShndxF,
496                                        uint64_t name,
497                                        uint8_t info, uint64_t value,
498                                        uint64_t size, uint8_t other,
499                                        uint32_t shndx,
500                                        bool Reserved) {
501   if (ShndxF) {
502     if (shndx >= ELF::SHN_LORESERVE && !Reserved)
503       String32(*ShndxF, shndx);
504     else
505       String32(*ShndxF, 0);
506   }
507
508   uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
509     uint16_t(ELF::SHN_XINDEX) : shndx;
510
511   if (is64Bit()) {
512     String32(*SymtabF, name);  // st_name
513     String8(*SymtabF, info);   // st_info
514     String8(*SymtabF, other);  // st_other
515     String16(*SymtabF, Index); // st_shndx
516     String64(*SymtabF, value); // st_value
517     String64(*SymtabF, size);  // st_size
518   } else {
519     String32(*SymtabF, name);  // st_name
520     String32(*SymtabF, value); // st_value
521     String32(*SymtabF, size);  // st_size
522     String8(*SymtabF, info);   // st_info
523     String8(*SymtabF, other);  // st_other
524     String16(*SymtabF, Index); // st_shndx
525   }
526 }
527
528 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
529                                       const MCAsmLayout &Layout) {
530   if (Data.isCommon() && Data.isExternal())
531     return Data.getCommonAlignment();
532
533   const MCSymbol &Symbol = Data.getSymbol();
534
535   if (Symbol.isAbsolute() && Symbol.isVariable()) {
536     if (const MCExpr *Value = Symbol.getVariableValue()) {
537       int64_t IntValue;
538       if (Value->EvaluateAsAbsolute(IntValue, Layout))
539         return (uint64_t)IntValue;
540     }
541   }
542
543   if (!Symbol.isInSection())
544     return 0;
545
546   if (Data.getFragment())
547     return Layout.getSymbolOffset(&Data);
548
549   return 0;
550 }
551
552 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
553                                                const MCAsmLayout &Layout) {
554   // The presence of symbol versions causes undefined symbols and
555   // versions declared with @@@ to be renamed.
556
557   for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
558          ie = Asm.symbol_end(); it != ie; ++it) {
559     const MCSymbol &Alias = it->getSymbol();
560     const MCSymbol &Symbol = Alias.AliasedSymbol();
561     MCSymbolData &SD = Asm.getSymbolData(Symbol);
562
563     // Not an alias.
564     if (&Symbol == &Alias)
565       continue;
566
567     StringRef AliasName = Alias.getName();
568     size_t Pos = AliasName.find('@');
569     if (Pos == StringRef::npos)
570       continue;
571
572     // Aliases defined with .symvar copy the binding from the symbol they alias.
573     // This is the first place we are able to copy this information.
574     it->setExternal(SD.isExternal());
575     MCELF::SetBinding(*it, MCELF::GetBinding(SD));
576
577     StringRef Rest = AliasName.substr(Pos);
578     if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
579       continue;
580
581     // FIXME: produce a better error message.
582     if (Symbol.isUndefined() && Rest.startswith("@@") &&
583         !Rest.startswith("@@@"))
584       report_fatal_error("A @@ version cannot be undefined");
585
586     Renames.insert(std::make_pair(&Symbol, &Alias));
587   }
588 }
589
590 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
591                                   MCDataFragment *ShndxF,
592                                   ELFSymbolData &MSD,
593                                   const MCAsmLayout &Layout) {
594   MCSymbolData &OrigData = *MSD.SymbolData;
595   MCSymbolData &Data =
596     Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
597
598   bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
599     Data.getSymbol().isVariable();
600
601   uint8_t Binding = MCELF::GetBinding(OrigData);
602   uint8_t Visibility = MCELF::GetVisibility(OrigData);
603   uint8_t Type = MCELF::GetType(Data);
604
605   uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
606   uint8_t Other = Visibility;
607
608   uint64_t Value = SymbolValue(Data, Layout);
609   uint64_t Size = 0;
610
611   assert(!(Data.isCommon() && !Data.isExternal()));
612
613   const MCExpr *ESize = Data.getSize();
614   if (ESize) {
615     int64_t Res;
616     if (!ESize->EvaluateAsAbsolute(Res, Layout))
617       report_fatal_error("Size expression must be absolute.");
618     Size = Res;
619   }
620
621   // Write out the symbol table entry
622   WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
623                    Size, Other, MSD.SectionIndex, IsReserved);
624 }
625
626 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
627                                        MCDataFragment *ShndxF,
628                                        const MCAssembler &Asm,
629                                        const MCAsmLayout &Layout,
630                                      const SectionIndexMapTy &SectionIndexMap) {
631   // The string table must be emitted first because we need the index
632   // into the string table for all the symbol names.
633   assert(StringTable.size() && "Missing string table");
634
635   // FIXME: Make sure the start of the symbol table is aligned.
636
637   // The first entry is the undefined symbol entry.
638   WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
639
640   // Write the symbol table entries.
641   LastLocalSymbolIndex = LocalSymbolData.size() + 1;
642   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
643     ELFSymbolData &MSD = LocalSymbolData[i];
644     WriteSymbol(SymtabF, ShndxF, MSD, Layout);
645   }
646
647   // Write out a symbol table entry for each regular section.
648   for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
649        ++i) {
650     const MCSectionELF &Section =
651       static_cast<const MCSectionELF&>(i->getSection());
652     if (Section.getType() == ELF::SHT_RELA ||
653         Section.getType() == ELF::SHT_REL ||
654         Section.getType() == ELF::SHT_STRTAB ||
655         Section.getType() == ELF::SHT_SYMTAB)
656       continue;
657     WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
658                      ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section), false);
659     LastLocalSymbolIndex++;
660   }
661
662   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
663     ELFSymbolData &MSD = ExternalSymbolData[i];
664     MCSymbolData &Data = *MSD.SymbolData;
665     assert(((Data.getFlags() & ELF_STB_Global) ||
666             (Data.getFlags() & ELF_STB_Weak)) &&
667            "External symbol requires STB_GLOBAL or STB_WEAK flag");
668     WriteSymbol(SymtabF, ShndxF, MSD, Layout);
669     if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
670       LastLocalSymbolIndex++;
671   }
672
673   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
674     ELFSymbolData &MSD = UndefinedSymbolData[i];
675     MCSymbolData &Data = *MSD.SymbolData;
676     WriteSymbol(SymtabF, ShndxF, MSD, Layout);
677     if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
678       LastLocalSymbolIndex++;
679   }
680 }
681
682 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
683                                                const MCValue &Target,
684                                                const MCFragment &F) const {
685   const MCSymbol &Symbol = Target.getSymA()->getSymbol();
686   const MCSymbol &ASymbol = Symbol.AliasedSymbol();
687   const MCSymbol *Renamed = Renames.lookup(&Symbol);
688   const MCSymbolData &SD = Asm.getSymbolData(Symbol);
689
690   if (ASymbol.isUndefined()) {
691     if (Renamed)
692       return Renamed;
693     return &ASymbol;
694   }
695
696   if (SD.isExternal()) {
697     if (Renamed)
698       return Renamed;
699     return &Symbol;
700   }
701
702   const MCSectionELF &Section =
703     static_cast<const MCSectionELF&>(ASymbol.getSection());
704   const SectionKind secKind = Section.getKind();
705
706   if (secKind.isBSS())
707     return ExplicitRelSym(Asm, Target, F, true);
708
709   if (secKind.isThreadLocal()) {
710     if (Renamed)
711       return Renamed;
712     return &Symbol;
713   }
714
715   MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
716   const MCSectionELF &Sec2 =
717     static_cast<const MCSectionELF&>(F.getParent()->getSection());
718
719   if (&Sec2 != &Section &&
720       (Kind == MCSymbolRefExpr::VK_PLT ||
721        Kind == MCSymbolRefExpr::VK_GOTPCREL ||
722        Kind == MCSymbolRefExpr::VK_GOTOFF)) {
723     if (Renamed)
724       return Renamed;
725     return &Symbol;
726   }
727
728   if (Section.getFlags() & ELF::SHF_MERGE) {
729     if (Target.getConstant() == 0)
730       return NULL;
731     if (Renamed)
732       return Renamed;
733     return &Symbol;
734   }
735
736   return ExplicitRelSym(Asm, Target, F, false);
737 }
738
739
740 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
741                                        const MCAsmLayout &Layout,
742                                        const MCFragment *Fragment,
743                                        const MCFixup &Fixup,
744                                        MCValue Target,
745                                        uint64_t &FixedValue) {
746   int64_t Addend = 0;
747   int Index = 0;
748   int64_t Value = Target.getConstant();
749   const MCSymbol *RelocSymbol = NULL;
750
751   bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
752   if (!Target.isAbsolute()) {
753     const MCSymbol &Symbol = Target.getSymA()->getSymbol();
754     const MCSymbol &ASymbol = Symbol.AliasedSymbol();
755     RelocSymbol = SymbolToReloc(Asm, Target, *Fragment);
756
757     if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
758       const MCSymbol &SymbolB = RefB->getSymbol();
759       MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
760       IsPCRel = true;
761
762       // Offset of the symbol in the section
763       int64_t a = Layout.getSymbolOffset(&SDB);
764
765       // Ofeset of the relocation in the section
766       int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
767       Value += b - a;
768     }
769
770     if (!RelocSymbol) {
771       MCSymbolData &SD = Asm.getSymbolData(ASymbol);
772       MCFragment *F = SD.getFragment();
773
774       Index = F->getParent()->getOrdinal() + 1;
775
776       // Offset of the symbol in the section
777       Value += Layout.getSymbolOffset(&SD);
778     } else {
779       if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
780         WeakrefUsedInReloc.insert(RelocSymbol);
781       else
782         UsedInReloc.insert(RelocSymbol);
783       Index = -1;
784     }
785     Addend = Value;
786     // Compensate for the addend on i386.
787     if (is64Bit())
788       Value = 0;
789   }
790
791   FixedValue = Value;
792   unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
793                                (RelocSymbol != 0), Addend);
794
795   uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
796     Fixup.getOffset();
797
798   if (!hasRelocationAddend())
799     Addend = 0;
800   ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend);
801   Relocations[Fragment->getParent()].push_back(ERE);
802 }
803
804
805 uint64_t
806 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
807                                              const MCSymbol *S) {
808   MCSymbolData &SD = Asm.getSymbolData(*S);
809   return SD.getIndex();
810 }
811
812 bool ELFObjectWriter::isInSymtab(const MCAssembler &Asm,
813                                  const MCSymbolData &Data,
814                                  bool Used, bool Renamed) {
815   if (Data.getFlags() & ELF_Other_Weakref)
816     return false;
817
818   if (Used)
819     return true;
820
821   if (Renamed)
822     return false;
823
824   const MCSymbol &Symbol = Data.getSymbol();
825
826   if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
827     return true;
828
829   const MCSymbol &A = Symbol.AliasedSymbol();
830   if (Symbol.isVariable() && !A.isVariable() && A.isUndefined())
831     return false;
832
833   bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
834   if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
835     return false;
836
837   if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
838     return false;
839
840   if (Symbol.isTemporary())
841     return false;
842
843   return true;
844 }
845
846 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isSignature,
847                               bool isUsedInReloc) {
848   if (Data.isExternal())
849     return false;
850
851   const MCSymbol &Symbol = Data.getSymbol();
852   const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
853
854   if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
855     if (isSignature && !isUsedInReloc)
856       return true;
857
858     return false;
859   }
860
861   return true;
862 }
863
864 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
865                                       SectionIndexMapTy &SectionIndexMap) {
866   unsigned Index = 1;
867   for (MCAssembler::iterator it = Asm.begin(),
868          ie = Asm.end(); it != ie; ++it) {
869     const MCSectionELF &Section =
870       static_cast<const MCSectionELF &>(it->getSection());
871     if (Section.getType() != ELF::SHT_GROUP)
872       continue;
873     SectionIndexMap[&Section] = Index++;
874   }
875
876   for (MCAssembler::iterator it = Asm.begin(),
877          ie = Asm.end(); it != ie; ++it) {
878     const MCSectionELF &Section =
879       static_cast<const MCSectionELF &>(it->getSection());
880     if (Section.getType() == ELF::SHT_GROUP)
881       continue;
882     SectionIndexMap[&Section] = Index++;
883   }
884 }
885
886 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
887                                       const SectionIndexMapTy &SectionIndexMap,
888                                       RevGroupMapTy RevGroupMap) {
889   // FIXME: Is this the correct place to do this?
890   if (NeedsGOT) {
891     llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
892     MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
893     MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
894     Data.setExternal(true);
895     MCELF::SetBinding(Data, ELF::STB_GLOBAL);
896   }
897
898   // Build section lookup table.
899   int NumRegularSections = Asm.size();
900
901   // Index 0 is always the empty string.
902   StringMap<uint64_t> StringIndexMap;
903   StringTable += '\x00';
904
905   // Add the data for the symbols.
906   for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
907          ie = Asm.symbol_end(); it != ie; ++it) {
908     const MCSymbol &Symbol = it->getSymbol();
909
910     bool Used = UsedInReloc.count(&Symbol);
911     bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
912     bool isSignature = RevGroupMap.count(&Symbol);
913
914     if (!isInSymtab(Asm, *it,
915                     Used || WeakrefUsed || isSignature,
916                     Renames.count(&Symbol)))
917       continue;
918
919     ELFSymbolData MSD;
920     MSD.SymbolData = it;
921     const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
922
923     // Undefined symbols are global, but this is the first place we
924     // are able to set it.
925     bool Local = isLocal(*it, isSignature, Used);
926     if (!Local && MCELF::GetBinding(*it) == ELF::STB_LOCAL) {
927       MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
928       MCELF::SetBinding(*it, ELF::STB_GLOBAL);
929       MCELF::SetBinding(SD, ELF::STB_GLOBAL);
930     }
931
932     if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
933       MCELF::SetBinding(*it, ELF::STB_WEAK);
934
935     if (it->isCommon()) {
936       assert(!Local);
937       MSD.SectionIndex = ELF::SHN_COMMON;
938     } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
939       MSD.SectionIndex = ELF::SHN_ABS;
940     } else if (RefSymbol.isUndefined()) {
941       if (isSignature && !Used)
942         MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
943       else
944         MSD.SectionIndex = ELF::SHN_UNDEF;
945     } else {
946       const MCSectionELF &Section =
947         static_cast<const MCSectionELF&>(RefSymbol.getSection());
948       MSD.SectionIndex = SectionIndexMap.lookup(&Section);
949       if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
950         NeedsSymtabShndx = true;
951       assert(MSD.SectionIndex && "Invalid section index!");
952     }
953
954     // The @@@ in symbol version is replaced with @ in undefined symbols and
955     // @@ in defined ones.
956     StringRef Name = Symbol.getName();
957     SmallString<32> Buf;
958
959     size_t Pos = Name.find("@@@");
960     if (Pos != StringRef::npos) {
961       Buf += Name.substr(0, Pos);
962       unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
963       Buf += Name.substr(Pos + Skip);
964       Name = Buf;
965     }
966
967     uint64_t &Entry = StringIndexMap[Name];
968     if (!Entry) {
969       Entry = StringTable.size();
970       StringTable += Name;
971       StringTable += '\x00';
972     }
973     MSD.StringIndex = Entry;
974     if (MSD.SectionIndex == ELF::SHN_UNDEF)
975       UndefinedSymbolData.push_back(MSD);
976     else if (Local)
977       LocalSymbolData.push_back(MSD);
978     else
979       ExternalSymbolData.push_back(MSD);
980   }
981
982   // Symbols are required to be in lexicographic order.
983   array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
984   array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
985   array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
986
987   // Set the symbol indices. Local symbols must come before all other
988   // symbols with non-local bindings.
989   unsigned Index = 1;
990   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
991     LocalSymbolData[i].SymbolData->setIndex(Index++);
992
993   Index += NumRegularSections;
994
995   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
996     ExternalSymbolData[i].SymbolData->setIndex(Index++);
997   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
998     UndefinedSymbolData[i].SymbolData->setIndex(Index++);
999 }
1000
1001 void ELFObjectWriter::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
1002                                       const MCSectionData &SD) {
1003   if (!Relocations[&SD].empty()) {
1004     MCContext &Ctx = Asm.getContext();
1005     const MCSectionELF *RelaSection;
1006     const MCSectionELF &Section =
1007       static_cast<const MCSectionELF&>(SD.getSection());
1008
1009     const StringRef SectionName = Section.getSectionName();
1010     std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1011     RelaSectionName += SectionName;
1012
1013     unsigned EntrySize;
1014     if (hasRelocationAddend())
1015       EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1016     else
1017       EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1018
1019     RelaSection = Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
1020                                     ELF::SHT_RELA : ELF::SHT_REL, 0,
1021                                     SectionKind::getReadOnly(),
1022                                     EntrySize, "");
1023
1024     MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1025     RelaSD.setAlignment(is64Bit() ? 8 : 4);
1026
1027     MCDataFragment *F = new MCDataFragment(&RelaSD);
1028
1029     WriteRelocationsFragment(Asm, F, &SD);
1030   }
1031 }
1032
1033 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1034                                        uint64_t Flags, uint64_t Address,
1035                                        uint64_t Offset, uint64_t Size,
1036                                        uint32_t Link, uint32_t Info,
1037                                        uint64_t Alignment,
1038                                        uint64_t EntrySize) {
1039   Write32(Name);        // sh_name: index into string table
1040   Write32(Type);        // sh_type
1041   WriteWord(Flags);     // sh_flags
1042   WriteWord(Address);   // sh_addr
1043   WriteWord(Offset);    // sh_offset
1044   WriteWord(Size);      // sh_size
1045   Write32(Link);        // sh_link
1046   Write32(Info);        // sh_info
1047   WriteWord(Alignment); // sh_addralign
1048   WriteWord(EntrySize); // sh_entsize
1049 }
1050
1051 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1052                                                MCDataFragment *F,
1053                                                const MCSectionData *SD) {
1054   std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1055   // sort by the r_offset just like gnu as does
1056   array_pod_sort(Relocs.begin(), Relocs.end());
1057
1058   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1059     ELFRelocationEntry entry = Relocs[e - i - 1];
1060
1061     if (!entry.Index)
1062       ;
1063     else if (entry.Index < 0)
1064       entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1065     else
1066       entry.Index += LocalSymbolData.size();
1067     if (is64Bit()) {
1068       String64(*F, entry.r_offset);
1069
1070       struct ELF::Elf64_Rela ERE64;
1071       ERE64.setSymbolAndType(entry.Index, entry.Type);
1072       String64(*F, ERE64.r_info);
1073
1074       if (hasRelocationAddend())
1075         String64(*F, entry.r_addend);
1076     } else {
1077       String32(*F, entry.r_offset);
1078
1079       struct ELF::Elf32_Rela ERE32;
1080       ERE32.setSymbolAndType(entry.Index, entry.Type);
1081       String32(*F, ERE32.r_info);
1082
1083       if (hasRelocationAddend())
1084         String32(*F, entry.r_addend);
1085     }
1086   }
1087 }
1088
1089 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1090                                              MCAsmLayout &Layout,
1091                                     const SectionIndexMapTy &SectionIndexMap) {
1092   MCContext &Ctx = Asm.getContext();
1093   MCDataFragment *F;
1094
1095   unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1096
1097   // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1098   const MCSectionELF *ShstrtabSection =
1099     Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1100                       SectionKind::getReadOnly());
1101   MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1102   ShstrtabSD.setAlignment(1);
1103   ShstrtabIndex = Asm.size();
1104
1105   const MCSectionELF *SymtabSection =
1106     Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1107                       SectionKind::getReadOnly(),
1108                       EntrySize, "");
1109   MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1110   SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1111   SymbolTableIndex = Asm.size();
1112
1113   MCSectionData *SymtabShndxSD = NULL;
1114
1115   if (NeedsSymtabShndx) {
1116     const MCSectionELF *SymtabShndxSection =
1117       Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1118                         SectionKind::getReadOnly(), 4, "");
1119     SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1120     SymtabShndxSD->setAlignment(4);
1121   }
1122
1123   const MCSection *StrtabSection;
1124   StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1125                                     SectionKind::getReadOnly());
1126   MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1127   StrtabSD.setAlignment(1);
1128   StringTableIndex = Asm.size();
1129
1130   WriteRelocations(Asm, Layout);
1131
1132   // Symbol table
1133   F = new MCDataFragment(&SymtabSD);
1134   MCDataFragment *ShndxF = NULL;
1135   if (NeedsSymtabShndx) {
1136     ShndxF = new MCDataFragment(SymtabShndxSD);
1137   }
1138   WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1139
1140   F = new MCDataFragment(&StrtabSD);
1141   F->getContents().append(StringTable.begin(), StringTable.end());
1142
1143   F = new MCDataFragment(&ShstrtabSD);
1144
1145   // Section header string table.
1146   //
1147   // The first entry of a string table holds a null character so skip
1148   // section 0.
1149   uint64_t Index = 1;
1150   F->getContents() += '\x00';
1151
1152   StringMap<uint64_t> SecStringMap;
1153   for (MCAssembler::const_iterator it = Asm.begin(),
1154          ie = Asm.end(); it != ie; ++it) {
1155     const MCSectionELF &Section =
1156       static_cast<const MCSectionELF&>(it->getSection());
1157     // FIXME: We could merge suffixes like in .text and .rela.text.
1158
1159     StringRef Name = Section.getSectionName();
1160     if (SecStringMap.count(Name)) {
1161       SectionStringTableIndex[&Section] =  SecStringMap[Name];
1162       continue;
1163     }
1164     // Remember the index into the string table so we can write it
1165     // into the sh_name field of the section header table.
1166     SectionStringTableIndex[&Section] = Index;
1167     SecStringMap[Name] = Index;
1168
1169     Index += Name.size() + 1;
1170     F->getContents() += Name;
1171     F->getContents() += '\x00';
1172   }
1173 }
1174
1175 void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1176                                             MCAsmLayout &Layout,
1177                                             GroupMapTy &GroupMap,
1178                                             RevGroupMapTy &RevGroupMap) {
1179   // Create the .note.GNU-stack section if needed.
1180   MCContext &Ctx = Asm.getContext();
1181   if (Asm.getNoExecStack()) {
1182     const MCSectionELF *GnuStackSection =
1183       Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1184                         SectionKind::getReadOnly());
1185     Asm.getOrCreateSectionData(*GnuStackSection);
1186   }
1187
1188   // Build the groups
1189   for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1190        it != ie; ++it) {
1191     const MCSectionELF &Section =
1192       static_cast<const MCSectionELF&>(it->getSection());
1193     if (!(Section.getFlags() & ELF::SHF_GROUP))
1194       continue;
1195
1196     const MCSymbol *SignatureSymbol = Section.getGroup();
1197     Asm.getOrCreateSymbolData(*SignatureSymbol);
1198     const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1199     if (!Group) {
1200       Group = Ctx.CreateELFGroupSection();
1201       MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1202       Data.setAlignment(4);
1203       MCDataFragment *F = new MCDataFragment(&Data);
1204       String32(*F, ELF::GRP_COMDAT);
1205     }
1206     GroupMap[Group] = SignatureSymbol;
1207   }
1208
1209   // Add sections to the groups
1210   unsigned Index = 1;
1211   unsigned NumGroups = RevGroupMap.size();
1212   for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1213        it != ie; ++it, ++Index) {
1214     const MCSectionELF &Section =
1215       static_cast<const MCSectionELF&>(it->getSection());
1216     if (!(Section.getFlags() & ELF::SHF_GROUP))
1217       continue;
1218     const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1219     MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1220     // FIXME: we could use the previous fragment
1221     MCDataFragment *F = new MCDataFragment(&Data);
1222     String32(*F, NumGroups + Index);
1223   }
1224 }
1225
1226 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1227                                    const SectionIndexMapTy &SectionIndexMap,
1228                                    uint32_t GroupSymbolIndex,
1229                                    uint64_t Offset, uint64_t Size,
1230                                    uint64_t Alignment,
1231                                    const MCSectionELF &Section) {
1232   uint64_t sh_link = 0;
1233   uint64_t sh_info = 0;
1234
1235   switch(Section.getType()) {
1236   case ELF::SHT_DYNAMIC:
1237     sh_link = SectionStringTableIndex[&Section];
1238     sh_info = 0;
1239     break;
1240
1241   case ELF::SHT_REL:
1242   case ELF::SHT_RELA: {
1243     const MCSectionELF *SymtabSection;
1244     const MCSectionELF *InfoSection;
1245     SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1246                                                    0,
1247                                                    SectionKind::getReadOnly());
1248     sh_link = SectionIndexMap.lookup(SymtabSection);
1249     assert(sh_link && ".symtab not found");
1250
1251     // Remove ".rel" and ".rela" prefixes.
1252     unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1253     StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1254
1255     InfoSection = Asm.getContext().getELFSection(SectionName,
1256                                                  ELF::SHT_PROGBITS, 0,
1257                                                  SectionKind::getReadOnly());
1258     sh_info = SectionIndexMap.lookup(InfoSection);
1259     break;
1260   }
1261
1262   case ELF::SHT_SYMTAB:
1263   case ELF::SHT_DYNSYM:
1264     sh_link = StringTableIndex;
1265     sh_info = LastLocalSymbolIndex;
1266     break;
1267
1268   case ELF::SHT_SYMTAB_SHNDX:
1269     sh_link = SymbolTableIndex;
1270     break;
1271
1272   case ELF::SHT_PROGBITS:
1273   case ELF::SHT_STRTAB:
1274   case ELF::SHT_NOBITS:
1275   case ELF::SHT_NOTE:
1276   case ELF::SHT_NULL:
1277   case ELF::SHT_ARM_ATTRIBUTES:
1278   case ELF::SHT_INIT_ARRAY:
1279   case ELF::SHT_FINI_ARRAY:
1280   case ELF::SHT_PREINIT_ARRAY:
1281   case ELF::SHT_X86_64_UNWIND:
1282     // Nothing to do.
1283     break;
1284
1285   case ELF::SHT_GROUP: {
1286     sh_link = SymbolTableIndex;
1287     sh_info = GroupSymbolIndex;
1288     break;
1289   }
1290
1291   default:
1292     assert(0 && "FIXME: sh_type value not supported!");
1293     break;
1294   }
1295
1296   WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1297                    Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1298                    Alignment, Section.getEntrySize());
1299 }
1300
1301 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1302   return SD.getOrdinal() == ~UINT32_C(0) &&
1303     !SD.getSection().isVirtualSection();
1304 }
1305
1306 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1307   uint64_t Ret = 0;
1308   for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1309        ++i) {
1310     const MCFragment &F = *i;
1311     assert(F.getKind() == MCFragment::FT_Data);
1312     Ret += cast<MCDataFragment>(F).getContents().size();
1313   }
1314   return Ret;
1315 }
1316
1317 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1318                                              const MCSectionData &SD) {
1319   if (IsELFMetaDataSection(SD))
1320     return DataSectionSize(SD);
1321   return Layout.getSectionFileSize(&SD);
1322 }
1323
1324 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1325                                                 const MCSectionData &SD) {
1326   if (IsELFMetaDataSection(SD))
1327     return DataSectionSize(SD);
1328   return Layout.getSectionAddressSize(&SD);
1329 }
1330
1331 void ELFObjectWriter::WriteDataSectionData(ELFObjectWriter *W,
1332                                            const MCSectionData &SD) {
1333   for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1334        ++i) {
1335     const MCFragment &F = *i;
1336     assert(F.getKind() == MCFragment::FT_Data);
1337     W->WriteBytes(cast<MCDataFragment>(F).getContents().str());
1338   }
1339 }
1340
1341 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1342                                   const MCAsmLayout &Layout) {
1343   GroupMapTy GroupMap;
1344   RevGroupMapTy RevGroupMap;
1345   CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1346                         RevGroupMap);
1347
1348   SectionIndexMapTy SectionIndexMap;
1349
1350   ComputeIndexMap(Asm, SectionIndexMap);
1351
1352   // Compute symbol table information.
1353   ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap);
1354
1355   CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1356                          const_cast<MCAsmLayout&>(Layout),
1357                          SectionIndexMap);
1358
1359   // Update to include the metadata sections.
1360   ComputeIndexMap(Asm, SectionIndexMap);
1361
1362   // Add 1 for the null section.
1363   unsigned NumSections = Asm.size() + 1;
1364   uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1365   uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1366                                     sizeof(ELF::Elf32_Ehdr);
1367   uint64_t FileOff = HeaderSize;
1368
1369   std::vector<const MCSectionELF*> Sections;
1370   Sections.resize(NumSections);
1371
1372   for (SectionIndexMapTy::const_iterator i=
1373          SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1374     const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1375     Sections[p.second] = p.first;
1376   }
1377
1378   for (unsigned i = 1; i < NumSections; ++i) {
1379     const MCSectionELF &Section = *Sections[i];
1380     const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1381
1382     FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1383
1384     // Get the size of the section in the output file (including padding).
1385     FileOff += GetSectionFileSize(Layout, SD);
1386   }
1387
1388   FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1389
1390   // Write out the ELF header ...
1391   WriteHeader(FileOff - HeaderSize, NumSections);
1392
1393   FileOff = HeaderSize;
1394
1395   // ... then all of the sections ...
1396   DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1397
1398   for (unsigned i = 1; i < NumSections; ++i) {
1399     const MCSectionELF &Section = *Sections[i];
1400     const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1401
1402     uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1403     WriteZeros(Padding);
1404     FileOff += Padding;
1405
1406     // Remember the offset into the file for this section.
1407     SectionOffsetMap[&Section] = FileOff;
1408
1409     FileOff += GetSectionFileSize(Layout, SD);
1410
1411     if (IsELFMetaDataSection(SD))
1412       WriteDataSectionData(this, SD);
1413     else
1414       Asm.WriteSectionData(&SD, Layout);
1415   }
1416
1417   uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1418   WriteZeros(Padding);
1419   FileOff += Padding;
1420
1421   // ... and then the section header table.
1422   // Should we align the section header table?
1423   //
1424   // Null section first.
1425   uint64_t FirstSectionSize =
1426     NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1427   uint32_t FirstSectionLink =
1428     ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1429   WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1430
1431   for (unsigned i = 1; i < NumSections; ++i) {
1432     const MCSectionELF &Section = *Sections[i];
1433     const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1434     uint32_t GroupSymbolIndex;
1435     if (Section.getType() != ELF::SHT_GROUP)
1436       GroupSymbolIndex = 0;
1437     else
1438       GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, GroupMap[&Section]);
1439
1440     uint64_t Size = GetSectionAddressSize(Layout, SD);
1441
1442     WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1443                  SectionOffsetMap[&Section], Size,
1444                  SD.getAlignment(), Section);
1445   }
1446 }
1447
1448 bool
1449 ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1450                                                       const MCSymbolData &DataA,
1451                                                       const MCFragment &FB,
1452                                                       bool InSet,
1453                                                       bool IsPCRel) const {
1454   if (DataA.getFlags() & ELF_STB_Weak)
1455     return false;
1456   return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1457                                                  Asm, DataA, FB,InSet, IsPCRel);
1458 }
1459
1460 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1461                                             raw_ostream &OS,
1462                                             bool IsLittleEndian) {
1463   switch (MOTW->getEMachine()) {
1464     case ELF::EM_386:
1465     case ELF::EM_X86_64:
1466       return new X86ELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1467     case ELF::EM_ARM:
1468       return new ARMELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1469     case ELF::EM_MBLAZE:
1470       return new MBlazeELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1471     default: llvm_unreachable("Unsupported architecture"); break;
1472   }
1473 }
1474
1475
1476 /// START OF SUBCLASSES for ELFObjectWriter
1477 //===- ARMELFObjectWriter -------------------------------------------===//
1478
1479 ARMELFObjectWriter::ARMELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1480                                        raw_ostream &_OS,
1481                                        bool IsLittleEndian)
1482   : ELFObjectWriter(MOTW, _OS, IsLittleEndian)
1483 {}
1484
1485 ARMELFObjectWriter::~ARMELFObjectWriter()
1486 {}
1487
1488 // FIXME: get the real EABI Version from the Triple.
1489 void ARMELFObjectWriter::WriteEFlags() {
1490   Write32(ELF::EF_ARM_EABIMASK & DefaultEABIVersion);
1491 }
1492
1493 // In ARM, _MergedGlobals and other most symbols get emitted directly.
1494 // I.e. not as an offset to a section symbol.
1495 // This code is a first-cut approximation of what ARM/gcc does.
1496
1497 const MCSymbol *ARMELFObjectWriter::ExplicitRelSym(const MCAssembler &Asm,
1498                                                    const MCValue &Target,
1499                                                    const MCFragment &F,
1500                                                    bool IsBSS) const {
1501   const MCSymbol &Symbol = Target.getSymA()->getSymbol();
1502   bool EmitThisSym = false;
1503
1504   if (IsBSS) {
1505     EmitThisSym = StringSwitch<bool>(Symbol.getName())
1506       .Case("_MergedGlobals", true)
1507       .Default(false);
1508   } else {
1509     EmitThisSym = StringSwitch<bool>(Symbol.getName())
1510       .Case("_MergedGlobals", true)
1511       .StartsWith(".L.str", true)
1512       .Default(false);
1513   }
1514   if (EmitThisSym)
1515     return &Symbol;
1516   if (! Symbol.isTemporary())
1517     return &Symbol;
1518   return NULL;
1519 }
1520
1521 unsigned ARMELFObjectWriter::GetRelocType(const MCValue &Target,
1522                                           const MCFixup &Fixup,
1523                                           bool IsPCRel,
1524                                           bool IsRelocWithSymbol,
1525                                           int64_t Addend) {
1526   MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1527     MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1528
1529   unsigned Type = 0;
1530   if (IsPCRel) {
1531     switch ((unsigned)Fixup.getKind()) {
1532     default: assert(0 && "Unimplemented");
1533     case FK_Data_4:
1534       switch (Modifier) {
1535       default: llvm_unreachable("Unsupported Modifier");
1536       case MCSymbolRefExpr::VK_None:
1537         Type = ELF::R_ARM_BASE_PREL;
1538         break;
1539       case MCSymbolRefExpr::VK_ARM_TLSGD:
1540         assert(0 && "unimplemented");
1541         break;
1542       case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
1543         Type = ELF::R_ARM_TLS_IE32;
1544         break;
1545       }
1546       break;
1547     case ARM::fixup_arm_uncondbranch:
1548       switch (Modifier) {
1549       case MCSymbolRefExpr::VK_ARM_PLT:
1550         Type = ELF::R_ARM_PLT32;
1551         break;
1552       default:
1553         Type = ELF::R_ARM_CALL;
1554         break;
1555       }
1556       break;
1557     case ARM::fixup_arm_condbranch:
1558       Type = ELF::R_ARM_JUMP24;
1559       break;
1560     case ARM::fixup_arm_movt_hi16:
1561     case ARM::fixup_arm_movt_hi16_pcrel:
1562       Type = ELF::R_ARM_MOVT_PREL;
1563       break;
1564     case ARM::fixup_arm_movw_lo16:
1565     case ARM::fixup_arm_movw_lo16_pcrel:
1566       Type = ELF::R_ARM_MOVW_PREL_NC;
1567       break;
1568     case ARM::fixup_t2_movt_hi16:
1569     case ARM::fixup_t2_movt_hi16_pcrel:
1570       Type = ELF::R_ARM_THM_MOVT_PREL;
1571       break;
1572     case ARM::fixup_t2_movw_lo16:
1573     case ARM::fixup_t2_movw_lo16_pcrel:
1574       Type = ELF::R_ARM_THM_MOVW_PREL_NC;
1575       break;
1576     }
1577   } else {
1578     switch ((unsigned)Fixup.getKind()) {
1579     default: llvm_unreachable("invalid fixup kind!");
1580     case FK_Data_4:
1581       switch (Modifier) {
1582       default: llvm_unreachable("Unsupported Modifier"); break;
1583       case MCSymbolRefExpr::VK_ARM_GOT:
1584         Type = ELF::R_ARM_GOT_BREL;
1585         break;
1586       case MCSymbolRefExpr::VK_ARM_TLSGD:
1587         Type = ELF::R_ARM_TLS_GD32;
1588         break;
1589       case MCSymbolRefExpr::VK_ARM_TPOFF:
1590         Type = ELF::R_ARM_TLS_LE32;
1591         break;
1592       case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
1593         Type = ELF::R_ARM_TLS_IE32;
1594         break;
1595       case MCSymbolRefExpr::VK_None:
1596         Type = ELF::R_ARM_ABS32;
1597         break;
1598       case MCSymbolRefExpr::VK_ARM_GOTOFF:
1599         Type = ELF::R_ARM_GOTOFF32;
1600         break;
1601       }
1602       break;
1603     case ARM::fixup_arm_ldst_pcrel_12:
1604     case ARM::fixup_arm_pcrel_10:
1605     case ARM::fixup_arm_adr_pcrel_12:
1606     case ARM::fixup_arm_thumb_bl:
1607     case ARM::fixup_arm_thumb_cb:
1608     case ARM::fixup_arm_thumb_cp:
1609     case ARM::fixup_arm_thumb_br:
1610       assert(0 && "Unimplemented");
1611       break;
1612     case ARM::fixup_arm_uncondbranch:
1613       Type = ELF::R_ARM_CALL;
1614       break;
1615     case ARM::fixup_arm_condbranch:
1616       Type = ELF::R_ARM_JUMP24;
1617       break;
1618     case ARM::fixup_arm_movt_hi16:
1619       Type = ELF::R_ARM_MOVT_ABS;
1620       break;
1621     case ARM::fixup_arm_movw_lo16:
1622       Type = ELF::R_ARM_MOVW_ABS_NC;
1623       break;
1624     case ARM::fixup_t2_movt_hi16:
1625       Type = ELF::R_ARM_THM_MOVT_ABS;
1626       break;
1627     case ARM::fixup_t2_movw_lo16:
1628       Type = ELF::R_ARM_THM_MOVW_ABS_NC;
1629       break;
1630     }
1631   }
1632
1633   if (RelocNeedsGOT(Modifier))
1634     NeedsGOT = true;
1635
1636   return Type;
1637 }
1638
1639 //===- MBlazeELFObjectWriter -------------------------------------------===//
1640
1641 MBlazeELFObjectWriter::MBlazeELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1642                                              raw_ostream &_OS,
1643                                              bool IsLittleEndian)
1644   : ELFObjectWriter(MOTW, _OS, IsLittleEndian) {
1645 }
1646
1647 MBlazeELFObjectWriter::~MBlazeELFObjectWriter() {
1648 }
1649
1650 unsigned MBlazeELFObjectWriter::GetRelocType(const MCValue &Target,
1651                                              const MCFixup &Fixup,
1652                                              bool IsPCRel,
1653                                              bool IsRelocWithSymbol,
1654                                              int64_t Addend) {
1655   // determine the type of the relocation
1656   unsigned Type;
1657   if (IsPCRel) {
1658     switch ((unsigned)Fixup.getKind()) {
1659     default:
1660       llvm_unreachable("Unimplemented");
1661     case FK_PCRel_4:
1662       Type = ELF::R_MICROBLAZE_64_PCREL;
1663       break;
1664     case FK_PCRel_2:
1665       Type = ELF::R_MICROBLAZE_32_PCREL;
1666       break;
1667     }
1668   } else {
1669     switch ((unsigned)Fixup.getKind()) {
1670     default: llvm_unreachable("invalid fixup kind!");
1671     case FK_Data_4:
1672       Type = ((IsRelocWithSymbol || Addend !=0)
1673               ? ELF::R_MICROBLAZE_32
1674               : ELF::R_MICROBLAZE_64);
1675       break;
1676     case FK_Data_2:
1677       Type = ELF::R_MICROBLAZE_32;
1678       break;
1679     }
1680   }
1681   return Type;
1682 }
1683
1684 //===- X86ELFObjectWriter -------------------------------------------===//
1685
1686
1687 X86ELFObjectWriter::X86ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1688                                        raw_ostream &_OS,
1689                                        bool IsLittleEndian)
1690   : ELFObjectWriter(MOTW, _OS, IsLittleEndian)
1691 {}
1692
1693 X86ELFObjectWriter::~X86ELFObjectWriter()
1694 {}
1695
1696 unsigned X86ELFObjectWriter::GetRelocType(const MCValue &Target,
1697                                           const MCFixup &Fixup,
1698                                           bool IsPCRel,
1699                                           bool IsRelocWithSymbol,
1700                                           int64_t Addend) {
1701   // determine the type of the relocation
1702
1703   MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1704     MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1705   unsigned Type;
1706   if (is64Bit()) {
1707     if (IsPCRel) {
1708       switch ((unsigned)Fixup.getKind()) {
1709       default: llvm_unreachable("invalid fixup kind!");
1710       case FK_PCRel_8:
1711         assert(Modifier == MCSymbolRefExpr::VK_None);
1712         Type = ELF::R_X86_64_PC64;
1713         break;
1714       case X86::reloc_signed_4byte:
1715       case X86::reloc_riprel_4byte_movq_load:
1716       case FK_Data_4: // FIXME?
1717       case X86::reloc_riprel_4byte:
1718       case FK_PCRel_4:
1719         switch (Modifier) {
1720         default:
1721           llvm_unreachable("Unimplemented");
1722         case MCSymbolRefExpr::VK_None:
1723           Type = ELF::R_X86_64_PC32;
1724           break;
1725         case MCSymbolRefExpr::VK_PLT:
1726           Type = ELF::R_X86_64_PLT32;
1727           break;
1728         case MCSymbolRefExpr::VK_GOTPCREL:
1729           Type = ELF::R_X86_64_GOTPCREL;
1730           break;
1731         case MCSymbolRefExpr::VK_GOTTPOFF:
1732           Type = ELF::R_X86_64_GOTTPOFF;
1733         break;
1734         case MCSymbolRefExpr::VK_TLSGD:
1735           Type = ELF::R_X86_64_TLSGD;
1736           break;
1737         case MCSymbolRefExpr::VK_TLSLD:
1738           Type = ELF::R_X86_64_TLSLD;
1739           break;
1740         }
1741         break;
1742       case FK_PCRel_2:
1743         assert(Modifier == MCSymbolRefExpr::VK_None);
1744         Type = ELF::R_X86_64_PC16;
1745         break;
1746       case FK_PCRel_1:
1747         assert(Modifier == MCSymbolRefExpr::VK_None);
1748         Type = ELF::R_X86_64_PC8;
1749         break;
1750       }
1751     } else {
1752       switch ((unsigned)Fixup.getKind()) {
1753       default: llvm_unreachable("invalid fixup kind!");
1754       case FK_Data_8: Type = ELF::R_X86_64_64; break;
1755       case X86::reloc_signed_4byte:
1756         assert(isInt<32>(Target.getConstant()));
1757         switch (Modifier) {
1758         default:
1759           llvm_unreachable("Unimplemented");
1760         case MCSymbolRefExpr::VK_None:
1761           Type = ELF::R_X86_64_32S;
1762           break;
1763         case MCSymbolRefExpr::VK_GOT:
1764           Type = ELF::R_X86_64_GOT32;
1765           break;
1766         case MCSymbolRefExpr::VK_GOTPCREL:
1767           Type = ELF::R_X86_64_GOTPCREL;
1768           break;
1769         case MCSymbolRefExpr::VK_TPOFF:
1770           Type = ELF::R_X86_64_TPOFF32;
1771           break;
1772         case MCSymbolRefExpr::VK_DTPOFF:
1773           Type = ELF::R_X86_64_DTPOFF32;
1774           break;
1775         }
1776         break;
1777       case FK_Data_4:
1778         Type = ELF::R_X86_64_32;
1779         break;
1780       case FK_Data_2: Type = ELF::R_X86_64_16; break;
1781       case FK_PCRel_1:
1782       case FK_Data_1: Type = ELF::R_X86_64_8; break;
1783       }
1784     }
1785   } else {
1786     if (IsPCRel) {
1787       switch (Modifier) {
1788       default:
1789         llvm_unreachable("Unimplemented");
1790       case MCSymbolRefExpr::VK_None:
1791         Type = ELF::R_386_PC32;
1792         break;
1793       case MCSymbolRefExpr::VK_PLT:
1794         Type = ELF::R_386_PLT32;
1795         break;
1796       }
1797     } else {
1798       switch ((unsigned)Fixup.getKind()) {
1799       default: llvm_unreachable("invalid fixup kind!");
1800
1801       case X86::reloc_global_offset_table:
1802         Type = ELF::R_386_GOTPC;
1803         break;
1804
1805       // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
1806       // instead?
1807       case X86::reloc_signed_4byte:
1808       case FK_PCRel_4:
1809       case FK_Data_4:
1810         switch (Modifier) {
1811         default:
1812           llvm_unreachable("Unimplemented");
1813         case MCSymbolRefExpr::VK_None:
1814           Type = ELF::R_386_32;
1815           break;
1816         case MCSymbolRefExpr::VK_GOT:
1817           Type = ELF::R_386_GOT32;
1818           break;
1819         case MCSymbolRefExpr::VK_GOTOFF:
1820           Type = ELF::R_386_GOTOFF;
1821           break;
1822         case MCSymbolRefExpr::VK_TLSGD:
1823           Type = ELF::R_386_TLS_GD;
1824           break;
1825         case MCSymbolRefExpr::VK_TPOFF:
1826           Type = ELF::R_386_TLS_LE_32;
1827           break;
1828         case MCSymbolRefExpr::VK_INDNTPOFF:
1829           Type = ELF::R_386_TLS_IE;
1830           break;
1831         case MCSymbolRefExpr::VK_NTPOFF:
1832           Type = ELF::R_386_TLS_LE;
1833           break;
1834         case MCSymbolRefExpr::VK_GOTNTPOFF:
1835           Type = ELF::R_386_TLS_GOTIE;
1836           break;
1837         case MCSymbolRefExpr::VK_TLSLDM:
1838           Type = ELF::R_386_TLS_LDM;
1839           break;
1840         case MCSymbolRefExpr::VK_DTPOFF:
1841           Type = ELF::R_386_TLS_LDO_32;
1842           break;
1843         }
1844         break;
1845       case FK_Data_2: Type = ELF::R_386_16; break;
1846       case FK_PCRel_1:
1847       case FK_Data_1: Type = ELF::R_386_8; break;
1848       }
1849     }
1850   }
1851
1852   if (RelocNeedsGOT(Modifier))
1853     NeedsGOT = true;
1854
1855   return Type;
1856 }