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