xref: /freebsd/contrib/llvm-project/llvm/lib/Object/IRSymtab.cpp (revision 38a52bd3b5cac3da6f7f6eef3dd050e6aa08ebb3)
1 //===- IRSymtab.cpp - implementation of IR symbol tables ------------------===//
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 "llvm/Object/IRSymtab.h"
10 #include "llvm/ADT/ArrayRef.h"
11 #include "llvm/ADT/DenseMap.h"
12 #include "llvm/ADT/SmallPtrSet.h"
13 #include "llvm/ADT/SmallString.h"
14 #include "llvm/ADT/SmallVector.h"
15 #include "llvm/ADT/StringRef.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/Bitcode/BitcodeReader.h"
18 #include "llvm/Config/llvm-config.h"
19 #include "llvm/IR/Comdat.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/GlobalAlias.h"
22 #include "llvm/IR/GlobalObject.h"
23 #include "llvm/IR/Mangler.h"
24 #include "llvm/IR/Metadata.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/MC/StringTableBuilder.h"
27 #include "llvm/Object/IRObjectFile.h"
28 #include "llvm/Object/ModuleSymbolTable.h"
29 #include "llvm/Object/SymbolicFile.h"
30 #include "llvm/Support/Allocator.h"
31 #include "llvm/Support/Casting.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Error.h"
34 #include "llvm/Support/StringSaver.h"
35 #include "llvm/Support/VCSRevision.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include <cassert>
38 #include <string>
39 #include <utility>
40 #include <vector>
41 
42 using namespace llvm;
43 using namespace irsymtab;
44 
45 cl::opt<bool> DisableBitcodeVersionUpgrade(
46     "disable-bitcode-version-upgrade", cl::init(false), cl::Hidden,
47     cl::desc("Disable automatic bitcode upgrade for version mismatch"));
48 
49 static const char *PreservedSymbols[] = {
50 #define HANDLE_LIBCALL(code, name) name,
51 #include "llvm/IR/RuntimeLibcalls.def"
52 #undef HANDLE_LIBCALL
53     // There are global variables, so put it here instead of in
54     // RuntimeLibcalls.def.
55     // TODO: Are there similar such variables?
56     "__ssp_canary_word",
57     "__stack_chk_guard",
58 };
59 
60 namespace {
61 
62 const char *getExpectedProducerName() {
63   static char DefaultName[] = LLVM_VERSION_STRING
64 #ifdef LLVM_REVISION
65       " " LLVM_REVISION
66 #endif
67       ;
68   // Allows for testing of the irsymtab writer and upgrade mechanism. This
69   // environment variable should not be set by users.
70   if (char *OverrideName = getenv("LLVM_OVERRIDE_PRODUCER"))
71     return OverrideName;
72   return DefaultName;
73 }
74 
75 const char *kExpectedProducerName = getExpectedProducerName();
76 
77 /// Stores the temporary state that is required to build an IR symbol table.
78 struct Builder {
79   SmallVector<char, 0> &Symtab;
80   StringTableBuilder &StrtabBuilder;
81   StringSaver Saver;
82 
83   // This ctor initializes a StringSaver using the passed in BumpPtrAllocator.
84   // The StringTableBuilder does not create a copy of any strings added to it,
85   // so this provides somewhere to store any strings that we create.
86   Builder(SmallVector<char, 0> &Symtab, StringTableBuilder &StrtabBuilder,
87           BumpPtrAllocator &Alloc)
88       : Symtab(Symtab), StrtabBuilder(StrtabBuilder), Saver(Alloc) {}
89 
90   DenseMap<const Comdat *, int> ComdatMap;
91   Mangler Mang;
92   Triple TT;
93 
94   std::vector<storage::Comdat> Comdats;
95   std::vector<storage::Module> Mods;
96   std::vector<storage::Symbol> Syms;
97   std::vector<storage::Uncommon> Uncommons;
98 
99   std::string COFFLinkerOpts;
100   raw_string_ostream COFFLinkerOptsOS{COFFLinkerOpts};
101 
102   std::vector<storage::Str> DependentLibraries;
103 
104   void setStr(storage::Str &S, StringRef Value) {
105     S.Offset = StrtabBuilder.add(Value);
106     S.Size = Value.size();
107   }
108 
109   template <typename T>
110   void writeRange(storage::Range<T> &R, const std::vector<T> &Objs) {
111     R.Offset = Symtab.size();
112     R.Size = Objs.size();
113     Symtab.insert(Symtab.end(), reinterpret_cast<const char *>(Objs.data()),
114                   reinterpret_cast<const char *>(Objs.data() + Objs.size()));
115   }
116 
117   Expected<int> getComdatIndex(const Comdat *C, const Module *M);
118 
119   Error addModule(Module *M);
120   Error addSymbol(const ModuleSymbolTable &Msymtab,
121                   const SmallPtrSet<GlobalValue *, 4> &Used,
122                   ModuleSymbolTable::Symbol Sym);
123 
124   Error build(ArrayRef<Module *> Mods);
125 };
126 
127 Error Builder::addModule(Module *M) {
128   if (M->getDataLayoutStr().empty())
129     return make_error<StringError>("input module has no datalayout",
130                                    inconvertibleErrorCode());
131 
132   // Symbols in the llvm.used list will get the FB_Used bit and will not be
133   // internalized. We do this for llvm.compiler.used as well:
134   //
135   // IR symbol table tracks module-level asm symbol references but not inline
136   // asm. A symbol only referenced by inline asm is not in the IR symbol table,
137   // so we may not know that the definition (in another translation unit) is
138   // referenced. That definition may have __attribute__((used)) (which lowers to
139   // llvm.compiler.used on ELF targets) to communicate to the compiler that it
140   // may be used by inline asm. The usage is perfectly fine, so we treat
141   // llvm.compiler.used conservatively as llvm.used to work around our own
142   // limitation.
143   SmallVector<GlobalValue *, 4> UsedV;
144   collectUsedGlobalVariables(*M, UsedV, /*CompilerUsed=*/false);
145   collectUsedGlobalVariables(*M, UsedV, /*CompilerUsed=*/true);
146   SmallPtrSet<GlobalValue *, 4> Used(UsedV.begin(), UsedV.end());
147 
148   ModuleSymbolTable Msymtab;
149   Msymtab.addModule(M);
150 
151   storage::Module Mod;
152   Mod.Begin = Syms.size();
153   Mod.End = Syms.size() + Msymtab.symbols().size();
154   Mod.UncBegin = Uncommons.size();
155   Mods.push_back(Mod);
156 
157   if (TT.isOSBinFormatCOFF()) {
158     if (auto E = M->materializeMetadata())
159       return E;
160     if (NamedMDNode *LinkerOptions =
161             M->getNamedMetadata("llvm.linker.options")) {
162       for (MDNode *MDOptions : LinkerOptions->operands())
163         for (const MDOperand &MDOption : cast<MDNode>(MDOptions)->operands())
164           COFFLinkerOptsOS << " " << cast<MDString>(MDOption)->getString();
165     }
166   }
167 
168   if (TT.isOSBinFormatELF()) {
169     if (auto E = M->materializeMetadata())
170       return E;
171     if (NamedMDNode *N = M->getNamedMetadata("llvm.dependent-libraries")) {
172       for (MDNode *MDOptions : N->operands()) {
173         const auto OperandStr =
174             cast<MDString>(cast<MDNode>(MDOptions)->getOperand(0))->getString();
175         storage::Str Specifier;
176         setStr(Specifier, OperandStr);
177         DependentLibraries.emplace_back(Specifier);
178       }
179     }
180   }
181 
182   for (ModuleSymbolTable::Symbol Msym : Msymtab.symbols())
183     if (Error Err = addSymbol(Msymtab, Used, Msym))
184       return Err;
185 
186   return Error::success();
187 }
188 
189 Expected<int> Builder::getComdatIndex(const Comdat *C, const Module *M) {
190   auto P = ComdatMap.insert(std::make_pair(C, Comdats.size()));
191   if (P.second) {
192     std::string Name;
193     if (TT.isOSBinFormatCOFF()) {
194       const GlobalValue *GV = M->getNamedValue(C->getName());
195       if (!GV)
196         return make_error<StringError>("Could not find leader",
197                                        inconvertibleErrorCode());
198       // Internal leaders do not affect symbol resolution, therefore they do not
199       // appear in the symbol table.
200       if (GV->hasLocalLinkage()) {
201         P.first->second = -1;
202         return -1;
203       }
204       llvm::raw_string_ostream OS(Name);
205       Mang.getNameWithPrefix(OS, GV, false);
206     } else {
207       Name = std::string(C->getName());
208     }
209 
210     storage::Comdat Comdat;
211     setStr(Comdat.Name, Saver.save(Name));
212     Comdat.SelectionKind = C->getSelectionKind();
213     Comdats.push_back(Comdat);
214   }
215 
216   return P.first->second;
217 }
218 
219 Error Builder::addSymbol(const ModuleSymbolTable &Msymtab,
220                          const SmallPtrSet<GlobalValue *, 4> &Used,
221                          ModuleSymbolTable::Symbol Msym) {
222   Syms.emplace_back();
223   storage::Symbol &Sym = Syms.back();
224   Sym = {};
225 
226   storage::Uncommon *Unc = nullptr;
227   auto Uncommon = [&]() -> storage::Uncommon & {
228     if (Unc)
229       return *Unc;
230     Sym.Flags |= 1 << storage::Symbol::FB_has_uncommon;
231     Uncommons.emplace_back();
232     Unc = &Uncommons.back();
233     *Unc = {};
234     setStr(Unc->COFFWeakExternFallbackName, "");
235     setStr(Unc->SectionName, "");
236     return *Unc;
237   };
238 
239   SmallString<64> Name;
240   {
241     raw_svector_ostream OS(Name);
242     Msymtab.printSymbolName(OS, Msym);
243   }
244   setStr(Sym.Name, Saver.save(Name.str()));
245 
246   auto Flags = Msymtab.getSymbolFlags(Msym);
247   if (Flags & object::BasicSymbolRef::SF_Undefined)
248     Sym.Flags |= 1 << storage::Symbol::FB_undefined;
249   if (Flags & object::BasicSymbolRef::SF_Weak)
250     Sym.Flags |= 1 << storage::Symbol::FB_weak;
251   if (Flags & object::BasicSymbolRef::SF_Common)
252     Sym.Flags |= 1 << storage::Symbol::FB_common;
253   if (Flags & object::BasicSymbolRef::SF_Indirect)
254     Sym.Flags |= 1 << storage::Symbol::FB_indirect;
255   if (Flags & object::BasicSymbolRef::SF_Global)
256     Sym.Flags |= 1 << storage::Symbol::FB_global;
257   if (Flags & object::BasicSymbolRef::SF_FormatSpecific)
258     Sym.Flags |= 1 << storage::Symbol::FB_format_specific;
259   if (Flags & object::BasicSymbolRef::SF_Executable)
260     Sym.Flags |= 1 << storage::Symbol::FB_executable;
261 
262   Sym.ComdatIndex = -1;
263   auto *GV = Msym.dyn_cast<GlobalValue *>();
264   if (!GV) {
265     // Undefined module asm symbols act as GC roots and are implicitly used.
266     if (Flags & object::BasicSymbolRef::SF_Undefined)
267       Sym.Flags |= 1 << storage::Symbol::FB_used;
268     setStr(Sym.IRName, "");
269     return Error::success();
270   }
271 
272   setStr(Sym.IRName, GV->getName());
273 
274   bool IsPreservedSymbol = llvm::is_contained(PreservedSymbols, GV->getName());
275 
276   if (Used.count(GV) || IsPreservedSymbol)
277     Sym.Flags |= 1 << storage::Symbol::FB_used;
278   if (GV->isThreadLocal())
279     Sym.Flags |= 1 << storage::Symbol::FB_tls;
280   if (GV->hasGlobalUnnamedAddr())
281     Sym.Flags |= 1 << storage::Symbol::FB_unnamed_addr;
282   if (GV->canBeOmittedFromSymbolTable())
283     Sym.Flags |= 1 << storage::Symbol::FB_may_omit;
284   Sym.Flags |= unsigned(GV->getVisibility()) << storage::Symbol::FB_visibility;
285 
286   if (Flags & object::BasicSymbolRef::SF_Common) {
287     auto *GVar = dyn_cast<GlobalVariable>(GV);
288     if (!GVar)
289       return make_error<StringError>("Only variables can have common linkage!",
290                                      inconvertibleErrorCode());
291     Uncommon().CommonSize =
292         GV->getParent()->getDataLayout().getTypeAllocSize(GV->getValueType());
293     Uncommon().CommonAlign = GVar->getAlignment();
294   }
295 
296   const GlobalObject *GO = GV->getAliaseeObject();
297   if (!GO) {
298     if (isa<GlobalIFunc>(GV))
299       GO = cast<GlobalIFunc>(GV)->getResolverFunction();
300     if (!GO)
301       return make_error<StringError>("Unable to determine comdat of alias!",
302                                      inconvertibleErrorCode());
303   }
304   if (const Comdat *C = GO->getComdat()) {
305     Expected<int> ComdatIndexOrErr = getComdatIndex(C, GV->getParent());
306     if (!ComdatIndexOrErr)
307       return ComdatIndexOrErr.takeError();
308     Sym.ComdatIndex = *ComdatIndexOrErr;
309   }
310 
311   if (TT.isOSBinFormatCOFF()) {
312     emitLinkerFlagsForGlobalCOFF(COFFLinkerOptsOS, GV, TT, Mang);
313 
314     if ((Flags & object::BasicSymbolRef::SF_Weak) &&
315         (Flags & object::BasicSymbolRef::SF_Indirect)) {
316       auto *Fallback = dyn_cast<GlobalValue>(
317           cast<GlobalAlias>(GV)->getAliasee()->stripPointerCasts());
318       if (!Fallback)
319         return make_error<StringError>("Invalid weak external",
320                                        inconvertibleErrorCode());
321       std::string FallbackName;
322       raw_string_ostream OS(FallbackName);
323       Msymtab.printSymbolName(OS, Fallback);
324       OS.flush();
325       setStr(Uncommon().COFFWeakExternFallbackName, Saver.save(FallbackName));
326     }
327   }
328 
329   if (!GO->getSection().empty())
330     setStr(Uncommon().SectionName, Saver.save(GO->getSection()));
331 
332   return Error::success();
333 }
334 
335 Error Builder::build(ArrayRef<Module *> IRMods) {
336   storage::Header Hdr;
337 
338   assert(!IRMods.empty());
339   Hdr.Version = storage::Header::kCurrentVersion;
340   setStr(Hdr.Producer, kExpectedProducerName);
341   setStr(Hdr.TargetTriple, IRMods[0]->getTargetTriple());
342   setStr(Hdr.SourceFileName, IRMods[0]->getSourceFileName());
343   TT = Triple(IRMods[0]->getTargetTriple());
344 
345   for (auto *M : IRMods)
346     if (Error Err = addModule(M))
347       return Err;
348 
349   COFFLinkerOptsOS.flush();
350   setStr(Hdr.COFFLinkerOpts, Saver.save(COFFLinkerOpts));
351 
352   // We are about to fill in the header's range fields, so reserve space for it
353   // and copy it in afterwards.
354   Symtab.resize(sizeof(storage::Header));
355   writeRange(Hdr.Modules, Mods);
356   writeRange(Hdr.Comdats, Comdats);
357   writeRange(Hdr.Symbols, Syms);
358   writeRange(Hdr.Uncommons, Uncommons);
359   writeRange(Hdr.DependentLibraries, DependentLibraries);
360   *reinterpret_cast<storage::Header *>(Symtab.data()) = Hdr;
361   return Error::success();
362 }
363 
364 } // end anonymous namespace
365 
366 Error irsymtab::build(ArrayRef<Module *> Mods, SmallVector<char, 0> &Symtab,
367                       StringTableBuilder &StrtabBuilder,
368                       BumpPtrAllocator &Alloc) {
369   return Builder(Symtab, StrtabBuilder, Alloc).build(Mods);
370 }
371 
372 // Upgrade a vector of bitcode modules created by an old version of LLVM by
373 // creating an irsymtab for them in the current format.
374 static Expected<FileContents> upgrade(ArrayRef<BitcodeModule> BMs) {
375   FileContents FC;
376 
377   LLVMContext Ctx;
378   std::vector<Module *> Mods;
379   std::vector<std::unique_ptr<Module>> OwnedMods;
380   for (auto BM : BMs) {
381     Expected<std::unique_ptr<Module>> MOrErr =
382         BM.getLazyModule(Ctx, /*ShouldLazyLoadMetadata*/ true,
383                          /*IsImporting*/ false);
384     if (!MOrErr)
385       return MOrErr.takeError();
386 
387     Mods.push_back(MOrErr->get());
388     OwnedMods.push_back(std::move(*MOrErr));
389   }
390 
391   StringTableBuilder StrtabBuilder(StringTableBuilder::RAW);
392   BumpPtrAllocator Alloc;
393   if (Error E = build(Mods, FC.Symtab, StrtabBuilder, Alloc))
394     return std::move(E);
395 
396   StrtabBuilder.finalizeInOrder();
397   FC.Strtab.resize(StrtabBuilder.getSize());
398   StrtabBuilder.write((uint8_t *)FC.Strtab.data());
399 
400   FC.TheReader = {{FC.Symtab.data(), FC.Symtab.size()},
401                   {FC.Strtab.data(), FC.Strtab.size()}};
402   return std::move(FC);
403 }
404 
405 Expected<FileContents> irsymtab::readBitcode(const BitcodeFileContents &BFC) {
406   if (BFC.Mods.empty())
407     return make_error<StringError>("Bitcode file does not contain any modules",
408                                    inconvertibleErrorCode());
409 
410   if (!DisableBitcodeVersionUpgrade) {
411     if (BFC.StrtabForSymtab.empty() ||
412         BFC.Symtab.size() < sizeof(storage::Header))
413       return upgrade(BFC.Mods);
414 
415     // We cannot use the regular reader to read the version and producer,
416     // because it will expect the header to be in the current format. The only
417     // thing we can rely on is that the version and producer will be present as
418     // the first struct elements.
419     auto *Hdr = reinterpret_cast<const storage::Header *>(BFC.Symtab.data());
420     unsigned Version = Hdr->Version;
421     StringRef Producer = Hdr->Producer.get(BFC.StrtabForSymtab);
422     if (Version != storage::Header::kCurrentVersion ||
423         Producer != kExpectedProducerName)
424       return upgrade(BFC.Mods);
425   }
426 
427   FileContents FC;
428   FC.TheReader = {{BFC.Symtab.data(), BFC.Symtab.size()},
429                   {BFC.StrtabForSymtab.data(), BFC.StrtabForSymtab.size()}};
430 
431   // Finally, make sure that the number of modules in the symbol table matches
432   // the number of modules in the bitcode file. If they differ, it may mean that
433   // the bitcode file was created by binary concatenation, so we need to create
434   // a new symbol table from scratch.
435   if (FC.TheReader.getNumModules() != BFC.Mods.size())
436     return upgrade(std::move(BFC.Mods));
437 
438   return std::move(FC);
439 }
440