IRSymtab.cpp 15 KB

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