1c94d393aSSam Clegg //===- SymbolTable.cpp ----------------------------------------------------===//
2c94d393aSSam Clegg //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6c94d393aSSam Clegg //
7c94d393aSSam Clegg //===----------------------------------------------------------------------===//
8c94d393aSSam Clegg 
9c94d393aSSam Clegg #include "SymbolTable.h"
10c94d393aSSam Clegg #include "Config.h"
115fa274beSSam Clegg #include "InputChunks.h"
12e915a71fSHeejin Ahn #include "InputEvent.h"
1393102974SSam Clegg #include "InputGlobal.h"
14b8621596SSam Clegg #include "WriterUtils.h"
15c94d393aSSam Clegg #include "lld/Common/ErrorHandler.h"
162017d52bSRui Ueyama #include "lld/Common/Memory.h"
177d67dd11SRui Ueyama #include "llvm/ADT/SetVector.h"
18c94d393aSSam Clegg 
19c94d393aSSam Clegg #define DEBUG_TYPE "lld"
20c94d393aSSam Clegg 
21c94d393aSSam Clegg using namespace llvm;
2220db381bSSam Clegg using namespace llvm::wasm;
2345218f4aSSam Clegg using namespace llvm::object;
24c94d393aSSam Clegg using namespace lld;
25c94d393aSSam Clegg using namespace lld::wasm;
26c94d393aSSam Clegg 
27c94d393aSSam Clegg SymbolTable *lld::wasm::Symtab;
28c94d393aSSam Clegg 
29c94d393aSSam Clegg void SymbolTable::addFile(InputFile *File) {
30c94d393aSSam Clegg   log("Processing: " + toString(File));
311f3f774fSSam Clegg   if (Config->Trace)
321f3f774fSSam Clegg     message(toString(File));
33c94d393aSSam Clegg   File->parse();
34c94d393aSSam Clegg 
35c729c1b4SSam Clegg   // LLVM bitcode file
36c729c1b4SSam Clegg   if (auto *F = dyn_cast<BitcodeFile>(File))
37c729c1b4SSam Clegg     BitcodeFiles.push_back(F);
38c729c1b4SSam Clegg   else if (auto *F = dyn_cast<ObjFile>(File))
39c94d393aSSam Clegg     ObjectFiles.push_back(F);
40a688a42cSSam Clegg   else if (auto *F = dyn_cast<SharedFile>(File))
41a688a42cSSam Clegg     SharedFiles.push_back(F);
42c94d393aSSam Clegg }
43c94d393aSSam Clegg 
44c729c1b4SSam Clegg // This function is where all the optimizations of link-time
45c729c1b4SSam Clegg // optimization happens. When LTO is in use, some input files are
46c729c1b4SSam Clegg // not in native object file format but in the LLVM bitcode format.
47c729c1b4SSam Clegg // This function compiles bitcode files into a few big native files
48c729c1b4SSam Clegg // using LLVM functions and replaces bitcode symbols with the results.
49c729c1b4SSam Clegg // Because all bitcode files that the program consists of are passed
50c729c1b4SSam Clegg // to the compiler at once, it can do whole-program optimization.
51c729c1b4SSam Clegg void SymbolTable::addCombinedLTOObject() {
52c729c1b4SSam Clegg   if (BitcodeFiles.empty())
53c729c1b4SSam Clegg     return;
54c729c1b4SSam Clegg 
55c729c1b4SSam Clegg   // Compile bitcode files and replace bitcode symbols.
56c729c1b4SSam Clegg   LTO.reset(new BitcodeCompiler);
57c729c1b4SSam Clegg   for (BitcodeFile *F : BitcodeFiles)
58c729c1b4SSam Clegg     LTO->add(*F);
59c729c1b4SSam Clegg 
60c729c1b4SSam Clegg   for (StringRef Filename : LTO->compile()) {
610cfaa247SSam Clegg     auto *Obj = make<ObjFile>(MemoryBufferRef(Filename, "lto.tmp"), "");
62697f2149SSam Clegg     Obj->parse(true);
63c729c1b4SSam Clegg     ObjectFiles.push_back(Obj);
64c729c1b4SSam Clegg   }
65c729c1b4SSam Clegg }
66c729c1b4SSam Clegg 
67c94d393aSSam Clegg void SymbolTable::reportRemainingUndefines() {
6874fe0ba1SSam Clegg   for (Symbol *Sym : SymVector) {
69c729c1b4SSam Clegg     if (!Sym->isUndefined() || Sym->isWeak())
70c729c1b4SSam Clegg       continue;
71c729c1b4SSam Clegg     if (Config->AllowUndefinedSymbols.count(Sym->getName()) != 0)
72c729c1b4SSam Clegg       continue;
73c729c1b4SSam Clegg     if (!Sym->IsUsedInRegularObj)
74c729c1b4SSam Clegg       continue;
7547e2b6b2SSam Clegg     error(toString(Sym->getFile()) + ": undefined symbol: " + toString(*Sym));
76c94d393aSSam Clegg   }
77c94d393aSSam Clegg }
78c94d393aSSam Clegg 
79c94d393aSSam Clegg Symbol *SymbolTable::find(StringRef Name) {
801f3f774fSSam Clegg   auto It = SymMap.find(CachedHashStringRef(Name));
811f3f774fSSam Clegg   if (It == SymMap.end() || It->second == -1)
821f3f774fSSam Clegg     return nullptr;
831f3f774fSSam Clegg   return SymVector[It->second];
841f3f774fSSam Clegg }
851f3f774fSSam Clegg 
866540e570SSam Clegg void SymbolTable::replace(StringRef Name, Symbol* Sym) {
876540e570SSam Clegg   auto It = SymMap.find(CachedHashStringRef(Name));
886540e570SSam Clegg   SymVector[It->second] = Sym;
896540e570SSam Clegg }
906540e570SSam Clegg 
911f3f774fSSam Clegg std::pair<Symbol *, bool> SymbolTable::insertName(StringRef Name) {
921f3f774fSSam Clegg   bool Trace = false;
931f3f774fSSam Clegg   auto P = SymMap.insert({CachedHashStringRef(Name), (int)SymVector.size()});
941f3f774fSSam Clegg   int &SymIndex = P.first->second;
951f3f774fSSam Clegg   bool IsNew = P.second;
961f3f774fSSam Clegg   if (SymIndex == -1) {
971f3f774fSSam Clegg     SymIndex = SymVector.size();
981f3f774fSSam Clegg     Trace = true;
991f3f774fSSam Clegg     IsNew = true;
1001f3f774fSSam Clegg   }
1011f3f774fSSam Clegg 
1021f3f774fSSam Clegg   if (!IsNew)
1031f3f774fSSam Clegg     return {SymVector[SymIndex], false};
1041f3f774fSSam Clegg 
1051f3f774fSSam Clegg   Symbol *Sym = reinterpret_cast<Symbol *>(make<SymbolUnion>());
1061f3f774fSSam Clegg   Sym->IsUsedInRegularObj = false;
1071f3f774fSSam Clegg   Sym->Traced = Trace;
1081f3f774fSSam Clegg   SymVector.emplace_back(Sym);
1091f3f774fSSam Clegg   return {Sym, true};
110c94d393aSSam Clegg }
111c94d393aSSam Clegg 
112230dc11dSSam Clegg std::pair<Symbol *, bool> SymbolTable::insert(StringRef Name,
113230dc11dSSam Clegg                                               const InputFile *File) {
1141f3f774fSSam Clegg   Symbol *S;
1151f3f774fSSam Clegg   bool WasInserted;
1161f3f774fSSam Clegg   std::tie(S, WasInserted) = insertName(Name);
1171f3f774fSSam Clegg 
1184c2cbfe6SSam Clegg   if (!File || File->kind() == InputFile::ObjectKind)
1191f3f774fSSam Clegg     S->IsUsedInRegularObj = true;
1201f3f774fSSam Clegg 
1211f3f774fSSam Clegg   return {S, WasInserted};
122c94d393aSSam Clegg }
123c94d393aSSam Clegg 
124e3498ec5SRui Ueyama static void reportTypeError(const Symbol *Existing, const InputFile *File,
1253876d89aSSam Clegg                             llvm::wasm::WasmSymbolType Type) {
126e3498ec5SRui Ueyama   error("symbol type mismatch: " + toString(*Existing) + "\n>>> defined as " +
127e3498ec5SRui Ueyama         toString(Existing->getWasmType()) + " in " +
1283876d89aSSam Clegg         toString(Existing->getFile()) + "\n>>> defined as " + toString(Type) +
1293876d89aSSam Clegg         " in " + toString(File));
130e3498ec5SRui Ueyama }
131e3498ec5SRui Ueyama 
1326f4286fbSHeejin Ahn // Check the type of new symbol matches that of the symbol is replacing.
1336540e570SSam Clegg // Returns true if the function types match, false is there is a singature
1346540e570SSam Clegg // mismatch.
135ba2ea93aSBenjamin Kramer static bool signatureMatches(FunctionSymbol *Existing,
136ba2ea93aSBenjamin Kramer                              const WasmSignature *NewSig) {
137cefbf9acSSam Clegg   if (!NewSig)
1386540e570SSam Clegg     return true;
139cefbf9acSSam Clegg 
1406540e570SSam Clegg   const WasmSignature *OldSig = Existing->Signature;
141cefbf9acSSam Clegg   if (!OldSig) {
1426540e570SSam Clegg     Existing->Signature = NewSig;
1436540e570SSam Clegg     return true;
144cefbf9acSSam Clegg   }
145cefbf9acSSam Clegg 
1466540e570SSam Clegg   return *NewSig == *OldSig;
147e3498ec5SRui Ueyama }
148e3498ec5SRui Ueyama 
149e3498ec5SRui Ueyama static void checkGlobalType(const Symbol *Existing, const InputFile *File,
150e3498ec5SRui Ueyama                             const WasmGlobalType *NewType) {
151e3498ec5SRui Ueyama   if (!isa<GlobalSymbol>(Existing)) {
1523876d89aSSam Clegg     reportTypeError(Existing, File, WASM_SYMBOL_TYPE_GLOBAL);
153b8621596SSam Clegg     return;
154b8621596SSam Clegg   }
155b8621596SSam Clegg 
156e3498ec5SRui Ueyama   const WasmGlobalType *OldType = cast<GlobalSymbol>(Existing)->getGlobalType();
157e3498ec5SRui Ueyama   if (*NewType != *OldType) {
158e3498ec5SRui Ueyama     error("Global type mismatch: " + Existing->getName() + "\n>>> defined as " +
159e3498ec5SRui Ueyama           toString(*OldType) + " in " + toString(Existing->getFile()) +
160e3498ec5SRui Ueyama           "\n>>> defined as " + toString(*NewType) + " in " + toString(File));
161c94d393aSSam Clegg   }
16224b3dcd4SSam Clegg }
16324b3dcd4SSam Clegg 
164e915a71fSHeejin Ahn static void checkEventType(const Symbol *Existing, const InputFile *File,
165e915a71fSHeejin Ahn                            const WasmEventType *NewType,
166e915a71fSHeejin Ahn                            const WasmSignature *NewSig) {
167e915a71fSHeejin Ahn   auto ExistingEvent = dyn_cast<EventSymbol>(Existing);
168e915a71fSHeejin Ahn   if (!isa<EventSymbol>(Existing)) {
169e915a71fSHeejin Ahn     reportTypeError(Existing, File, WASM_SYMBOL_TYPE_EVENT);
170e915a71fSHeejin Ahn     return;
171e915a71fSHeejin Ahn   }
172e915a71fSHeejin Ahn 
173e915a71fSHeejin Ahn   const WasmEventType *OldType = cast<EventSymbol>(Existing)->getEventType();
174e915a71fSHeejin Ahn   const WasmSignature *OldSig = ExistingEvent->Signature;
175e915a71fSHeejin Ahn   if (NewType->Attribute != OldType->Attribute)
176e915a71fSHeejin Ahn     error("Event type mismatch: " + Existing->getName() + "\n>>> defined as " +
177e915a71fSHeejin Ahn           toString(*OldType) + " in " + toString(Existing->getFile()) +
178e915a71fSHeejin Ahn           "\n>>> defined as " + toString(*NewType) + " in " + toString(File));
179e915a71fSHeejin Ahn   if (*NewSig != *OldSig)
180e915a71fSHeejin Ahn     warn("Event signature mismatch: " + Existing->getName() +
181e915a71fSHeejin Ahn          "\n>>> defined as " + toString(*OldSig) + " in " +
182e915a71fSHeejin Ahn          toString(Existing->getFile()) + "\n>>> defined as " +
183e915a71fSHeejin Ahn          toString(*NewSig) + " in " + toString(File));
184e915a71fSHeejin Ahn }
185e915a71fSHeejin Ahn 
186e3498ec5SRui Ueyama static void checkDataType(const Symbol *Existing, const InputFile *File) {
187e3498ec5SRui Ueyama   if (!isa<DataSymbol>(Existing))
1883876d89aSSam Clegg     reportTypeError(Existing, File, WASM_SYMBOL_TYPE_DATA);
189e3498ec5SRui Ueyama }
190e3498ec5SRui Ueyama 
191dfb0b2c7SSam Clegg DefinedFunction *SymbolTable::addSyntheticFunction(StringRef Name,
192ebda41f8SNicholas Wilson                                                    uint32_t Flags,
193ebda41f8SNicholas Wilson                                                    InputFunction *Function) {
194e7245b42SNicola Zaghen   LLVM_DEBUG(dbgs() << "addSyntheticFunction: " << Name << "\n");
195b961abc8SRui Ueyama   assert(!find(Name));
196ebda41f8SNicholas Wilson   SyntheticFunctions.emplace_back(Function);
197d15a4154SSam Clegg   return replaceSymbol<DefinedFunction>(insertName(Name).first, Name,
1984c2cbfe6SSam Clegg                                         Flags, nullptr, Function);
19950686856SSam Clegg }
20050686856SSam Clegg 
2014bce63a0SSam Clegg DefinedData *SymbolTable::addOptionalDataSymbol(StringRef Name, uint32_t Value,
2024bce63a0SSam Clegg                                                 uint32_t Flags) {
2034bce63a0SSam Clegg   Symbol *S = find(Name);
2044bce63a0SSam Clegg   if (!S || S->isDefined())
2054bce63a0SSam Clegg     return nullptr;
2064bce63a0SSam Clegg   LLVM_DEBUG(dbgs() << "addOptionalDataSymbol: " << Name << "\n");
2074bce63a0SSam Clegg   auto *rtn = replaceSymbol<DefinedData>(S, Name, Flags);
2084bce63a0SSam Clegg   rtn->setVirtualAddress(Value);
2094bce63a0SSam Clegg   return rtn;
2104bce63a0SSam Clegg }
2114bce63a0SSam Clegg 
21200245539SSam Clegg DefinedData *SymbolTable::addSyntheticDataSymbol(StringRef Name,
21300245539SSam Clegg                                                  uint32_t Flags) {
214e7245b42SNicola Zaghen   LLVM_DEBUG(dbgs() << "addSyntheticDataSymbol: " << Name << "\n");
215b961abc8SRui Ueyama   assert(!find(Name));
216d15a4154SSam Clegg   return replaceSymbol<DefinedData>(insertName(Name).first, Name, Flags);
217c94d393aSSam Clegg }
218c94d393aSSam Clegg 
21993102974SSam Clegg DefinedGlobal *SymbolTable::addSyntheticGlobal(StringRef Name, uint32_t Flags,
22093102974SSam Clegg                                                InputGlobal *Global) {
221e7245b42SNicola Zaghen   LLVM_DEBUG(dbgs() << "addSyntheticGlobal: " << Name << " -> " << Global
222e7245b42SNicola Zaghen                     << "\n");
223b961abc8SRui Ueyama   assert(!find(Name));
224ebda41f8SNicholas Wilson   SyntheticGlobals.emplace_back(Global);
225d15a4154SSam Clegg   return replaceSymbol<DefinedGlobal>(insertName(Name).first, Name, Flags,
2264c2cbfe6SSam Clegg                                       nullptr, Global);
22793102974SSam Clegg }
22893102974SSam Clegg 
229e3498ec5SRui Ueyama static bool shouldReplace(const Symbol *Existing, InputFile *NewFile,
230e3498ec5SRui Ueyama                           uint32_t NewFlags) {
231c03c9040SRui Ueyama   // If existing symbol is undefined, replace it.
232e3498ec5SRui Ueyama   if (!Existing->isDefined()) {
233e7245b42SNicola Zaghen     LLVM_DEBUG(dbgs() << "resolving existing undefined symbol: "
234e3498ec5SRui Ueyama                       << Existing->getName() << "\n");
235c03c9040SRui Ueyama     return true;
236c03c9040SRui Ueyama   }
237c03c9040SRui Ueyama 
238c03c9040SRui Ueyama   // Now we have two defined symbols. If the new one is weak, we can ignore it.
239c03c9040SRui Ueyama   if ((NewFlags & WASM_SYMBOL_BINDING_MASK) == WASM_SYMBOL_BINDING_WEAK) {
240e7245b42SNicola Zaghen     LLVM_DEBUG(dbgs() << "existing symbol takes precedence\n");
241c03c9040SRui Ueyama     return false;
242c03c9040SRui Ueyama   }
243c03c9040SRui Ueyama 
244c03c9040SRui Ueyama   // If the existing symbol is weak, we should replace it.
245e3498ec5SRui Ueyama   if (Existing->isWeak()) {
246e7245b42SNicola Zaghen     LLVM_DEBUG(dbgs() << "replacing existing weak symbol\n");
247c03c9040SRui Ueyama     return true;
248c03c9040SRui Ueyama   }
249c03c9040SRui Ueyama 
250c03c9040SRui Ueyama   // Neither symbol is week. They conflict.
251e3498ec5SRui Ueyama   error("duplicate symbol: " + toString(*Existing) + "\n>>> defined in " +
252e3498ec5SRui Ueyama         toString(Existing->getFile()) + "\n>>> defined in " +
253e3498ec5SRui Ueyama         toString(NewFile));
254c03c9040SRui Ueyama   return true;
255b8621596SSam Clegg }
25693e559b1SSam Clegg 
25793e559b1SSam Clegg Symbol *SymbolTable::addDefinedFunction(StringRef Name, uint32_t Flags,
258e3498ec5SRui Ueyama                                         InputFile *File,
259e3498ec5SRui Ueyama                                         InputFunction *Function) {
2608b0b48f3SSam Clegg   LLVM_DEBUG(dbgs() << "addDefinedFunction: " << Name << " ["
2618b0b48f3SSam Clegg                     << (Function ? toString(Function->Signature) : "none")
2628b0b48f3SSam Clegg                     << "]\n");
26393e559b1SSam Clegg   Symbol *S;
26493e559b1SSam Clegg   bool WasInserted;
2654c2cbfe6SSam Clegg   std::tie(S, WasInserted) = insert(Name, File);
266c729c1b4SSam Clegg 
2676540e570SSam Clegg   auto Replace = [&](Symbol* Sym) {
2686540e570SSam Clegg     // If the new defined function doesn't have signture (i.e. bitcode
2696540e570SSam Clegg     // functions) but the old symbol does, then preserve the old signature
2706540e570SSam Clegg     const WasmSignature *OldSig = S->getSignature();
2716540e570SSam Clegg     auto* NewSym = replaceSymbol<DefinedFunction>(Sym, Name, Flags, File, Function);
2726540e570SSam Clegg     if (!NewSym->Signature)
2736540e570SSam Clegg       NewSym->Signature = OldSig;
2746540e570SSam Clegg   };
2756540e570SSam Clegg 
276e3498ec5SRui Ueyama   if (WasInserted || S->isLazy()) {
2776540e570SSam Clegg     Replace(S);
278e3498ec5SRui Ueyama     return S;
279e3498ec5SRui Ueyama   }
280e3498ec5SRui Ueyama 
2816540e570SSam Clegg   auto ExistingFunction = dyn_cast<FunctionSymbol>(S);
2826540e570SSam Clegg   if (!ExistingFunction) {
2836540e570SSam Clegg     reportTypeError(S, File, WASM_SYMBOL_TYPE_FUNCTION);
2846540e570SSam Clegg     return S;
2858b0b48f3SSam Clegg   }
2866540e570SSam Clegg 
2876540e570SSam Clegg   if (Function && !signatureMatches(ExistingFunction, &Function->Signature)) {
2886540e570SSam Clegg     Symbol* Variant;
2896540e570SSam Clegg     if (getFunctionVariant(S, &Function->Signature, File, &Variant))
2906540e570SSam Clegg       // New variant, always replace
2916540e570SSam Clegg       Replace(Variant);
2926540e570SSam Clegg     else if (shouldReplace(S, File, Flags))
2936540e570SSam Clegg       // Variant already exists, replace it after checking shouldReplace
2946540e570SSam Clegg       Replace(Variant);
2956540e570SSam Clegg 
2966540e570SSam Clegg     // This variant we found take the place in the symbol table as the primary
2976540e570SSam Clegg     // variant.
2986540e570SSam Clegg     replace(Name, Variant);
2996540e570SSam Clegg     return Variant;
3006540e570SSam Clegg   }
3016540e570SSam Clegg 
3026540e570SSam Clegg   // Existing function with matching signature.
3036540e570SSam Clegg   if (shouldReplace(S, File, Flags))
3046540e570SSam Clegg     Replace(S);
3056540e570SSam Clegg 
30693e559b1SSam Clegg   return S;
30793e559b1SSam Clegg }
30893e559b1SSam Clegg 
30900245539SSam Clegg Symbol *SymbolTable::addDefinedData(StringRef Name, uint32_t Flags,
310e3498ec5SRui Ueyama                                     InputFile *File, InputSegment *Segment,
31193102974SSam Clegg                                     uint32_t Address, uint32_t Size) {
312e7245b42SNicola Zaghen   LLVM_DEBUG(dbgs() << "addDefinedData:" << Name << " addr:" << Address
313e7245b42SNicola Zaghen                     << "\n");
31493e559b1SSam Clegg   Symbol *S;
31593e559b1SSam Clegg   bool WasInserted;
3164c2cbfe6SSam Clegg   std::tie(S, WasInserted) = insert(Name, File);
317c729c1b4SSam Clegg 
3186540e570SSam Clegg   auto Replace = [&]() {
319e3498ec5SRui Ueyama     replaceSymbol<DefinedData>(S, Name, Flags, File, Segment, Address, Size);
3206540e570SSam Clegg   };
3216540e570SSam Clegg 
3226540e570SSam Clegg   if (WasInserted || S->isLazy()) {
3236540e570SSam Clegg     Replace();
324e3498ec5SRui Ueyama     return S;
325e3498ec5SRui Ueyama   }
326e3498ec5SRui Ueyama 
327e3498ec5SRui Ueyama   checkDataType(S, File);
328e3498ec5SRui Ueyama 
329e3498ec5SRui Ueyama   if (shouldReplace(S, File, Flags))
3306540e570SSam Clegg     Replace();
331c94d393aSSam Clegg   return S;
332c94d393aSSam Clegg }
333c94d393aSSam Clegg 
33493102974SSam Clegg Symbol *SymbolTable::addDefinedGlobal(StringRef Name, uint32_t Flags,
335e3498ec5SRui Ueyama                                       InputFile *File, InputGlobal *Global) {
336e7245b42SNicola Zaghen   LLVM_DEBUG(dbgs() << "addDefinedGlobal:" << Name << "\n");
3374c2cbfe6SSam Clegg 
33893102974SSam Clegg   Symbol *S;
33993102974SSam Clegg   bool WasInserted;
3404c2cbfe6SSam Clegg   std::tie(S, WasInserted) = insert(Name, File);
341c729c1b4SSam Clegg 
3426540e570SSam Clegg   auto Replace = [&]() {
343e3498ec5SRui Ueyama     replaceSymbol<DefinedGlobal>(S, Name, Flags, File, Global);
3446540e570SSam Clegg   };
3456540e570SSam Clegg 
3466540e570SSam Clegg   if (WasInserted || S->isLazy()) {
3476540e570SSam Clegg     Replace();
34893102974SSam Clegg     return S;
34993102974SSam Clegg   }
35093102974SSam Clegg 
351e3498ec5SRui Ueyama   checkGlobalType(S, File, &Global->getType());
352e3498ec5SRui Ueyama 
353e3498ec5SRui Ueyama   if (shouldReplace(S, File, Flags))
3546540e570SSam Clegg     Replace();
355e3498ec5SRui Ueyama   return S;
356e3498ec5SRui Ueyama }
357e3498ec5SRui Ueyama 
358e915a71fSHeejin Ahn Symbol *SymbolTable::addDefinedEvent(StringRef Name, uint32_t Flags,
359e915a71fSHeejin Ahn                                      InputFile *File, InputEvent *Event) {
360e915a71fSHeejin Ahn   LLVM_DEBUG(dbgs() << "addDefinedEvent:" << Name << "\n");
361e915a71fSHeejin Ahn 
362e915a71fSHeejin Ahn   Symbol *S;
363e915a71fSHeejin Ahn   bool WasInserted;
364e915a71fSHeejin Ahn   std::tie(S, WasInserted) = insert(Name, File);
365e915a71fSHeejin Ahn 
3666540e570SSam Clegg   auto Replace = [&]() {
367e915a71fSHeejin Ahn     replaceSymbol<DefinedEvent>(S, Name, Flags, File, Event);
3686540e570SSam Clegg   };
3696540e570SSam Clegg 
3706540e570SSam Clegg   if (WasInserted || S->isLazy()) {
3716540e570SSam Clegg     Replace();
372e915a71fSHeejin Ahn     return S;
373e915a71fSHeejin Ahn   }
374e915a71fSHeejin Ahn 
375e915a71fSHeejin Ahn   checkEventType(S, File, &Event->getType(), &Event->Signature);
376e915a71fSHeejin Ahn 
377e915a71fSHeejin Ahn   if (shouldReplace(S, File, Flags))
3786540e570SSam Clegg     Replace();
379e915a71fSHeejin Ahn   return S;
380e915a71fSHeejin Ahn }
381e915a71fSHeejin Ahn 
3829b84eeaaSDan Gohman Symbol *SymbolTable::addUndefinedFunction(StringRef Name, StringRef ImportName,
3839b84eeaaSDan Gohman                                           StringRef ImportModule,
3847cc07531SSam Clegg                                           uint32_t Flags, InputFile *File,
385e3498ec5SRui Ueyama                                           const WasmSignature *Sig) {
3868b0b48f3SSam Clegg   LLVM_DEBUG(dbgs() << "addUndefinedFunction: " << Name <<
3878b0b48f3SSam Clegg              " [" << (Sig ? toString(*Sig) : "none") << "]\n");
388c03c9040SRui Ueyama 
389c94d393aSSam Clegg   Symbol *S;
390c94d393aSSam Clegg   bool WasInserted;
3914c2cbfe6SSam Clegg   std::tie(S, WasInserted) = insert(Name, File);
392*7991b682SSam Clegg   if (S->Traced)
393*7991b682SSam Clegg     printTraceSymbolUndefined(Name, File);
394c729c1b4SSam Clegg 
3956540e570SSam Clegg   auto Replace = [&]() {
3969b84eeaaSDan Gohman     replaceSymbol<UndefinedFunction>(S, Name, ImportName, ImportModule, Flags,
3979b84eeaaSDan Gohman                                      File, Sig);
3986540e570SSam Clegg   };
3996540e570SSam Clegg 
4006540e570SSam Clegg   if (WasInserted)
4016540e570SSam Clegg     Replace();
402e3498ec5SRui Ueyama   else if (auto *Lazy = dyn_cast<LazySymbol>(S))
403b961abc8SRui Ueyama     Lazy->fetch();
4046540e570SSam Clegg   else {
4056540e570SSam Clegg     auto ExistingFunction = dyn_cast<FunctionSymbol>(S);
4066540e570SSam Clegg     if (!ExistingFunction) {
4076540e570SSam Clegg       reportTypeError(S, File, WASM_SYMBOL_TYPE_FUNCTION);
4086540e570SSam Clegg       return S;
4096540e570SSam Clegg     }
4106540e570SSam Clegg     if (!signatureMatches(ExistingFunction, Sig))
4116540e570SSam Clegg       if (getFunctionVariant(S, Sig, File, &S))
4126540e570SSam Clegg         Replace();
4136540e570SSam Clegg   }
414cefbf9acSSam Clegg 
415c03c9040SRui Ueyama   return S;
416c03c9040SRui Ueyama }
417c03c9040SRui Ueyama 
418e3498ec5SRui Ueyama Symbol *SymbolTable::addUndefinedData(StringRef Name, uint32_t Flags,
419e3498ec5SRui Ueyama                                       InputFile *File) {
420e7245b42SNicola Zaghen   LLVM_DEBUG(dbgs() << "addUndefinedData: " << Name << "\n");
42193102974SSam Clegg 
422e3498ec5SRui Ueyama   Symbol *S;
423e3498ec5SRui Ueyama   bool WasInserted;
4244c2cbfe6SSam Clegg   std::tie(S, WasInserted) = insert(Name, File);
425*7991b682SSam Clegg   if (S->Traced)
426*7991b682SSam Clegg     printTraceSymbolUndefined(Name, File);
427f989a92dSSam Clegg 
428e3498ec5SRui Ueyama   if (WasInserted)
429e3498ec5SRui Ueyama     replaceSymbol<UndefinedData>(S, Name, Flags, File);
430e3498ec5SRui Ueyama   else if (auto *Lazy = dyn_cast<LazySymbol>(S))
431b961abc8SRui Ueyama     Lazy->fetch();
432e3498ec5SRui Ueyama   else if (S->isDefined())
433e3498ec5SRui Ueyama     checkDataType(S, File);
434c94d393aSSam Clegg   return S;
435c94d393aSSam Clegg }
436c94d393aSSam Clegg 
4379b84eeaaSDan Gohman Symbol *SymbolTable::addUndefinedGlobal(StringRef Name, StringRef ImportName,
4389b84eeaaSDan Gohman                                         StringRef ImportModule, uint32_t Flags,
439e3498ec5SRui Ueyama                                         InputFile *File,
440e3498ec5SRui Ueyama                                         const WasmGlobalType *Type) {
441e7245b42SNicola Zaghen   LLVM_DEBUG(dbgs() << "addUndefinedGlobal: " << Name << "\n");
442e3498ec5SRui Ueyama 
443e3498ec5SRui Ueyama   Symbol *S;
444e3498ec5SRui Ueyama   bool WasInserted;
4454c2cbfe6SSam Clegg   std::tie(S, WasInserted) = insert(Name, File);
446*7991b682SSam Clegg   if (S->Traced)
447*7991b682SSam Clegg     printTraceSymbolUndefined(Name, File);
448c729c1b4SSam Clegg 
449e3498ec5SRui Ueyama   if (WasInserted)
4509b84eeaaSDan Gohman     replaceSymbol<UndefinedGlobal>(S, Name, ImportName, ImportModule, Flags,
4519b84eeaaSDan Gohman                                    File, Type);
452e3498ec5SRui Ueyama   else if (auto *Lazy = dyn_cast<LazySymbol>(S))
453b961abc8SRui Ueyama     Lazy->fetch();
454e3498ec5SRui Ueyama   else if (S->isDefined())
455e3498ec5SRui Ueyama     checkGlobalType(S, File, Type);
456e3498ec5SRui Ueyama   return S;
457e3498ec5SRui Ueyama }
458e3498ec5SRui Ueyama 
459e3498ec5SRui Ueyama void SymbolTable::addLazy(ArchiveFile *File, const Archive::Symbol *Sym) {
460e7245b42SNicola Zaghen   LLVM_DEBUG(dbgs() << "addLazy: " << Sym->getName() << "\n");
461c94d393aSSam Clegg   StringRef Name = Sym->getName();
462c03c9040SRui Ueyama 
463c94d393aSSam Clegg   Symbol *S;
464c94d393aSSam Clegg   bool WasInserted;
465d15a4154SSam Clegg   std::tie(S, WasInserted) = insertName(Name);
466c03c9040SRui Ueyama 
467c94d393aSSam Clegg   if (WasInserted) {
46837b4ee52SSam Clegg     replaceSymbol<LazySymbol>(S, Name, 0, File, *Sym);
469c03c9040SRui Ueyama     return;
470c03c9040SRui Ueyama   }
471c03c9040SRui Ueyama 
47237b4ee52SSam Clegg   if (!S->isUndefined())
47337b4ee52SSam Clegg     return;
47437b4ee52SSam Clegg 
47537b4ee52SSam Clegg   // The existing symbol is undefined, load a new one from the archive,
47637b4ee52SSam Clegg   // unless the the existing symbol is weak in which case replace the undefined
47737b4ee52SSam Clegg   // symbols with a LazySymbol.
47837b4ee52SSam Clegg   if (S->isWeak()) {
47937b4ee52SSam Clegg     const WasmSignature *OldSig = nullptr;
48037b4ee52SSam Clegg     // In the case of an UndefinedFunction we need to preserve the expected
48137b4ee52SSam Clegg     // signature.
48237b4ee52SSam Clegg     if (auto *F = dyn_cast<UndefinedFunction>(S))
48337b4ee52SSam Clegg       OldSig = F->Signature;
48437b4ee52SSam Clegg     LLVM_DEBUG(dbgs() << "replacing existing weak undefined symbol\n");
48537b4ee52SSam Clegg     auto NewSym = replaceSymbol<LazySymbol>(S, Name, WASM_SYMBOL_BINDING_WEAK,
48637b4ee52SSam Clegg                                             File, *Sym);
48737b4ee52SSam Clegg     NewSym->Signature = OldSig;
48837b4ee52SSam Clegg     return;
48937b4ee52SSam Clegg   }
49037b4ee52SSam Clegg 
491e7245b42SNicola Zaghen   LLVM_DEBUG(dbgs() << "replacing existing undefined\n");
492e3498ec5SRui Ueyama   File->addMember(Sym);
493c94d393aSSam Clegg }
494e0f6fcd0SSam Clegg 
495c4d9aa1bSNicholas Wilson bool SymbolTable::addComdat(StringRef Name) {
496697f2149SSam Clegg   return ComdatGroups.insert(CachedHashStringRef(Name)).second;
497e0f6fcd0SSam Clegg }
4981f3f774fSSam Clegg 
4996540e570SSam Clegg // The new signature doesn't match.  Create a variant to the symbol with the
5006540e570SSam Clegg // signature encoded in the name and return that instead.  These symbols are
5016540e570SSam Clegg // then unified later in handleSymbolVariants.
5026540e570SSam Clegg bool SymbolTable::getFunctionVariant(Symbol* Sym, const WasmSignature *Sig,
5036540e570SSam Clegg                                      const InputFile *File, Symbol **Out) {
50414bab09eSRichard Trieu   LLVM_DEBUG(dbgs() << "getFunctionVariant: " << Sym->getName() << " -> "
5056540e570SSam Clegg                     << " " << toString(*Sig) << "\n");
5066540e570SSam Clegg   Symbol *Variant = nullptr;
5076540e570SSam Clegg 
5086540e570SSam Clegg   // Linear search through symbol variants.  Should never be more than two
5096540e570SSam Clegg   // or three entries here.
5106540e570SSam Clegg   auto &Variants = SymVariants[CachedHashStringRef(Sym->getName())];
511196a4404SFangrui Song   if (Variants.empty())
5126540e570SSam Clegg     Variants.push_back(Sym);
5136540e570SSam Clegg 
5146540e570SSam Clegg   for (Symbol* V : Variants) {
5156540e570SSam Clegg     if (*V->getSignature() == *Sig) {
5166540e570SSam Clegg       Variant = V;
5176540e570SSam Clegg       break;
5186540e570SSam Clegg     }
5196540e570SSam Clegg   }
5206540e570SSam Clegg 
5216540e570SSam Clegg   bool WasAdded = !Variant;
5226540e570SSam Clegg   if (WasAdded) {
5236540e570SSam Clegg     // Create a new variant;
5246540e570SSam Clegg     LLVM_DEBUG(dbgs() << "added new variant\n");
5256540e570SSam Clegg     Variant = reinterpret_cast<Symbol *>(make<SymbolUnion>());
5266540e570SSam Clegg     Variants.push_back(Variant);
5276540e570SSam Clegg   } else {
5286540e570SSam Clegg     LLVM_DEBUG(dbgs() << "variant already exists: " << toString(*Variant) << "\n");
5296540e570SSam Clegg     assert(*Variant->getSignature() == *Sig);
5306540e570SSam Clegg   }
5316540e570SSam Clegg 
5326540e570SSam Clegg   *Out = Variant;
5336540e570SSam Clegg   return WasAdded;
5346540e570SSam Clegg }
5356540e570SSam Clegg 
5361f3f774fSSam Clegg // Set a flag for --trace-symbol so that we can print out a log message
5371f3f774fSSam Clegg // if a new symbol with the same name is inserted into the symbol table.
5381f3f774fSSam Clegg void SymbolTable::trace(StringRef Name) {
5391f3f774fSSam Clegg   SymMap.insert({CachedHashStringRef(Name), -1});
5401f3f774fSSam Clegg }
541230dc11dSSam Clegg 
542230dc11dSSam Clegg static const uint8_t UnreachableFn[] = {
543230dc11dSSam Clegg     0x03 /* ULEB length */, 0x00 /* ULEB num locals */,
544230dc11dSSam Clegg     0x00 /* opcode unreachable */, 0x0b /* opcode end */
545230dc11dSSam Clegg };
546230dc11dSSam Clegg 
547230dc11dSSam Clegg // Replace the given symbol body with an unreachable function.
548230dc11dSSam Clegg // This is used by handleWeakUndefines in order to generate a callable
5496540e570SSam Clegg // equivalent of an undefined function and also handleSymbolVariants for
5506540e570SSam Clegg // undefined functions that don't match the signature of the definition.
551230dc11dSSam Clegg InputFunction *SymbolTable::replaceWithUnreachable(Symbol *Sym,
552230dc11dSSam Clegg                                                    const WasmSignature &Sig,
553230dc11dSSam Clegg                                                    StringRef DebugName) {
554230dc11dSSam Clegg   auto *Func = make<SyntheticFunction>(Sig, Sym->getName(), DebugName);
555230dc11dSSam Clegg   Func->setBody(UnreachableFn);
556230dc11dSSam Clegg   SyntheticFunctions.emplace_back(Func);
5576540e570SSam Clegg   replaceSymbol<DefinedFunction>(Sym, Sym->getName(), Sym->getFlags(), nullptr,
5586540e570SSam Clegg                                  Func);
559230dc11dSSam Clegg   return Func;
560230dc11dSSam Clegg }
561230dc11dSSam Clegg 
562230dc11dSSam Clegg // For weak undefined functions, there may be "call" instructions that reference
563230dc11dSSam Clegg // the symbol. In this case, we need to synthesise a dummy/stub function that
564230dc11dSSam Clegg // will abort at runtime, so that relocations can still provided an operand to
565230dc11dSSam Clegg // the call instruction that passes Wasm validation.
566230dc11dSSam Clegg void SymbolTable::handleWeakUndefines() {
567230dc11dSSam Clegg   for (Symbol *Sym : getSymbols()) {
568230dc11dSSam Clegg     if (!Sym->isUndefWeak())
569230dc11dSSam Clegg       continue;
570230dc11dSSam Clegg 
5716540e570SSam Clegg     const WasmSignature *Sig = Sym->getSignature();
5726540e570SSam Clegg     if (!Sig) {
573230dc11dSSam Clegg       // It is possible for undefined functions not to have a signature (eg. if
574230dc11dSSam Clegg       // added via "--undefined"), but weak undefined ones do have a signature.
5756540e570SSam Clegg       // Lazy symbols may not be functions and therefore Sig can still be null
5766540e570SSam Clegg       // in some circumstantce.
5776540e570SSam Clegg       assert(!isa<FunctionSymbol>(Sym));
578230dc11dSSam Clegg       continue;
5796540e570SSam Clegg     }
580230dc11dSSam Clegg 
581230dc11dSSam Clegg     // Add a synthetic dummy for weak undefined functions.  These dummies will
582230dc11dSSam Clegg     // be GC'd if not used as the target of any "call" instructions.
583230dc11dSSam Clegg     StringRef DebugName = Saver.save("undefined:" + toString(*Sym));
584230dc11dSSam Clegg     InputFunction* Func = replaceWithUnreachable(Sym, *Sig, DebugName);
585230dc11dSSam Clegg     // Ensure it compares equal to the null pointer, and so that table relocs
586230dc11dSSam Clegg     // don't pull in the stub body (only call-operand relocs should do that).
587230dc11dSSam Clegg     Func->setTableIndex(0);
588230dc11dSSam Clegg     // Hide our dummy to prevent export.
589230dc11dSSam Clegg     Sym->setHidden(true);
590230dc11dSSam Clegg   }
591230dc11dSSam Clegg }
5926540e570SSam Clegg 
5936540e570SSam Clegg static void reportFunctionSignatureMismatch(StringRef SymName,
5946540e570SSam Clegg                                             FunctionSymbol *A,
5956540e570SSam Clegg                                             FunctionSymbol *B, bool Error) {
5966540e570SSam Clegg   std::string msg = ("function signature mismatch: " + SymName +
5976540e570SSam Clegg                      "\n>>> defined as " + toString(*A->Signature) + " in " +
5986540e570SSam Clegg                      toString(A->getFile()) + "\n>>> defined as " +
5996540e570SSam Clegg                      toString(*B->Signature) + " in " + toString(B->getFile()))
6006540e570SSam Clegg                         .str();
6016540e570SSam Clegg   if (Error)
6026540e570SSam Clegg     error(msg);
6036540e570SSam Clegg   else
6046540e570SSam Clegg     warn(msg);
6056540e570SSam Clegg }
6066540e570SSam Clegg 
6076540e570SSam Clegg // Remove any variant symbols that were created due to function signature
6086540e570SSam Clegg // mismatches.
6096540e570SSam Clegg void SymbolTable::handleSymbolVariants() {
6106540e570SSam Clegg   for (auto Pair : SymVariants) {
6116540e570SSam Clegg     // Push the initial symbol onto the list of variants.
6126540e570SSam Clegg     StringRef SymName = Pair.first.val();
6136540e570SSam Clegg     std::vector<Symbol *> &Variants = Pair.second;
6146540e570SSam Clegg 
6156540e570SSam Clegg #ifndef NDEBUG
616f8d736f1SSam Clegg     LLVM_DEBUG(dbgs() << "symbol with (" << Variants.size()
617f8d736f1SSam Clegg                       << ") variants: " << SymName << "\n");
6186540e570SSam Clegg     for (auto *S: Variants) {
6196540e570SSam Clegg       auto *F = cast<FunctionSymbol>(S);
620f8d736f1SSam Clegg       LLVM_DEBUG(dbgs() << " variant: " + F->getName() << " "
621f8d736f1SSam Clegg                         << toString(*F->Signature) << "\n");
6226540e570SSam Clegg     }
6236540e570SSam Clegg #endif
6246540e570SSam Clegg 
6256540e570SSam Clegg     // Find the one definition.
6266540e570SSam Clegg     DefinedFunction *Defined = nullptr;
6276540e570SSam Clegg     for (auto *Symbol : Variants) {
6286540e570SSam Clegg       if (auto F = dyn_cast<DefinedFunction>(Symbol)) {
6296540e570SSam Clegg         Defined = F;
6306540e570SSam Clegg         break;
6316540e570SSam Clegg       }
6326540e570SSam Clegg     }
6336540e570SSam Clegg 
6346540e570SSam Clegg     // If there are no definitions, and the undefined symbols disagree on
6356540e570SSam Clegg     // the signature, there is not we can do since we don't know which one
6366540e570SSam Clegg     // to use as the signature on the import.
6376540e570SSam Clegg     if (!Defined) {
6386540e570SSam Clegg       reportFunctionSignatureMismatch(SymName,
6396540e570SSam Clegg                                       cast<FunctionSymbol>(Variants[0]),
6406540e570SSam Clegg                                       cast<FunctionSymbol>(Variants[1]), true);
6416540e570SSam Clegg       return;
6426540e570SSam Clegg     }
6436540e570SSam Clegg 
6446540e570SSam Clegg     for (auto *Symbol : Variants) {
6456540e570SSam Clegg       if (Symbol != Defined) {
6466540e570SSam Clegg         auto *F = cast<FunctionSymbol>(Symbol);
6476540e570SSam Clegg         reportFunctionSignatureMismatch(SymName, F, Defined, false);
6486540e570SSam Clegg         StringRef DebugName = Saver.save("unreachable:" + toString(*F));
6496540e570SSam Clegg         replaceWithUnreachable(F, *F->Signature, DebugName);
6506540e570SSam Clegg       }
6516540e570SSam Clegg     }
6526540e570SSam Clegg   }
6536540e570SSam Clegg }
654