IRSymtab.cpp 15 KB

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