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