Compute A-B if both A and B are in the same comdat section.
[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/MC/MCELFObjectWriter.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/MC/MCAsmBackend.h"
20 #include "llvm/MC/MCAsmInfo.h"
21 #include "llvm/MC/MCAsmLayout.h"
22 #include "llvm/MC/MCAssembler.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCELF.h"
25 #include "llvm/MC/MCELFSymbolFlags.h"
26 #include "llvm/MC/MCExpr.h"
27 #include "llvm/MC/MCFixupKindInfo.h"
28 #include "llvm/MC/MCObjectWriter.h"
29 #include "llvm/MC/MCSectionELF.h"
30 #include "llvm/MC/MCValue.h"
31 #include "llvm/MC/StringTableBuilder.h"
32 #include "llvm/Support/Compression.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ELF.h"
35 #include "llvm/Support/Endian.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include <vector>
38 using namespace llvm;
39
40 #undef  DEBUG_TYPE
41 #define DEBUG_TYPE "reloc-info"
42
43 namespace {
44 class FragmentWriter {
45   bool IsLittleEndian;
46
47 public:
48   FragmentWriter(bool IsLittleEndian);
49   template <typename T> void write(MCDataFragment &F, T Val);
50 };
51
52 typedef DenseMap<const MCSectionELF *, uint32_t> SectionIndexMapTy;
53
54 class SymbolTableWriter {
55   MCAssembler &Asm;
56   FragmentWriter &FWriter;
57   bool Is64Bit;
58   SectionIndexMapTy &SectionIndexMap;
59
60   // The symbol .symtab fragment we are writting to.
61   MCDataFragment *SymtabF;
62
63   // .symtab_shndx fragment we are writting to.
64   MCDataFragment *ShndxF;
65
66   // The numbel of symbols written so far.
67   unsigned NumWritten;
68
69   void createSymtabShndx();
70
71   template <typename T> void write(MCDataFragment &F, T Value);
72
73 public:
74   SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter, bool Is64Bit,
75                     SectionIndexMapTy &SectionIndexMap,
76                     MCDataFragment *SymtabF);
77
78   void writeSymbol(uint32_t name, uint8_t info, uint64_t value, uint64_t size,
79                    uint8_t other, uint32_t shndx, bool Reserved);
80 };
81
82 class ELFObjectWriter : public MCObjectWriter {
83   FragmentWriter FWriter;
84
85   protected:
86
87     static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
88     static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
89     static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
90     static bool isInSymtab(const MCAsmLayout &Layout, const MCSymbolData &Data,
91                            bool Used, bool Renamed);
92     static bool isLocal(const MCSymbolData &Data, bool isUsedInReloc);
93     static bool IsELFMetaDataSection(const MCSectionData &SD);
94     static uint64_t DataSectionSize(const MCSectionData &SD);
95     static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
96                                           const MCSectionData &SD);
97
98     void writeDataSectionData(MCAssembler &Asm, const MCAsmLayout &Layout,
99                               const MCSectionData &SD);
100
101     /// Helper struct for containing some precomputed information on symbols.
102     struct ELFSymbolData {
103       MCSymbolData *SymbolData;
104       uint64_t StringIndex;
105       uint32_t SectionIndex;
106       StringRef Name;
107
108       // Support lexicographic sorting.
109       bool operator<(const ELFSymbolData &RHS) const {
110         unsigned LHSType = MCELF::GetType(*SymbolData);
111         unsigned RHSType = MCELF::GetType(*RHS.SymbolData);
112         if (LHSType == ELF::STT_SECTION && RHSType != ELF::STT_SECTION)
113           return false;
114         if (LHSType != ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
115           return true;
116         if (LHSType == ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
117           return SectionIndex < RHS.SectionIndex;
118         return Name < RHS.Name;
119       }
120     };
121
122     /// The target specific ELF writer instance.
123     std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
124
125     SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
126     SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
127     DenseMap<const MCSymbol *, const MCSymbol *> Renames;
128
129     llvm::DenseMap<const MCSectionData *, std::vector<ELFRelocationEntry>>
130     Relocations;
131     StringTableBuilder ShStrTabBuilder;
132
133     /// @}
134     /// @name Symbol Table Data
135     /// @{
136
137     StringTableBuilder StrTabBuilder;
138     std::vector<uint64_t> FileSymbolData;
139     std::vector<ELFSymbolData> LocalSymbolData;
140     std::vector<ELFSymbolData> ExternalSymbolData;
141     std::vector<ELFSymbolData> UndefinedSymbolData;
142
143     /// @}
144
145     bool NeedsGOT;
146
147     // This holds the symbol table index of the last local symbol.
148     unsigned LastLocalSymbolIndex;
149     // This holds the .strtab section index.
150     unsigned StringTableIndex;
151     // This holds the .symtab section index.
152     unsigned SymbolTableIndex;
153
154     unsigned ShstrtabIndex;
155
156
157     // TargetObjectWriter wrappers.
158     bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
159     bool hasRelocationAddend() const {
160       return TargetObjectWriter->hasRelocationAddend();
161     }
162     unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
163                           bool IsPCRel) const {
164       return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
165     }
166
167   public:
168     ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_pwrite_stream &OS,
169                     bool IsLittleEndian)
170         : MCObjectWriter(OS, IsLittleEndian), FWriter(IsLittleEndian),
171           TargetObjectWriter(MOTW), NeedsGOT(false) {}
172
173     void reset() override {
174       UsedInReloc.clear();
175       WeakrefUsedInReloc.clear();
176       Renames.clear();
177       Relocations.clear();
178       ShStrTabBuilder.clear();
179       StrTabBuilder.clear();
180       FileSymbolData.clear();
181       LocalSymbolData.clear();
182       ExternalSymbolData.clear();
183       UndefinedSymbolData.clear();
184       MCObjectWriter::reset();
185     }
186
187     ~ELFObjectWriter() override;
188
189     void WriteWord(uint64_t W) {
190       if (is64Bit())
191         Write64(W);
192       else
193         Write32(W);
194     }
195
196     template <typename T> void write(MCDataFragment &F, T Value) {
197       FWriter.write(F, Value);
198     }
199
200     void WriteHeader(const MCAssembler &Asm,
201                      unsigned NumberOfSections);
202
203     void WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
204                      const MCAsmLayout &Layout);
205
206     void WriteSymbolTable(MCDataFragment *SymtabF, MCAssembler &Asm,
207                           const MCAsmLayout &Layout,
208                           SectionIndexMapTy &SectionIndexMap);
209
210     bool shouldRelocateWithSymbol(const MCAssembler &Asm,
211                                   const MCSymbolRefExpr *RefA,
212                                   const MCSymbolData *SD, uint64_t C,
213                                   unsigned Type) const;
214
215     void RecordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
216                           const MCFragment *Fragment, const MCFixup &Fixup,
217                           MCValue Target, bool &IsPCRel,
218                           uint64_t &FixedValue) override;
219
220     uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
221                                          const MCSymbol *S);
222
223     // Map from a group section to the signature symbol
224     typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
225     // Map from a signature symbol to the group section
226     typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
227     // Map from a section to its offset
228     typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
229
230     /// Compute the symbol table data
231     ///
232     /// \param Asm - The assembler.
233     /// \param SectionIndexMap - Maps a section to its index.
234     /// \param RevGroupMap - Maps a signature symbol to the group section.
235     void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
236                             const SectionIndexMapTy &SectionIndexMap,
237                             const RevGroupMapTy &RevGroupMap);
238
239     void computeIndexMap(MCAssembler &Asm, SectionIndexMapTy &SectionIndexMap);
240
241     MCSectionData *createRelocationSection(MCAssembler &Asm,
242                                            const MCSectionData &SD);
243
244     void CompressDebugSections(MCAssembler &Asm, MCAsmLayout &Layout);
245
246     void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout);
247
248     void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
249                                 SectionIndexMapTy &SectionIndexMap);
250
251     // Create the sections that show up in the symbol table. Currently
252     // those are the .note.GNU-stack section and the group sections.
253     void createIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
254                                GroupMapTy &GroupMap, RevGroupMapTy &RevGroupMap,
255                                SectionIndexMapTy &SectionIndexMap);
256
257     void ExecutePostLayoutBinding(MCAssembler &Asm,
258                                   const MCAsmLayout &Layout) override;
259
260     void writeSectionHeader(ArrayRef<const MCSectionELF *> Sections,
261                             MCAssembler &Asm, const GroupMapTy &GroupMap,
262                             const MCAsmLayout &Layout,
263                             const SectionIndexMapTy &SectionIndexMap,
264                             const SectionOffsetMapTy &SectionOffsetMap);
265
266     void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
267                           uint64_t Address, uint64_t Offset,
268                           uint64_t Size, uint32_t Link, uint32_t Info,
269                           uint64_t Alignment, uint64_t EntrySize);
270
271     void WriteRelocationsFragment(const MCAssembler &Asm,
272                                   MCDataFragment *F,
273                                   const MCSectionData *SD);
274
275     bool
276     IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
277                                            const MCSymbolData &DataA,
278                                            const MCSymbolData *DataB,
279                                            const MCFragment &FB,
280                                            bool InSet,
281                                            bool IsPCRel) const override;
282
283     bool isWeak(const MCSymbolData &SD) const override;
284
285     void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
286     void writeSection(MCAssembler &Asm,
287                       const SectionIndexMapTy &SectionIndexMap,
288                       uint32_t GroupSymbolIndex,
289                       uint64_t Offset, uint64_t Size, uint64_t Alignment,
290                       const MCSectionELF &Section);
291   };
292 }
293
294 FragmentWriter::FragmentWriter(bool IsLittleEndian)
295     : IsLittleEndian(IsLittleEndian) {}
296
297 template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
298   if (IsLittleEndian)
299     Val = support::endian::byte_swap<T, support::little>(Val);
300   else
301     Val = support::endian::byte_swap<T, support::big>(Val);
302   const char *Start = (const char *)&Val;
303   F.getContents().append(Start, Start + sizeof(T));
304 }
305
306 void SymbolTableWriter::createSymtabShndx() {
307   if (ShndxF)
308     return;
309
310   MCContext &Ctx = Asm.getContext();
311   const MCSectionELF *SymtabShndxSection =
312       Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
313   MCSectionData *SymtabShndxSD =
314       &Asm.getOrCreateSectionData(*SymtabShndxSection);
315   SymtabShndxSD->setAlignment(4);
316   ShndxF = new MCDataFragment(SymtabShndxSD);
317   unsigned Index = SectionIndexMap.size() + 1;
318   SectionIndexMap[SymtabShndxSection] = Index;
319
320   for (unsigned I = 0; I < NumWritten; ++I)
321     write(*ShndxF, uint32_t(0));
322 }
323
324 template <typename T>
325 void SymbolTableWriter::write(MCDataFragment &F, T Value) {
326   FWriter.write(F, Value);
327 }
328
329 SymbolTableWriter::SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter,
330                                      bool Is64Bit,
331                                      SectionIndexMapTy &SectionIndexMap,
332                                      MCDataFragment *SymtabF)
333     : Asm(Asm), FWriter(FWriter), Is64Bit(Is64Bit),
334       SectionIndexMap(SectionIndexMap), SymtabF(SymtabF), ShndxF(nullptr),
335       NumWritten(0) {}
336
337 void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
338                                     uint64_t size, uint8_t other,
339                                     uint32_t shndx, bool Reserved) {
340   bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
341
342   if (LargeIndex)
343     createSymtabShndx();
344
345   if (ShndxF) {
346     if (LargeIndex)
347       write(*ShndxF, shndx);
348     else
349       write(*ShndxF, uint32_t(0));
350   }
351
352   uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
353
354   if (Is64Bit) {
355     write(*SymtabF, name);  // st_name
356     write(*SymtabF, info);  // st_info
357     write(*SymtabF, other); // st_other
358     write(*SymtabF, Index); // st_shndx
359     write(*SymtabF, value); // st_value
360     write(*SymtabF, size);  // st_size
361   } else {
362     write(*SymtabF, name);            // st_name
363     write(*SymtabF, uint32_t(value)); // st_value
364     write(*SymtabF, uint32_t(size));  // st_size
365     write(*SymtabF, info);            // st_info
366     write(*SymtabF, other);           // st_other
367     write(*SymtabF, Index);           // st_shndx
368   }
369
370   ++NumWritten;
371 }
372
373 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
374   const MCFixupKindInfo &FKI =
375     Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
376
377   return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
378 }
379
380 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
381   switch (Variant) {
382   default:
383     return false;
384   case MCSymbolRefExpr::VK_GOT:
385   case MCSymbolRefExpr::VK_PLT:
386   case MCSymbolRefExpr::VK_GOTPCREL:
387   case MCSymbolRefExpr::VK_GOTOFF:
388   case MCSymbolRefExpr::VK_TPOFF:
389   case MCSymbolRefExpr::VK_TLSGD:
390   case MCSymbolRefExpr::VK_GOTTPOFF:
391   case MCSymbolRefExpr::VK_INDNTPOFF:
392   case MCSymbolRefExpr::VK_NTPOFF:
393   case MCSymbolRefExpr::VK_GOTNTPOFF:
394   case MCSymbolRefExpr::VK_TLSLDM:
395   case MCSymbolRefExpr::VK_DTPOFF:
396   case MCSymbolRefExpr::VK_TLSLD:
397     return true;
398   }
399 }
400
401 ELFObjectWriter::~ELFObjectWriter()
402 {}
403
404 // Emit the ELF header.
405 void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
406                                   unsigned NumberOfSections) {
407   // ELF Header
408   // ----------
409   //
410   // Note
411   // ----
412   // emitWord method behaves differently for ELF32 and ELF64, writing
413   // 4 bytes in the former and 8 in the latter.
414
415   WriteBytes(ELF::ElfMagic); // e_ident[EI_MAG0] to e_ident[EI_MAG3]
416
417   Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
418
419   // e_ident[EI_DATA]
420   Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
421
422   Write8(ELF::EV_CURRENT);        // e_ident[EI_VERSION]
423   // e_ident[EI_OSABI]
424   Write8(TargetObjectWriter->getOSABI());
425   Write8(0);                  // e_ident[EI_ABIVERSION]
426
427   WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
428
429   Write16(ELF::ET_REL);             // e_type
430
431   Write16(TargetObjectWriter->getEMachine()); // e_machine = target
432
433   Write32(ELF::EV_CURRENT);         // e_version
434   WriteWord(0);                    // e_entry, no entry point in .o file
435   WriteWord(0);                    // e_phoff, no program header for .o
436   WriteWord(0);                     // e_shoff = sec hdr table off in bytes
437
438   // e_flags = whatever the target wants
439   Write32(Asm.getELFHeaderEFlags());
440
441   // e_ehsize = ELF header size
442   Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
443
444   Write16(0);                  // e_phentsize = prog header entry size
445   Write16(0);                  // e_phnum = # prog header entries = 0
446
447   // e_shentsize = Section header entry size
448   Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
449
450   // e_shnum     = # of section header ents
451   if (NumberOfSections >= ELF::SHN_LORESERVE)
452     Write16(ELF::SHN_UNDEF);
453   else
454     Write16(NumberOfSections);
455
456   // e_shstrndx  = Section # of '.shstrtab'
457   if (ShstrtabIndex >= ELF::SHN_LORESERVE)
458     Write16(ELF::SHN_XINDEX);
459   else
460     Write16(ShstrtabIndex);
461 }
462
463 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
464                                       const MCAsmLayout &Layout) {
465   if (Data.isCommon() && Data.isExternal())
466     return Data.getCommonAlignment();
467
468   uint64_t Res;
469   if (!Layout.getSymbolOffset(&Data, Res))
470     return 0;
471
472   if (Layout.getAssembler().isThumbFunc(&Data.getSymbol()))
473     Res |= 1;
474
475   return Res;
476 }
477
478 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
479                                                const MCAsmLayout &Layout) {
480   // The presence of symbol versions causes undefined symbols and
481   // versions declared with @@@ to be renamed.
482
483   for (MCSymbolData &OriginalData : Asm.symbols()) {
484     const MCSymbol &Alias = OriginalData.getSymbol();
485
486     // Not an alias.
487     if (!Alias.isVariable())
488       continue;
489     auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
490     if (!Ref)
491       continue;
492     const MCSymbol &Symbol = Ref->getSymbol();
493     MCSymbolData &SD = Asm.getSymbolData(Symbol);
494
495     StringRef AliasName = Alias.getName();
496     size_t Pos = AliasName.find('@');
497     if (Pos == StringRef::npos)
498       continue;
499
500     // Aliases defined with .symvar copy the binding from the symbol they alias.
501     // This is the first place we are able to copy this information.
502     OriginalData.setExternal(SD.isExternal());
503     MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
504
505     StringRef Rest = AliasName.substr(Pos);
506     if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
507       continue;
508
509     // FIXME: produce a better error message.
510     if (Symbol.isUndefined() && Rest.startswith("@@") &&
511         !Rest.startswith("@@@"))
512       report_fatal_error("A @@ version cannot be undefined");
513
514     Renames.insert(std::make_pair(&Symbol, &Alias));
515   }
516 }
517
518 static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
519   uint8_t Type = newType;
520
521   // Propagation rules:
522   // IFUNC > FUNC > OBJECT > NOTYPE
523   // TLS_OBJECT > OBJECT > NOTYPE
524   //
525   // dont let the new type degrade the old type
526   switch (origType) {
527   default:
528     break;
529   case ELF::STT_GNU_IFUNC:
530     if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
531         Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
532       Type = ELF::STT_GNU_IFUNC;
533     break;
534   case ELF::STT_FUNC:
535     if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
536         Type == ELF::STT_TLS)
537       Type = ELF::STT_FUNC;
538     break;
539   case ELF::STT_OBJECT:
540     if (Type == ELF::STT_NOTYPE)
541       Type = ELF::STT_OBJECT;
542     break;
543   case ELF::STT_TLS:
544     if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
545         Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
546       Type = ELF::STT_TLS;
547     break;
548   }
549
550   return Type;
551 }
552
553 void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
554                                   const MCAsmLayout &Layout) {
555   MCSymbolData &OrigData = *MSD.SymbolData;
556   assert((!OrigData.getFragment() ||
557           (&OrigData.getFragment()->getParent()->getSection() ==
558            &OrigData.getSymbol().getSection())) &&
559          "The symbol's section doesn't match the fragment's symbol");
560   const MCSymbol *Base = Layout.getBaseSymbol(OrigData.getSymbol());
561
562   // This has to be in sync with when computeSymbolTable uses SHN_ABS or
563   // SHN_COMMON.
564   bool IsReserved = !Base || OrigData.isCommon();
565
566   // Binding and Type share the same byte as upper and lower nibbles
567   uint8_t Binding = MCELF::GetBinding(OrigData);
568   uint8_t Type = MCELF::GetType(OrigData);
569   MCSymbolData *BaseSD = nullptr;
570   if (Base) {
571     BaseSD = &Layout.getAssembler().getSymbolData(*Base);
572     Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
573   }
574   uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
575
576   // Other and Visibility share the same byte with Visibility using the lower
577   // 2 bits
578   uint8_t Visibility = MCELF::GetVisibility(OrigData);
579   uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
580   Other |= Visibility;
581
582   uint64_t Value = SymbolValue(OrigData, Layout);
583   uint64_t Size = 0;
584
585   const MCExpr *ESize = OrigData.getSize();
586   if (!ESize && Base)
587     ESize = BaseSD->getSize();
588
589   if (ESize) {
590     int64_t Res;
591     if (!ESize->evaluateKnownAbsolute(Res, Layout))
592       report_fatal_error("Size expression must be absolute.");
593     Size = Res;
594   }
595
596   // Write out the symbol table entry
597   Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
598                      MSD.SectionIndex, IsReserved);
599 }
600
601 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
602                                        MCAssembler &Asm,
603                                        const MCAsmLayout &Layout,
604                                        SectionIndexMapTy &SectionIndexMap) {
605   // The string table must be emitted first because we need the index
606   // into the string table for all the symbol names.
607
608   // FIXME: Make sure the start of the symbol table is aligned.
609
610   SymbolTableWriter Writer(Asm, FWriter, is64Bit(), SectionIndexMap, SymtabF);
611
612   // The first entry is the undefined symbol entry.
613   Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
614
615   for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
616     Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
617                        ELF::STV_DEFAULT, ELF::SHN_ABS, true);
618   }
619
620   // Write the symbol table entries.
621   LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
622
623   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
624     ELFSymbolData &MSD = LocalSymbolData[i];
625     WriteSymbol(Writer, MSD, Layout);
626   }
627
628   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
629     ELFSymbolData &MSD = ExternalSymbolData[i];
630     MCSymbolData &Data = *MSD.SymbolData;
631     assert(((Data.getFlags() & ELF_STB_Global) ||
632             (Data.getFlags() & ELF_STB_Weak)) &&
633            "External symbol requires STB_GLOBAL or STB_WEAK flag");
634     WriteSymbol(Writer, MSD, Layout);
635     if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
636       LastLocalSymbolIndex++;
637   }
638
639   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
640     ELFSymbolData &MSD = UndefinedSymbolData[i];
641     MCSymbolData &Data = *MSD.SymbolData;
642     WriteSymbol(Writer, MSD, Layout);
643     if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
644       LastLocalSymbolIndex++;
645   }
646 }
647
648 // It is always valid to create a relocation with a symbol. It is preferable
649 // to use a relocation with a section if that is possible. Using the section
650 // allows us to omit some local symbols from the symbol table.
651 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
652                                                const MCSymbolRefExpr *RefA,
653                                                const MCSymbolData *SD,
654                                                uint64_t C,
655                                                unsigned Type) const {
656   // A PCRel relocation to an absolute value has no symbol (or section). We
657   // represent that with a relocation to a null section.
658   if (!RefA)
659     return false;
660
661   MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
662   switch (Kind) {
663   default:
664     break;
665   // The .odp creation emits a relocation against the symbol ".TOC." which
666   // create a R_PPC64_TOC relocation. However the relocation symbol name
667   // in final object creation should be NULL, since the symbol does not
668   // really exist, it is just the reference to TOC base for the current
669   // object file. Since the symbol is undefined, returning false results
670   // in a relocation with a null section which is the desired result.
671   case MCSymbolRefExpr::VK_PPC_TOCBASE:
672     return false;
673
674   // These VariantKind cause the relocation to refer to something other than
675   // the symbol itself, like a linker generated table. Since the address of
676   // symbol is not relevant, we cannot replace the symbol with the
677   // section and patch the difference in the addend.
678   case MCSymbolRefExpr::VK_GOT:
679   case MCSymbolRefExpr::VK_PLT:
680   case MCSymbolRefExpr::VK_GOTPCREL:
681   case MCSymbolRefExpr::VK_Mips_GOT:
682   case MCSymbolRefExpr::VK_PPC_GOT_LO:
683   case MCSymbolRefExpr::VK_PPC_GOT_HI:
684   case MCSymbolRefExpr::VK_PPC_GOT_HA:
685     return true;
686   }
687
688   // An undefined symbol is not in any section, so the relocation has to point
689   // to the symbol itself.
690   const MCSymbol &Sym = SD->getSymbol();
691   if (Sym.isUndefined())
692     return true;
693
694   unsigned Binding = MCELF::GetBinding(*SD);
695   switch(Binding) {
696   default:
697     llvm_unreachable("Invalid Binding");
698   case ELF::STB_LOCAL:
699     break;
700   case ELF::STB_WEAK:
701     // If the symbol is weak, it might be overridden by a symbol in another
702     // file. The relocation has to point to the symbol so that the linker
703     // can update it.
704     return true;
705   case ELF::STB_GLOBAL:
706     // Global ELF symbols can be preempted by the dynamic linker. The relocation
707     // has to point to the symbol for a reason analogous to the STB_WEAK case.
708     return true;
709   }
710
711   // If a relocation points to a mergeable section, we have to be careful.
712   // If the offset is zero, a relocation with the section will encode the
713   // same information. With a non-zero offset, the situation is different.
714   // For example, a relocation can point 42 bytes past the end of a string.
715   // If we change such a relocation to use the section, the linker would think
716   // that it pointed to another string and subtracting 42 at runtime will
717   // produce the wrong value.
718   auto &Sec = cast<MCSectionELF>(Sym.getSection());
719   unsigned Flags = Sec.getFlags();
720   if (Flags & ELF::SHF_MERGE) {
721     if (C != 0)
722       return true;
723
724     // It looks like gold has a bug (http://sourceware.org/PR16794) and can
725     // only handle section relocations to mergeable sections if using RELA.
726     if (!hasRelocationAddend())
727       return true;
728   }
729
730   // Most TLS relocations use a got, so they need the symbol. Even those that
731   // are just an offset (@tpoff), require a symbol in gold versions before
732   // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
733   // http://sourceware.org/PR16773.
734   if (Flags & ELF::SHF_TLS)
735     return true;
736
737   // If the symbol is a thumb function the final relocation must set the lowest
738   // bit. With a symbol that is done by just having the symbol have that bit
739   // set, so we would lose the bit if we relocated with the section.
740   // FIXME: We could use the section but add the bit to the relocation value.
741   if (Asm.isThumbFunc(&Sym))
742     return true;
743
744   if (TargetObjectWriter->needsRelocateWithSymbol(*SD, Type))
745     return true;
746   return false;
747 }
748
749 static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
750   const MCSymbol &Sym = Ref.getSymbol();
751
752   if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
753     return &Sym;
754
755   if (!Sym.isVariable())
756     return nullptr;
757
758   const MCExpr *Expr = Sym.getVariableValue();
759   const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
760   if (!Inner)
761     return nullptr;
762
763   if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
764     return &Inner->getSymbol();
765   return nullptr;
766 }
767
768 // True if the assembler knows nothing about the final value of the symbol.
769 // This doesn't cover the comdat issues, since in those cases the assembler
770 // can at least know that all symbols in the section will move together.
771 static bool isWeak(const MCSymbolData &D) {
772   if (MCELF::GetType(D) == ELF::STT_GNU_IFUNC)
773     return true;
774
775   switch (MCELF::GetBinding(D)) {
776   default:
777     llvm_unreachable("Unknown binding");
778   case ELF::STB_LOCAL:
779     return false;
780   case ELF::STB_GLOBAL:
781     return false;
782   case ELF::STB_WEAK:
783   case ELF::STB_GNU_UNIQUE:
784     return true;
785   }
786 }
787
788 void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
789                                        const MCAsmLayout &Layout,
790                                        const MCFragment *Fragment,
791                                        const MCFixup &Fixup, MCValue Target,
792                                        bool &IsPCRel, uint64_t &FixedValue) {
793   const MCSectionData *FixupSection = Fragment->getParent();
794   uint64_t C = Target.getConstant();
795   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
796
797   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
798     assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
799            "Should not have constructed this");
800
801     // Let A, B and C being the components of Target and R be the location of
802     // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
803     // If it is pcrel, we want to compute (A - B + C - R).
804
805     // In general, ELF has no relocations for -B. It can only represent (A + C)
806     // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
807     // replace B to implement it: (A - R - K + C)
808     if (IsPCRel)
809       Asm.getContext().FatalError(
810           Fixup.getLoc(),
811           "No relocation available to represent this relative expression");
812
813     const MCSymbol &SymB = RefB->getSymbol();
814
815     if (SymB.isUndefined())
816       Asm.getContext().FatalError(
817           Fixup.getLoc(),
818           Twine("symbol '") + SymB.getName() +
819               "' can not be undefined in a subtraction expression");
820
821     assert(!SymB.isAbsolute() && "Should have been folded");
822     const MCSection &SecB = SymB.getSection();
823     if (&SecB != &FixupSection->getSection())
824       Asm.getContext().FatalError(
825           Fixup.getLoc(), "Cannot represent a difference across sections");
826
827     const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
828     if (::isWeak(SymBD))
829       Asm.getContext().FatalError(
830           Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
831
832     uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
833     uint64_t K = SymBOffset - FixupOffset;
834     IsPCRel = true;
835     C -= K;
836   }
837
838   // We either rejected the fixup or folded B into C at this point.
839   const MCSymbolRefExpr *RefA = Target.getSymA();
840   const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
841   const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
842
843   unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
844   bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymAD, C, Type);
845   if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
846     C += Layout.getSymbolOffset(SymAD);
847
848   uint64_t Addend = 0;
849   if (hasRelocationAddend()) {
850     Addend = C;
851     C = 0;
852   }
853
854   FixedValue = C;
855
856   // FIXME: What is this!?!?
857   MCSymbolRefExpr::VariantKind Modifier =
858       RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
859   if (RelocNeedsGOT(Modifier))
860     NeedsGOT = true;
861
862   if (!RelocateWithSymbol) {
863     const MCSection *SecA =
864         (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
865     auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
866     MCSymbol *SectionSymbol =
867         ELFSec ? Asm.getContext().getOrCreateSectionSymbol(*ELFSec)
868                : nullptr;
869     ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
870     Relocations[FixupSection].push_back(Rec);
871     return;
872   }
873
874   if (SymA) {
875     if (const MCSymbol *R = Renames.lookup(SymA))
876       SymA = R;
877
878     if (const MCSymbol *WeakRef = getWeakRef(*RefA))
879       WeakrefUsedInReloc.insert(WeakRef);
880     else
881       UsedInReloc.insert(SymA);
882   }
883   ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
884   Relocations[FixupSection].push_back(Rec);
885   return;
886 }
887
888
889 uint64_t
890 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
891                                              const MCSymbol *S) {
892   const MCSymbolData &SD = Asm.getSymbolData(*S);
893   return SD.getIndex();
894 }
895
896 bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
897                                  const MCSymbolData &Data, bool Used,
898                                  bool Renamed) {
899   const MCSymbol &Symbol = Data.getSymbol();
900   if (Symbol.isVariable()) {
901     const MCExpr *Expr = Symbol.getVariableValue();
902     if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
903       if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
904         return false;
905     }
906   }
907
908   if (Used)
909     return true;
910
911   if (Renamed)
912     return false;
913
914   if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
915     return true;
916
917   if (Symbol.isVariable()) {
918     const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
919     if (Base && Base->isUndefined())
920       return false;
921   }
922
923   bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
924   if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
925     return false;
926
927   if (Symbol.isTemporary())
928     return false;
929
930   return true;
931 }
932
933 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isUsedInReloc) {
934   if (Data.isExternal())
935     return false;
936
937   const MCSymbol &Symbol = Data.getSymbol();
938   if (Symbol.isDefined())
939     return true;
940
941   if (isUsedInReloc)
942     return false;
943
944   return true;
945 }
946
947 void ELFObjectWriter::computeIndexMap(MCAssembler &Asm,
948                                       SectionIndexMapTy &SectionIndexMap) {
949   unsigned Index = 1;
950   for (MCAssembler::iterator it = Asm.begin(),
951          ie = Asm.end(); it != ie; ++it) {
952     const MCSectionELF &Section =
953       static_cast<const MCSectionELF &>(it->getSection());
954     if (Section.getType() != ELF::SHT_GROUP)
955       continue;
956     SectionIndexMap[&Section] = Index++;
957   }
958
959   std::vector<const MCSectionELF *> RelSections;
960
961   for (MCAssembler::iterator it = Asm.begin(),
962          ie = Asm.end(); it != ie; ++it) {
963     const MCSectionData &SD = *it;
964     const MCSectionELF &Section =
965       static_cast<const MCSectionELF &>(SD.getSection());
966     if (Section.getType() == ELF::SHT_GROUP ||
967         Section.getType() == ELF::SHT_REL ||
968         Section.getType() == ELF::SHT_RELA)
969       continue;
970     SectionIndexMap[&Section] = Index++;
971     if (MCSectionData *RelSD = createRelocationSection(Asm, SD)) {
972       const MCSectionELF *RelSection =
973           static_cast<const MCSectionELF *>(&RelSD->getSection());
974       RelSections.push_back(RelSection);
975     }
976   }
977
978   // Put relocation sections close together. The linker reads them
979   // first, so this improves cache locality.
980   for (const MCSectionELF * Sec: RelSections)
981     SectionIndexMap[Sec] = Index++;
982 }
983
984 void ELFObjectWriter::computeSymbolTable(
985     MCAssembler &Asm, const MCAsmLayout &Layout,
986     const SectionIndexMapTy &SectionIndexMap,
987     const RevGroupMapTy &RevGroupMap) {
988   // FIXME: Is this the correct place to do this?
989   // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
990   if (NeedsGOT) {
991     StringRef Name = "_GLOBAL_OFFSET_TABLE_";
992     MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
993     MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
994     Data.setExternal(true);
995     MCELF::SetBinding(Data, ELF::STB_GLOBAL);
996   }
997
998   // Add the data for the symbols.
999   for (MCSymbolData &SD : Asm.symbols()) {
1000     const MCSymbol &Symbol = SD.getSymbol();
1001
1002     bool Used = UsedInReloc.count(&Symbol);
1003     bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
1004     bool isSignature = RevGroupMap.count(&Symbol);
1005
1006     if (!isInSymtab(Layout, SD,
1007                     Used || WeakrefUsed || isSignature,
1008                     Renames.count(&Symbol)))
1009       continue;
1010
1011     ELFSymbolData MSD;
1012     MSD.SymbolData = &SD;
1013     const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
1014
1015     // Undefined symbols are global, but this is the first place we
1016     // are able to set it.
1017     bool Local = isLocal(SD, Used);
1018     if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
1019       assert(BaseSymbol);
1020       MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
1021       MCELF::SetBinding(SD, ELF::STB_GLOBAL);
1022       MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
1023     }
1024
1025     if (!BaseSymbol) {
1026       MSD.SectionIndex = ELF::SHN_ABS;
1027     } else if (SD.isCommon()) {
1028       assert(!Local);
1029       MSD.SectionIndex = ELF::SHN_COMMON;
1030     } else if (BaseSymbol->isUndefined()) {
1031       if (isSignature && !Used)
1032         MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap.lookup(&Symbol));
1033       else
1034         MSD.SectionIndex = ELF::SHN_UNDEF;
1035       if (!Used && WeakrefUsed)
1036         MCELF::SetBinding(SD, ELF::STB_WEAK);
1037     } else {
1038       const MCSectionELF &Section =
1039         static_cast<const MCSectionELF&>(BaseSymbol->getSection());
1040       MSD.SectionIndex = SectionIndexMap.lookup(&Section);
1041       assert(MSD.SectionIndex && "Invalid section index!");
1042     }
1043
1044     // The @@@ in symbol version is replaced with @ in undefined symbols and @@
1045     // in defined ones.
1046     //
1047     // FIXME: All name handling should be done before we get to the writer,
1048     // including dealing with GNU-style version suffixes.  Fixing this isn't
1049     // trivial.
1050     //
1051     // We thus have to be careful to not perform the symbol version replacement
1052     // blindly:
1053     //
1054     // The ELF format is used on Windows by the MCJIT engine.  Thus, on
1055     // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
1056     // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
1057     // C++ name mangling can legally have "@@@" as a sub-string. In that case,
1058     // the EFLObjectWriter should not interpret the "@@@" sub-string as
1059     // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
1060     // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
1061     // "__imp_?" or "__imp_@?".
1062     //
1063     // It would have been interesting to perform the MS mangling prefix check
1064     // only when the target triple is of the form *-pc-windows-elf. But, it
1065     // seems that this information is not easily accessible from the
1066     // ELFObjectWriter.
1067     StringRef Name = Symbol.getName();
1068     if (!Name.startswith("?") && !Name.startswith("@?") &&
1069         !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
1070       // This symbol isn't following the MSVC C++ name mangling convention. We
1071       // can thus safely interpret the @@@ in symbol names as specifying symbol
1072       // versioning.
1073       SmallString<32> Buf;
1074       size_t Pos = Name.find("@@@");
1075       if (Pos != StringRef::npos) {
1076         Buf += Name.substr(0, Pos);
1077         unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1078         Buf += Name.substr(Pos + Skip);
1079         Name = Buf;
1080       }
1081     }
1082
1083     // Sections have their own string table
1084     if (MCELF::GetType(SD) != ELF::STT_SECTION)
1085       MSD.Name = StrTabBuilder.add(Name);
1086
1087     if (MSD.SectionIndex == ELF::SHN_UNDEF)
1088       UndefinedSymbolData.push_back(MSD);
1089     else if (Local)
1090       LocalSymbolData.push_back(MSD);
1091     else
1092       ExternalSymbolData.push_back(MSD);
1093   }
1094
1095   for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1096     StrTabBuilder.add(*i);
1097
1098   StrTabBuilder.finalize(StringTableBuilder::ELF);
1099
1100   for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1101     FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1102
1103   for (ELFSymbolData &MSD : LocalSymbolData)
1104     MSD.StringIndex = MCELF::GetType(*MSD.SymbolData) == ELF::STT_SECTION
1105                           ? 0
1106                           : StrTabBuilder.getOffset(MSD.Name);
1107   for (ELFSymbolData &MSD : ExternalSymbolData)
1108     MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1109   for (ELFSymbolData& MSD : UndefinedSymbolData)
1110     MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1111
1112   // Symbols are required to be in lexicographic order.
1113   array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1114   array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1115   array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1116
1117   // Set the symbol indices. Local symbols must come before all other
1118   // symbols with non-local bindings.
1119   unsigned Index = FileSymbolData.size() + 1;
1120   for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1121     LocalSymbolData[i].SymbolData->setIndex(Index++);
1122
1123   for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1124     ExternalSymbolData[i].SymbolData->setIndex(Index++);
1125   for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1126     UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1127 }
1128
1129 MCSectionData *
1130 ELFObjectWriter::createRelocationSection(MCAssembler &Asm,
1131                                          const MCSectionData &SD) {
1132   if (Relocations[&SD].empty())
1133     return nullptr;
1134
1135   MCContext &Ctx = Asm.getContext();
1136   const MCSectionELF &Section =
1137       static_cast<const MCSectionELF &>(SD.getSection());
1138
1139   const StringRef SectionName = Section.getSectionName();
1140   std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1141   RelaSectionName += SectionName;
1142
1143   unsigned EntrySize;
1144   if (hasRelocationAddend())
1145     EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1146   else
1147     EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1148
1149   unsigned Flags = 0;
1150   if (Section.getFlags() & ELF::SHF_GROUP)
1151     Flags = ELF::SHF_GROUP;
1152
1153   const MCSectionELF *RelaSection = Ctx.createELFRelSection(
1154       RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
1155       Flags, EntrySize, Section.getGroup(), &Section);
1156   return &Asm.getOrCreateSectionData(*RelaSection);
1157 }
1158
1159 static SmallVector<char, 128>
1160 getUncompressedData(MCAsmLayout &Layout,
1161                     MCSectionData::FragmentListType &Fragments) {
1162   SmallVector<char, 128> UncompressedData;
1163   for (const MCFragment &F : Fragments) {
1164     const SmallVectorImpl<char> *Contents;
1165     switch (F.getKind()) {
1166     case MCFragment::FT_Data:
1167       Contents = &cast<MCDataFragment>(F).getContents();
1168       break;
1169     case MCFragment::FT_Dwarf:
1170       Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1171       break;
1172     case MCFragment::FT_DwarfFrame:
1173       Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1174       break;
1175     default:
1176       llvm_unreachable(
1177           "Not expecting any other fragment types in a debug_* section");
1178     }
1179     UncompressedData.append(Contents->begin(), Contents->end());
1180   }
1181   return UncompressedData;
1182 }
1183
1184 // Include the debug info compression header:
1185 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1186 // useful for consumers to preallocate a buffer to decompress into.
1187 static bool
1188 prependCompressionHeader(uint64_t Size,
1189                          SmallVectorImpl<char> &CompressedContents) {
1190   const StringRef Magic = "ZLIB";
1191   if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1192     return false;
1193   if (sys::IsLittleEndianHost)
1194     sys::swapByteOrder(Size);
1195   CompressedContents.insert(CompressedContents.begin(),
1196                             Magic.size() + sizeof(Size), 0);
1197   std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1198   std::copy(reinterpret_cast<char *>(&Size),
1199             reinterpret_cast<char *>(&Size + 1),
1200             CompressedContents.begin() + Magic.size());
1201   return true;
1202 }
1203
1204 // Return a single fragment containing the compressed contents of the whole
1205 // section. Null if the section was not compressed for any reason.
1206 static std::unique_ptr<MCDataFragment>
1207 getCompressedFragment(MCAsmLayout &Layout,
1208                       MCSectionData::FragmentListType &Fragments) {
1209   std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1210
1211   // Gather the uncompressed data from all the fragments, recording the
1212   // alignment fragment, if seen, and any fixups.
1213   SmallVector<char, 128> UncompressedData =
1214       getUncompressedData(Layout, Fragments);
1215
1216   SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1217
1218   zlib::Status Success = zlib::compress(
1219       StringRef(UncompressedData.data(), UncompressedData.size()),
1220       CompressedContents);
1221   if (Success != zlib::StatusOK)
1222     return nullptr;
1223
1224   if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1225     return nullptr;
1226
1227   return CompressedFragment;
1228 }
1229
1230 typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1231 DefiningSymbolMap;
1232
1233 static void UpdateSymbols(const MCAsmLayout &Layout,
1234                           const std::vector<MCSymbolData *> &Symbols,
1235                           MCFragment &NewFragment) {
1236   for (MCSymbolData *Sym : Symbols) {
1237     Sym->setOffset(Sym->getOffset() +
1238                    Layout.getFragmentOffset(Sym->getFragment()));
1239     Sym->setFragment(&NewFragment);
1240   }
1241 }
1242
1243 static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
1244                                  const DefiningSymbolMap &DefiningSymbols,
1245                                  const MCSectionELF &Section,
1246                                  MCSectionData &SD) {
1247   StringRef SectionName = Section.getSectionName();
1248   MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1249
1250   std::unique_ptr<MCDataFragment> CompressedFragment =
1251       getCompressedFragment(Layout, Fragments);
1252
1253   // Leave the section as-is if the fragments could not be compressed.
1254   if (!CompressedFragment)
1255     return;
1256
1257   // Update the fragment+offsets of any symbols referring to fragments in this
1258   // section to refer to the new fragment.
1259   auto I = DefiningSymbols.find(&SD);
1260   if (I != DefiningSymbols.end())
1261     UpdateSymbols(Layout, I->second, *CompressedFragment);
1262
1263   // Invalidate the layout for the whole section since it will have new and
1264   // different fragments now.
1265   Layout.invalidateFragmentsFrom(&Fragments.front());
1266   Fragments.clear();
1267
1268   // Complete the initialization of the new fragment
1269   CompressedFragment->setParent(&SD);
1270   CompressedFragment->setLayoutOrder(0);
1271   Fragments.push_back(CompressedFragment.release());
1272
1273   // Rename from .debug_* to .zdebug_*
1274   Asm.getContext().renameELFSection(&Section,
1275                                     (".z" + SectionName.drop_front(1)).str());
1276 }
1277
1278 void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1279                                             MCAsmLayout &Layout) {
1280   if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1281     return;
1282
1283   DefiningSymbolMap DefiningSymbols;
1284
1285   for (MCSymbolData &SD : Asm.symbols())
1286     if (MCFragment *F = SD.getFragment())
1287       DefiningSymbols[F->getParent()].push_back(&SD);
1288
1289   for (MCSectionData &SD : Asm) {
1290     const MCSectionELF &Section =
1291         static_cast<const MCSectionELF &>(SD.getSection());
1292     StringRef SectionName = Section.getSectionName();
1293
1294     // Compressing debug_frame requires handling alignment fragments which is
1295     // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1296     // for writing to arbitrary buffers) for little benefit.
1297     if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1298       continue;
1299
1300     CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
1301   }
1302 }
1303
1304 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
1305   for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1306     MCSectionData &RelSD = *it;
1307     const MCSectionELF &RelSection =
1308         static_cast<const MCSectionELF &>(RelSD.getSection());
1309
1310     unsigned Type = RelSection.getType();
1311     if (Type != ELF::SHT_REL && Type != ELF::SHT_RELA)
1312       continue;
1313
1314     const MCSectionELF *Section = RelSection.getAssociatedSection();
1315     MCSectionData &SD = Asm.getOrCreateSectionData(*Section);
1316     RelSD.setAlignment(is64Bit() ? 8 : 4);
1317
1318     MCDataFragment *F = new MCDataFragment(&RelSD);
1319     WriteRelocationsFragment(Asm, F, &SD);
1320   }
1321 }
1322
1323 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1324                                        uint64_t Flags, uint64_t Address,
1325                                        uint64_t Offset, uint64_t Size,
1326                                        uint32_t Link, uint32_t Info,
1327                                        uint64_t Alignment,
1328                                        uint64_t EntrySize) {
1329   Write32(Name);        // sh_name: index into string table
1330   Write32(Type);        // sh_type
1331   WriteWord(Flags);     // sh_flags
1332   WriteWord(Address);   // sh_addr
1333   WriteWord(Offset);    // sh_offset
1334   WriteWord(Size);      // sh_size
1335   Write32(Link);        // sh_link
1336   Write32(Info);        // sh_info
1337   WriteWord(Alignment); // sh_addralign
1338   WriteWord(EntrySize); // sh_entsize
1339 }
1340
1341 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1342                                                MCDataFragment *F,
1343                                                const MCSectionData *SD) {
1344   std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1345
1346   // Sort the relocation entries. Most targets just sort by Offset, but some
1347   // (e.g., MIPS) have additional constraints.
1348   TargetObjectWriter->sortRelocs(Asm, Relocs);
1349
1350   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1351     const ELFRelocationEntry &Entry = Relocs[e - i - 1];
1352     unsigned Index =
1353         Entry.Symbol ? getSymbolIndexInSymbolTable(Asm, Entry.Symbol) : 0;
1354
1355     if (is64Bit()) {
1356       write(*F, Entry.Offset);
1357       if (TargetObjectWriter->isN64()) {
1358         write(*F, uint32_t(Index));
1359
1360         write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1361         write(*F, TargetObjectWriter->getRType3(Entry.Type));
1362         write(*F, TargetObjectWriter->getRType2(Entry.Type));
1363         write(*F, TargetObjectWriter->getRType(Entry.Type));
1364       } else {
1365         struct ELF::Elf64_Rela ERE64;
1366         ERE64.setSymbolAndType(Index, Entry.Type);
1367         write(*F, ERE64.r_info);
1368       }
1369       if (hasRelocationAddend())
1370         write(*F, Entry.Addend);
1371     } else {
1372       write(*F, uint32_t(Entry.Offset));
1373
1374       struct ELF::Elf32_Rela ERE32;
1375       ERE32.setSymbolAndType(Index, Entry.Type);
1376       write(*F, ERE32.r_info);
1377
1378       if (hasRelocationAddend())
1379         write(*F, uint32_t(Entry.Addend));
1380     }
1381   }
1382 }
1383
1384 void ELFObjectWriter::CreateMetadataSections(
1385     MCAssembler &Asm, MCAsmLayout &Layout, SectionIndexMapTy &SectionIndexMap) {
1386   MCContext &Ctx = Asm.getContext();
1387   MCDataFragment *F;
1388
1389   unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1390
1391   // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1392   const MCSectionELF *ShstrtabSection =
1393       Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0);
1394   MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1395   ShstrtabSD.setAlignment(1);
1396   ShstrtabIndex = SectionIndexMap.size() + 1;
1397   SectionIndexMap[ShstrtabSection] = ShstrtabIndex;
1398
1399   const MCSectionELF *SymtabSection =
1400     Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1401                       EntrySize, "");
1402   MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1403   SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1404   SymbolTableIndex = SectionIndexMap.size() + 1;
1405   SectionIndexMap[SymtabSection] = SymbolTableIndex;
1406
1407   const MCSectionELF *StrtabSection;
1408   StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1409   MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1410   StrtabSD.setAlignment(1);
1411   StringTableIndex = SectionIndexMap.size() + 1;
1412   SectionIndexMap[StrtabSection] = StringTableIndex;
1413
1414   // Symbol table
1415   F = new MCDataFragment(&SymtabSD);
1416   WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
1417
1418   F = new MCDataFragment(&StrtabSD);
1419   F->getContents().append(StrTabBuilder.data().begin(),
1420                           StrTabBuilder.data().end());
1421
1422   F = new MCDataFragment(&ShstrtabSD);
1423
1424   // Section header string table.
1425   for (auto it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1426     const MCSectionELF &Section =
1427       static_cast<const MCSectionELF&>(it->getSection());
1428     ShStrTabBuilder.add(Section.getSectionName());
1429   }
1430   ShStrTabBuilder.finalize(StringTableBuilder::ELF);
1431   F->getContents().append(ShStrTabBuilder.data().begin(),
1432                           ShStrTabBuilder.data().end());
1433 }
1434
1435 void ELFObjectWriter::createIndexedSections(
1436     MCAssembler &Asm, MCAsmLayout &Layout, GroupMapTy &GroupMap,
1437     RevGroupMapTy &RevGroupMap, SectionIndexMapTy &SectionIndexMap) {
1438   MCContext &Ctx = Asm.getContext();
1439
1440   // Build the groups
1441   for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1442        it != ie; ++it) {
1443     const MCSectionELF &Section =
1444       static_cast<const MCSectionELF&>(it->getSection());
1445     if (!(Section.getFlags() & ELF::SHF_GROUP))
1446       continue;
1447
1448     const MCSymbol *SignatureSymbol = Section.getGroup();
1449     Asm.getOrCreateSymbolData(*SignatureSymbol);
1450     const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1451     if (!Group) {
1452       Group = Ctx.CreateELFGroupSection();
1453       MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1454       Data.setAlignment(4);
1455       MCDataFragment *F = new MCDataFragment(&Data);
1456       write(*F, uint32_t(ELF::GRP_COMDAT));
1457     }
1458     GroupMap[Group] = SignatureSymbol;
1459   }
1460
1461   computeIndexMap(Asm, SectionIndexMap);
1462
1463   // Add sections to the groups
1464   for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1465        it != ie; ++it) {
1466     const MCSectionELF &Section =
1467       static_cast<const MCSectionELF&>(it->getSection());
1468     if (!(Section.getFlags() & ELF::SHF_GROUP))
1469       continue;
1470     const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1471     MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1472     // FIXME: we could use the previous fragment
1473     MCDataFragment *F = new MCDataFragment(&Data);
1474     uint32_t Index = SectionIndexMap.lookup(&Section);
1475     write(*F, Index);
1476   }
1477 }
1478
1479 void ELFObjectWriter::writeSection(MCAssembler &Asm,
1480                                    const SectionIndexMapTy &SectionIndexMap,
1481                                    uint32_t GroupSymbolIndex,
1482                                    uint64_t Offset, uint64_t Size,
1483                                    uint64_t Alignment,
1484                                    const MCSectionELF &Section) {
1485   uint64_t sh_link = 0;
1486   uint64_t sh_info = 0;
1487
1488   switch(Section.getType()) {
1489   default:
1490     // Nothing to do.
1491     break;
1492
1493   case ELF::SHT_DYNAMIC:
1494     sh_link = ShStrTabBuilder.getOffset(Section.getSectionName());
1495     break;
1496
1497   case ELF::SHT_REL:
1498   case ELF::SHT_RELA: {
1499     sh_link = SymbolTableIndex;
1500     assert(sh_link && ".symtab not found");
1501     const MCSectionELF *InfoSection = Section.getAssociatedSection();
1502     sh_info = SectionIndexMap.lookup(InfoSection);
1503     break;
1504   }
1505
1506   case ELF::SHT_SYMTAB:
1507   case ELF::SHT_DYNSYM:
1508     sh_link = StringTableIndex;
1509     sh_info = LastLocalSymbolIndex;
1510     break;
1511
1512   case ELF::SHT_SYMTAB_SHNDX:
1513     sh_link = SymbolTableIndex;
1514     break;
1515
1516   case ELF::SHT_GROUP:
1517     sh_link = SymbolTableIndex;
1518     sh_info = GroupSymbolIndex;
1519     break;
1520   }
1521
1522   if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1523       Section.getType() == ELF::SHT_ARM_EXIDX)
1524     sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
1525
1526   WriteSecHdrEntry(ShStrTabBuilder.getOffset(Section.getSectionName()),
1527                    Section.getType(),
1528                    Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1529                    Alignment, Section.getEntrySize());
1530 }
1531
1532 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1533   return SD.getOrdinal() == ~UINT32_C(0) &&
1534     !SD.getSection().isVirtualSection();
1535 }
1536
1537 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1538   uint64_t Ret = 0;
1539   for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1540        ++i) {
1541     const MCFragment &F = *i;
1542     assert(F.getKind() == MCFragment::FT_Data);
1543     Ret += cast<MCDataFragment>(F).getContents().size();
1544   }
1545   return Ret;
1546 }
1547
1548 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1549                                                 const MCSectionData &SD) {
1550   if (IsELFMetaDataSection(SD))
1551     return DataSectionSize(SD);
1552   return Layout.getSectionAddressSize(&SD);
1553 }
1554
1555 void ELFObjectWriter::writeDataSectionData(MCAssembler &Asm,
1556                                            const MCAsmLayout &Layout,
1557                                            const MCSectionData &SD) {
1558   if (IsELFMetaDataSection(SD)) {
1559     for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1560          ++i) {
1561       const MCFragment &F = *i;
1562       assert(F.getKind() == MCFragment::FT_Data);
1563       WriteBytes(cast<MCDataFragment>(F).getContents());
1564     }
1565   } else {
1566     Asm.writeSectionData(&SD, Layout);
1567   }
1568 }
1569
1570 void ELFObjectWriter::writeSectionHeader(
1571     ArrayRef<const MCSectionELF *> Sections, MCAssembler &Asm,
1572     const GroupMapTy &GroupMap, const MCAsmLayout &Layout,
1573     const SectionIndexMapTy &SectionIndexMap,
1574     const SectionOffsetMapTy &SectionOffsetMap) {
1575   const unsigned NumSections = Asm.size();
1576
1577   // Null section first.
1578   uint64_t FirstSectionSize =
1579       (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
1580   uint32_t FirstSectionLink =
1581     ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1582   WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1583
1584   for (unsigned i = 0; i < NumSections; ++i) {
1585     const MCSectionELF &Section = *Sections[i];
1586     const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1587     uint32_t GroupSymbolIndex;
1588     if (Section.getType() != ELF::SHT_GROUP)
1589       GroupSymbolIndex = 0;
1590     else
1591       GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1592                                                      GroupMap.lookup(&Section));
1593
1594     uint64_t Size = GetSectionAddressSize(Layout, SD);
1595
1596     writeSection(Asm, SectionIndexMap, GroupSymbolIndex,
1597                  SectionOffsetMap.lookup(&Section), Size, SD.getAlignment(),
1598                  Section);
1599   }
1600 }
1601
1602 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1603                                   const MCAsmLayout &Layout) {
1604   GroupMapTy GroupMap;
1605   RevGroupMapTy RevGroupMap;
1606   SectionIndexMapTy SectionIndexMap;
1607
1608   CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
1609   createIndexedSections(Asm, const_cast<MCAsmLayout &>(Layout), GroupMap,
1610                         RevGroupMap, SectionIndexMap);
1611
1612   // Compute symbol table information.
1613   computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap);
1614
1615   WriteRelocations(Asm, const_cast<MCAsmLayout &>(Layout));
1616
1617   CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1618                          const_cast<MCAsmLayout&>(Layout),
1619                          SectionIndexMap);
1620
1621   unsigned NumSections = Asm.size();
1622   std::vector<const MCSectionELF*> Sections;
1623   Sections.resize(NumSections);
1624
1625   for (auto &Pair : SectionIndexMap)
1626     Sections[Pair.second - 1] = Pair.first;
1627
1628   SectionOffsetMapTy SectionOffsetMap;
1629
1630   // Write out the ELF header ...
1631   WriteHeader(Asm, NumSections + 1);
1632
1633   // ... then the sections ...
1634   for (unsigned i = 0; i < NumSections; ++i) {
1635     const MCSectionELF &Section = *Sections[i];
1636     const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1637     uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1638     WriteZeros(Padding);
1639
1640     // Remember the offset into the file for this section.
1641     SectionOffsetMap[&Section] = OS.tell();
1642
1643     writeDataSectionData(Asm, Layout, SD);
1644   }
1645
1646   uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1647   uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1648   WriteZeros(Padding);
1649
1650   const unsigned SectionHeaderOffset = OS.tell();
1651
1652   // ... then the section header table ...
1653   writeSectionHeader(Sections, Asm, GroupMap, Layout, SectionIndexMap,
1654                      SectionOffsetMap);
1655
1656   if (is64Bit()) {
1657     uint64_t Val = SectionHeaderOffset;
1658     if (sys::IsLittleEndianHost != IsLittleEndian)
1659       sys::swapByteOrder(Val);
1660     OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1661               offsetof(ELF::Elf64_Ehdr, e_shoff));
1662   } else {
1663     uint32_t Val = SectionHeaderOffset;
1664     if (sys::IsLittleEndianHost != IsLittleEndian)
1665       sys::swapByteOrder(Val);
1666     OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1667               offsetof(ELF::Elf32_Ehdr, e_shoff));
1668   }
1669 }
1670
1671 bool ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1672     const MCAssembler &Asm, const MCSymbolData &DataA,
1673     const MCSymbolData *DataB, const MCFragment &FB, bool InSet,
1674     bool IsPCRel) const {
1675   if (!InSet && (::isWeak(DataA) || (DataB && ::isWeak(*DataB))))
1676     return false;
1677   return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1678       Asm, DataA, DataB, FB, InSet, IsPCRel);
1679 }
1680
1681 bool ELFObjectWriter::isWeak(const MCSymbolData &SD) const {
1682   if (::isWeak(SD))
1683     return true;
1684
1685   const MCSymbol &Sym = SD.getSymbol();
1686   if (!Sym.isInSection())
1687     return false;
1688
1689   const auto &Sec = cast<MCSectionELF>(Sym.getSection());
1690   if (!Sec.getGroup())
1691     return false;
1692
1693   // It is invalid to replace a reference to a global in a comdat
1694   // with a reference to a local since out of comdat references
1695   // to a local are forbidden.
1696   // We could try to return false for more cases, like the reference
1697   // being in the same comdat or Sym being an alias to another global,
1698   // but it is not clear if it is worth the effort.
1699   return true;
1700
1701 }
1702
1703 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1704                                             raw_pwrite_stream &OS,
1705                                             bool IsLittleEndian) {
1706   return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
1707 }