1 //===- SymbolTable.cpp ----------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "SymbolTable.h"
10 #include "Config.h"
11 #include "Driver.h"
12 #include "LTO.h"
13 #include "PDB.h"
14 #include "Symbols.h"
15 #include "lld/Common/ErrorHandler.h"
16 #include "lld/Common/Memory.h"
17 #include "lld/Common/Timer.h"
18 #include "llvm/DebugInfo/Symbolize/Symbolize.h"
19 #include "llvm/IR/LLVMContext.h"
20 #include "llvm/Object/WindowsMachineFlag.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include <utility>
24 
25 using namespace llvm;
26 
27 namespace lld {
28 namespace coff {
29 
30 static Timer ltoTimer("LTO", Timer::root());
31 
32 SymbolTable *symtab;
33 
34 void SymbolTable::addFile(InputFile *file) {
35   log("Reading " + toString(file));
36   file->parse();
37 
38   MachineTypes mt = file->getMachineType();
39   if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) {
40     config->machine = mt;
41   } else if (mt != IMAGE_FILE_MACHINE_UNKNOWN && config->machine != mt) {
42     error(toString(file) + ": machine type " + machineToStr(mt) +
43           " conflicts with " + machineToStr(config->machine));
44     return;
45   }
46 
47   if (auto *f = dyn_cast<ObjFile>(file)) {
48     ObjFile::instances.push_back(f);
49   } else if (auto *f = dyn_cast<BitcodeFile>(file)) {
50     BitcodeFile::instances.push_back(f);
51   } else if (auto *f = dyn_cast<ImportFile>(file)) {
52     ImportFile::instances.push_back(f);
53   }
54 
55   driver->parseDirectives(file);
56 }
57 
58 static void errorOrWarn(const Twine &s) {
59   if (config->forceUnresolved)
60     warn(s);
61   else
62     error(s);
63 }
64 
65 // Causes the file associated with a lazy symbol to be linked in.
66 static void forceLazy(Symbol *s) {
67   s->pendingArchiveLoad = true;
68   switch (s->kind()) {
69   case Symbol::Kind::LazyArchiveKind: {
70     auto *l = cast<LazyArchive>(s);
71     l->file->addMember(l->sym);
72     break;
73   }
74   case Symbol::Kind::LazyObjectKind:
75     cast<LazyObject>(s)->file->fetch();
76     break;
77   default:
78     llvm_unreachable(
79         "symbol passed to forceLazy is not a LazyArchive or LazyObject");
80   }
81 }
82 
83 // Returns the symbol in SC whose value is <= Addr that is closest to Addr.
84 // This is generally the global variable or function whose definition contains
85 // Addr.
86 static Symbol *getSymbol(SectionChunk *sc, uint32_t addr) {
87   DefinedRegular *candidate = nullptr;
88 
89   for (Symbol *s : sc->file->getSymbols()) {
90     auto *d = dyn_cast_or_null<DefinedRegular>(s);
91     if (!d || !d->data || d->file != sc->file || d->getChunk() != sc ||
92         d->getValue() > addr ||
93         (candidate && d->getValue() < candidate->getValue()))
94       continue;
95 
96     candidate = d;
97   }
98 
99   return candidate;
100 }
101 
102 static std::vector<std::string> getSymbolLocations(BitcodeFile *file) {
103   std::string res("\n>>> referenced by ");
104   StringRef source = file->obj->getSourceFileName();
105   if (!source.empty())
106     res += source.str() + "\n>>>               ";
107   res += toString(file);
108   return {res};
109 }
110 
111 static std::pair<StringRef, uint32_t> getFileLineDwarf(const SectionChunk *c,
112                                                        uint32_t addr) {
113   if (!config->symbolizer)
114     config->symbolizer = make<symbolize::LLVMSymbolizer>();
115   Expected<DILineInfo> expectedLineInfo = config->symbolizer->symbolizeCode(
116       *c->file->getCOFFObj(), {addr, c->getSectionNumber() - 1});
117   if (!expectedLineInfo)
118     return {"", 0};
119   const DILineInfo &lineInfo = *expectedLineInfo;
120   if (lineInfo.FileName == DILineInfo::BadString)
121     return {"", 0};
122   return {saver.save(lineInfo.FileName), lineInfo.Line};
123 }
124 
125 static std::pair<StringRef, uint32_t> getFileLine(const SectionChunk *c,
126                                                   uint32_t addr) {
127   // MinGW can optionally use codeview, even if the default is dwarf.
128   std::pair<StringRef, uint32_t> fileLine = getFileLineCodeView(c, addr);
129   // If codeview didn't yield any result, check dwarf in MinGW mode.
130   if (fileLine.first.empty() && config->mingw)
131     fileLine = getFileLineDwarf(c, addr);
132   return fileLine;
133 }
134 
135 // Given a file and the index of a symbol in that file, returns a description
136 // of all references to that symbol from that file. If no debug information is
137 // available, returns just the name of the file, else one string per actual
138 // reference as described in the debug info.
139 std::vector<std::string> getSymbolLocations(ObjFile *file, uint32_t symIndex) {
140   struct Location {
141     Symbol *sym;
142     std::pair<StringRef, uint32_t> fileLine;
143   };
144   std::vector<Location> locations;
145 
146   for (Chunk *c : file->getChunks()) {
147     auto *sc = dyn_cast<SectionChunk>(c);
148     if (!sc)
149       continue;
150     for (const coff_relocation &r : sc->getRelocs()) {
151       if (r.SymbolTableIndex != symIndex)
152         continue;
153       std::pair<StringRef, uint32_t> fileLine =
154           getFileLine(sc, r.VirtualAddress);
155       Symbol *sym = getSymbol(sc, r.VirtualAddress);
156       if (!fileLine.first.empty() || sym)
157         locations.push_back({sym, fileLine});
158     }
159   }
160 
161   if (locations.empty())
162     return std::vector<std::string>({"\n>>> referenced by " + toString(file)});
163 
164   std::vector<std::string> symbolLocations(locations.size());
165   size_t i = 0;
166   for (Location loc : locations) {
167     llvm::raw_string_ostream os(symbolLocations[i++]);
168     os << "\n>>> referenced by ";
169     if (!loc.fileLine.first.empty())
170       os << loc.fileLine.first << ":" << loc.fileLine.second
171          << "\n>>>               ";
172     os << toString(file);
173     if (loc.sym)
174       os << ":(" << toString(*loc.sym) << ')';
175   }
176   return symbolLocations;
177 }
178 
179 std::vector<std::string> getSymbolLocations(InputFile *file,
180                                             uint32_t symIndex) {
181   if (auto *o = dyn_cast<ObjFile>(file))
182     return getSymbolLocations(o, symIndex);
183   if (auto *b = dyn_cast<BitcodeFile>(file))
184     return getSymbolLocations(b);
185   llvm_unreachable("unsupported file type passed to getSymbolLocations");
186   return {};
187 }
188 
189 // For an undefined symbol, stores all files referencing it and the index of
190 // the undefined symbol in each file.
191 struct UndefinedDiag {
192   Symbol *sym;
193   struct File {
194     InputFile *file;
195     uint32_t symIndex;
196   };
197   std::vector<File> files;
198 };
199 
200 static void reportUndefinedSymbol(const UndefinedDiag &undefDiag) {
201   std::string out;
202   llvm::raw_string_ostream os(out);
203   os << "undefined symbol: " << toString(*undefDiag.sym);
204 
205   const size_t maxUndefReferences = 10;
206   size_t i = 0, numRefs = 0;
207   for (const UndefinedDiag::File &ref : undefDiag.files) {
208     std::vector<std::string> symbolLocations =
209         getSymbolLocations(ref.file, ref.symIndex);
210     numRefs += symbolLocations.size();
211     for (const std::string &s : symbolLocations) {
212       if (i >= maxUndefReferences)
213         break;
214       os << s;
215       i++;
216     }
217   }
218   if (i < numRefs)
219     os << "\n>>> referenced " << numRefs - i << " more times";
220   errorOrWarn(os.str());
221 }
222 
223 void SymbolTable::loadMinGWAutomaticImports() {
224   for (auto &i : symMap) {
225     Symbol *sym = i.second;
226     auto *undef = dyn_cast<Undefined>(sym);
227     if (!undef)
228       continue;
229     if (!sym->isUsedInRegularObj)
230       continue;
231     if (undef->getWeakAlias())
232       continue;
233 
234     StringRef name = undef->getName();
235 
236     if (name.startswith("__imp_"))
237       continue;
238     // If we have an undefined symbol, but we have a lazy symbol we could
239     // load, load it.
240     Symbol *l = find(("__imp_" + name).str());
241     if (!l || l->pendingArchiveLoad || !l->isLazy())
242       continue;
243 
244     log("Loading lazy " + l->getName() + " from " + l->getFile()->getName() +
245         " for automatic import");
246     forceLazy(l);
247   }
248 }
249 
250 Defined *SymbolTable::impSymbol(StringRef name) {
251   if (name.startswith("__imp_"))
252     return nullptr;
253   return dyn_cast_or_null<Defined>(find(("__imp_" + name).str()));
254 }
255 
256 bool SymbolTable::handleMinGWAutomaticImport(Symbol *sym, StringRef name) {
257   Defined *imp = impSymbol(name);
258   if (!imp)
259     return false;
260 
261   // Replace the reference directly to a variable with a reference
262   // to the import address table instead. This obviously isn't right,
263   // but we mark the symbol as isRuntimePseudoReloc, and a later pass
264   // will add runtime pseudo relocations for every relocation against
265   // this Symbol. The runtime pseudo relocation framework expects the
266   // reference itself to point at the IAT entry.
267   size_t impSize = 0;
268   if (isa<DefinedImportData>(imp)) {
269     log("Automatically importing " + name + " from " +
270         cast<DefinedImportData>(imp)->getDLLName());
271     impSize = sizeof(DefinedImportData);
272   } else if (isa<DefinedRegular>(imp)) {
273     log("Automatically importing " + name + " from " +
274         toString(cast<DefinedRegular>(imp)->file));
275     impSize = sizeof(DefinedRegular);
276   } else {
277     warn("unable to automatically import " + name + " from " + imp->getName() +
278          " from " + toString(cast<DefinedRegular>(imp)->file) +
279          "; unexpected symbol type");
280     return false;
281   }
282   sym->replaceKeepingName(imp, impSize);
283   sym->isRuntimePseudoReloc = true;
284 
285   // There may exist symbols named .refptr.<name> which only consist
286   // of a single pointer to <name>. If it turns out <name> is
287   // automatically imported, we don't need to keep the .refptr.<name>
288   // pointer at all, but redirect all accesses to it to the IAT entry
289   // for __imp_<name> instead, and drop the whole .refptr.<name> chunk.
290   DefinedRegular *refptr =
291       dyn_cast_or_null<DefinedRegular>(find((".refptr." + name).str()));
292   if (refptr && refptr->getChunk()->getSize() == config->wordsize) {
293     SectionChunk *sc = dyn_cast_or_null<SectionChunk>(refptr->getChunk());
294     if (sc && sc->getRelocs().size() == 1 && *sc->symbols().begin() == sym) {
295       log("Replacing .refptr." + name + " with " + imp->getName());
296       refptr->getChunk()->live = false;
297       refptr->replaceKeepingName(imp, impSize);
298     }
299   }
300   return true;
301 }
302 
303 /// Helper function for reportUnresolvable and resolveRemainingUndefines.
304 /// This function emits an "undefined symbol" diagnostic for each symbol in
305 /// undefs. If localImports is not nullptr, it also emits a "locally
306 /// defined symbol imported" diagnostic for symbols in localImports.
307 /// objFiles and bitcodeFiles (if not nullptr) are used to report where
308 /// undefined symbols are referenced.
309 static void
310 reportProblemSymbols(const SmallPtrSetImpl<Symbol *> &undefs,
311                      const DenseMap<Symbol *, Symbol *> *localImports,
312                      const std::vector<ObjFile *> objFiles,
313                      const std::vector<BitcodeFile *> *bitcodeFiles) {
314 
315   // Return early if there is nothing to report (which should be
316   // the common case).
317   if (undefs.empty() && (!localImports || localImports->empty()))
318     return;
319 
320   for (Symbol *b : config->gcroot) {
321     if (undefs.count(b))
322       errorOrWarn("<root>: undefined symbol: " + toString(*b));
323     if (localImports)
324       if (Symbol *imp = localImports->lookup(b))
325         warn("<root>: locally defined symbol imported: " + toString(*imp) +
326              " (defined in " + toString(imp->getFile()) + ") [LNK4217]");
327   }
328 
329   std::vector<UndefinedDiag> undefDiags;
330   DenseMap<Symbol *, int> firstDiag;
331 
332   auto processFile = [&](InputFile *file, ArrayRef<Symbol *> symbols) {
333     uint32_t symIndex = (uint32_t)-1;
334     for (Symbol *sym : symbols) {
335       ++symIndex;
336       if (!sym)
337         continue;
338       if (undefs.count(sym)) {
339         auto it = firstDiag.find(sym);
340         if (it == firstDiag.end()) {
341           firstDiag[sym] = undefDiags.size();
342           undefDiags.push_back({sym, {{file, symIndex}}});
343         } else {
344           undefDiags[it->second].files.push_back({file, symIndex});
345         }
346       }
347       if (localImports)
348         if (Symbol *imp = localImports->lookup(sym))
349           warn(toString(file) +
350                ": locally defined symbol imported: " + toString(*imp) +
351                " (defined in " + toString(imp->getFile()) + ") [LNK4217]");
352     }
353   };
354 
355   for (ObjFile *file : objFiles)
356     processFile(file, file->getSymbols());
357 
358   if (bitcodeFiles)
359     for (BitcodeFile *file : *bitcodeFiles)
360       processFile(file, file->getSymbols());
361 
362   for (const UndefinedDiag &undefDiag : undefDiags)
363     reportUndefinedSymbol(undefDiag);
364 }
365 
366 void SymbolTable::reportUnresolvable() {
367   SmallPtrSet<Symbol *, 8> undefs;
368   for (auto &i : symMap) {
369     Symbol *sym = i.second;
370     auto *undef = dyn_cast<Undefined>(sym);
371     if (!undef)
372       continue;
373     if (undef->getWeakAlias())
374       continue;
375     StringRef name = undef->getName();
376     if (name.startswith("__imp_")) {
377       Symbol *imp = find(name.substr(strlen("__imp_")));
378       if (imp && isa<Defined>(imp))
379         continue;
380     }
381     if (name.contains("_PchSym_"))
382       continue;
383     if (config->mingw && impSymbol(name))
384       continue;
385     undefs.insert(sym);
386   }
387 
388   reportProblemSymbols(undefs,
389                        /* localImports */ nullptr, ObjFile::instances,
390                        &BitcodeFile::instances);
391 }
392 
393 void SymbolTable::resolveRemainingUndefines() {
394   SmallPtrSet<Symbol *, 8> undefs;
395   DenseMap<Symbol *, Symbol *> localImports;
396 
397   for (auto &i : symMap) {
398     Symbol *sym = i.second;
399     auto *undef = dyn_cast<Undefined>(sym);
400     if (!undef)
401       continue;
402     if (!sym->isUsedInRegularObj)
403       continue;
404 
405     StringRef name = undef->getName();
406 
407     // A weak alias may have been resolved, so check for that.
408     if (Defined *d = undef->getWeakAlias()) {
409       // We want to replace Sym with D. However, we can't just blindly
410       // copy sizeof(SymbolUnion) bytes from D to Sym because D may be an
411       // internal symbol, and internal symbols are stored as "unparented"
412       // Symbols. For that reason we need to check which type of symbol we
413       // are dealing with and copy the correct number of bytes.
414       if (isa<DefinedRegular>(d))
415         memcpy(sym, d, sizeof(DefinedRegular));
416       else if (isa<DefinedAbsolute>(d))
417         memcpy(sym, d, sizeof(DefinedAbsolute));
418       else
419         memcpy(sym, d, sizeof(SymbolUnion));
420       continue;
421     }
422 
423     // If we can resolve a symbol by removing __imp_ prefix, do that.
424     // This odd rule is for compatibility with MSVC linker.
425     if (name.startswith("__imp_")) {
426       Symbol *imp = find(name.substr(strlen("__imp_")));
427       if (imp && isa<Defined>(imp)) {
428         auto *d = cast<Defined>(imp);
429         replaceSymbol<DefinedLocalImport>(sym, name, d);
430         localImportChunks.push_back(cast<DefinedLocalImport>(sym)->getChunk());
431         localImports[sym] = d;
432         continue;
433       }
434     }
435 
436     // We don't want to report missing Microsoft precompiled headers symbols.
437     // A proper message will be emitted instead in PDBLinker::aquirePrecompObj
438     if (name.contains("_PchSym_"))
439       continue;
440 
441     if (config->mingw && handleMinGWAutomaticImport(sym, name))
442       continue;
443 
444     // Remaining undefined symbols are not fatal if /force is specified.
445     // They are replaced with dummy defined symbols.
446     if (config->forceUnresolved)
447       replaceSymbol<DefinedAbsolute>(sym, name, 0);
448     undefs.insert(sym);
449   }
450 
451   reportProblemSymbols(
452       undefs, config->warnLocallyDefinedImported ? &localImports : nullptr,
453       ObjFile::instances, /* bitcode files no longer needed */ nullptr);
454 }
455 
456 std::pair<Symbol *, bool> SymbolTable::insert(StringRef name) {
457   bool inserted = false;
458   Symbol *&sym = symMap[CachedHashStringRef(name)];
459   if (!sym) {
460     sym = reinterpret_cast<Symbol *>(make<SymbolUnion>());
461     sym->isUsedInRegularObj = false;
462     sym->pendingArchiveLoad = false;
463     inserted = true;
464   }
465   return {sym, inserted};
466 }
467 
468 std::pair<Symbol *, bool> SymbolTable::insert(StringRef name, InputFile *file) {
469   std::pair<Symbol *, bool> result = insert(name);
470   if (!file || !isa<BitcodeFile>(file))
471     result.first->isUsedInRegularObj = true;
472   return result;
473 }
474 
475 Symbol *SymbolTable::addUndefined(StringRef name, InputFile *f,
476                                   bool isWeakAlias) {
477   Symbol *s;
478   bool wasInserted;
479   std::tie(s, wasInserted) = insert(name, f);
480   if (wasInserted || (s->isLazy() && isWeakAlias)) {
481     replaceSymbol<Undefined>(s, name);
482     return s;
483   }
484   if (s->isLazy())
485     forceLazy(s);
486   return s;
487 }
488 
489 void SymbolTable::addLazyArchive(ArchiveFile *f, const Archive::Symbol &sym) {
490   StringRef name = sym.getName();
491   Symbol *s;
492   bool wasInserted;
493   std::tie(s, wasInserted) = insert(name);
494   if (wasInserted) {
495     replaceSymbol<LazyArchive>(s, f, sym);
496     return;
497   }
498   auto *u = dyn_cast<Undefined>(s);
499   if (!u || u->weakAlias || s->pendingArchiveLoad)
500     return;
501   s->pendingArchiveLoad = true;
502   f->addMember(sym);
503 }
504 
505 void SymbolTable::addLazyObject(LazyObjFile *f, StringRef n) {
506   Symbol *s;
507   bool wasInserted;
508   std::tie(s, wasInserted) = insert(n, f);
509   if (wasInserted) {
510     replaceSymbol<LazyObject>(s, f, n);
511     return;
512   }
513   auto *u = dyn_cast<Undefined>(s);
514   if (!u || u->weakAlias || s->pendingArchiveLoad)
515     return;
516   s->pendingArchiveLoad = true;
517   f->fetch();
518 }
519 
520 void SymbolTable::reportDuplicate(Symbol *existing, InputFile *newFile) {
521   std::string msg = "duplicate symbol: " + toString(*existing) + " in " +
522                     toString(existing->getFile()) + " and in " +
523                     toString(newFile);
524 
525   if (config->forceMultiple)
526     warn(msg);
527   else
528     error(msg);
529 }
530 
531 Symbol *SymbolTable::addAbsolute(StringRef n, COFFSymbolRef sym) {
532   Symbol *s;
533   bool wasInserted;
534   std::tie(s, wasInserted) = insert(n, nullptr);
535   s->isUsedInRegularObj = true;
536   if (wasInserted || isa<Undefined>(s) || s->isLazy())
537     replaceSymbol<DefinedAbsolute>(s, n, sym);
538   else if (!isa<DefinedCOFF>(s))
539     reportDuplicate(s, nullptr);
540   return s;
541 }
542 
543 Symbol *SymbolTable::addAbsolute(StringRef n, uint64_t va) {
544   Symbol *s;
545   bool wasInserted;
546   std::tie(s, wasInserted) = insert(n, nullptr);
547   s->isUsedInRegularObj = true;
548   if (wasInserted || isa<Undefined>(s) || s->isLazy())
549     replaceSymbol<DefinedAbsolute>(s, n, va);
550   else if (!isa<DefinedCOFF>(s))
551     reportDuplicate(s, nullptr);
552   return s;
553 }
554 
555 Symbol *SymbolTable::addSynthetic(StringRef n, Chunk *c) {
556   Symbol *s;
557   bool wasInserted;
558   std::tie(s, wasInserted) = insert(n, nullptr);
559   s->isUsedInRegularObj = true;
560   if (wasInserted || isa<Undefined>(s) || s->isLazy())
561     replaceSymbol<DefinedSynthetic>(s, n, c);
562   else if (!isa<DefinedCOFF>(s))
563     reportDuplicate(s, nullptr);
564   return s;
565 }
566 
567 Symbol *SymbolTable::addRegular(InputFile *f, StringRef n,
568                                 const coff_symbol_generic *sym,
569                                 SectionChunk *c) {
570   Symbol *s;
571   bool wasInserted;
572   std::tie(s, wasInserted) = insert(n, f);
573   if (wasInserted || !isa<DefinedRegular>(s))
574     replaceSymbol<DefinedRegular>(s, f, n, /*IsCOMDAT*/ false,
575                                   /*IsExternal*/ true, sym, c);
576   else
577     reportDuplicate(s, f);
578   return s;
579 }
580 
581 std::pair<DefinedRegular *, bool>
582 SymbolTable::addComdat(InputFile *f, StringRef n,
583                        const coff_symbol_generic *sym) {
584   Symbol *s;
585   bool wasInserted;
586   std::tie(s, wasInserted) = insert(n, f);
587   if (wasInserted || !isa<DefinedRegular>(s)) {
588     replaceSymbol<DefinedRegular>(s, f, n, /*IsCOMDAT*/ true,
589                                   /*IsExternal*/ true, sym, nullptr);
590     return {cast<DefinedRegular>(s), true};
591   }
592   auto *existingSymbol = cast<DefinedRegular>(s);
593   if (!existingSymbol->isCOMDAT)
594     reportDuplicate(s, f);
595   return {existingSymbol, false};
596 }
597 
598 Symbol *SymbolTable::addCommon(InputFile *f, StringRef n, uint64_t size,
599                                const coff_symbol_generic *sym, CommonChunk *c) {
600   Symbol *s;
601   bool wasInserted;
602   std::tie(s, wasInserted) = insert(n, f);
603   if (wasInserted || !isa<DefinedCOFF>(s))
604     replaceSymbol<DefinedCommon>(s, f, n, size, sym, c);
605   else if (auto *dc = dyn_cast<DefinedCommon>(s))
606     if (size > dc->getSize())
607       replaceSymbol<DefinedCommon>(s, f, n, size, sym, c);
608   return s;
609 }
610 
611 Symbol *SymbolTable::addImportData(StringRef n, ImportFile *f) {
612   Symbol *s;
613   bool wasInserted;
614   std::tie(s, wasInserted) = insert(n, nullptr);
615   s->isUsedInRegularObj = true;
616   if (wasInserted || isa<Undefined>(s) || s->isLazy()) {
617     replaceSymbol<DefinedImportData>(s, n, f);
618     return s;
619   }
620 
621   reportDuplicate(s, f);
622   return nullptr;
623 }
624 
625 Symbol *SymbolTable::addImportThunk(StringRef name, DefinedImportData *id,
626                                     uint16_t machine) {
627   Symbol *s;
628   bool wasInserted;
629   std::tie(s, wasInserted) = insert(name, nullptr);
630   s->isUsedInRegularObj = true;
631   if (wasInserted || isa<Undefined>(s) || s->isLazy()) {
632     replaceSymbol<DefinedImportThunk>(s, name, id, machine);
633     return s;
634   }
635 
636   reportDuplicate(s, id->file);
637   return nullptr;
638 }
639 
640 void SymbolTable::addLibcall(StringRef name) {
641   Symbol *sym = findUnderscore(name);
642   if (!sym)
643     return;
644 
645   if (auto *l = dyn_cast<LazyArchive>(sym)) {
646     MemoryBufferRef mb = l->getMemberBuffer();
647     if (isBitcode(mb))
648       addUndefined(sym->getName());
649   } else if (LazyObject *o = dyn_cast<LazyObject>(sym)) {
650     if (isBitcode(o->file->mb))
651       addUndefined(sym->getName());
652   }
653 }
654 
655 std::vector<Chunk *> SymbolTable::getChunks() {
656   std::vector<Chunk *> res;
657   for (ObjFile *file : ObjFile::instances) {
658     ArrayRef<Chunk *> v = file->getChunks();
659     res.insert(res.end(), v.begin(), v.end());
660   }
661   return res;
662 }
663 
664 Symbol *SymbolTable::find(StringRef name) {
665   return symMap.lookup(CachedHashStringRef(name));
666 }
667 
668 Symbol *SymbolTable::findUnderscore(StringRef name) {
669   if (config->machine == I386)
670     return find(("_" + name).str());
671   return find(name);
672 }
673 
674 // Return all symbols that start with Prefix, possibly ignoring the first
675 // character of Prefix or the first character symbol.
676 std::vector<Symbol *> SymbolTable::getSymsWithPrefix(StringRef prefix) {
677   std::vector<Symbol *> syms;
678   for (auto pair : symMap) {
679     StringRef name = pair.first.val();
680     if (name.startswith(prefix) || name.startswith(prefix.drop_front()) ||
681         name.drop_front().startswith(prefix) ||
682         name.drop_front().startswith(prefix.drop_front())) {
683       syms.push_back(pair.second);
684     }
685   }
686   return syms;
687 }
688 
689 Symbol *SymbolTable::findMangle(StringRef name) {
690   if (Symbol *sym = find(name))
691     if (!isa<Undefined>(sym))
692       return sym;
693 
694   // Efficient fuzzy string lookup is impossible with a hash table, so iterate
695   // the symbol table once and collect all possibly matching symbols into this
696   // vector. Then compare each possibly matching symbol with each possible
697   // mangling.
698   std::vector<Symbol *> syms = getSymsWithPrefix(name);
699   auto findByPrefix = [&syms](const Twine &t) -> Symbol * {
700     std::string prefix = t.str();
701     for (auto *s : syms)
702       if (s->getName().startswith(prefix))
703         return s;
704     return nullptr;
705   };
706 
707   // For non-x86, just look for C++ functions.
708   if (config->machine != I386)
709     return findByPrefix("?" + name + "@@Y");
710 
711   if (!name.startswith("_"))
712     return nullptr;
713   // Search for x86 stdcall function.
714   if (Symbol *s = findByPrefix(name + "@"))
715     return s;
716   // Search for x86 fastcall function.
717   if (Symbol *s = findByPrefix("@" + name.substr(1) + "@"))
718     return s;
719   // Search for x86 vectorcall function.
720   if (Symbol *s = findByPrefix(name.substr(1) + "@@"))
721     return s;
722   // Search for x86 C++ non-member function.
723   return findByPrefix("?" + name.substr(1) + "@@Y");
724 }
725 
726 Symbol *SymbolTable::addUndefined(StringRef name) {
727   return addUndefined(name, nullptr, false);
728 }
729 
730 std::vector<StringRef> SymbolTable::compileBitcodeFiles() {
731   lto.reset(new BitcodeCompiler);
732   for (BitcodeFile *f : BitcodeFile::instances)
733     lto->add(*f);
734   return lto->compile();
735 }
736 
737 void SymbolTable::addCombinedLTOObjects() {
738   if (BitcodeFile::instances.empty())
739     return;
740 
741   ScopedTimer t(ltoTimer);
742   for (StringRef object : compileBitcodeFiles()) {
743     auto *obj = make<ObjFile>(MemoryBufferRef(object, "lto.tmp"));
744     obj->parse();
745     ObjFile::instances.push_back(obj);
746   }
747 }
748 
749 } // namespace coff
750 } // namespace lld
751