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