Module.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. //===- Module.cpp - Implement the Module class ----------------------------===//
  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. // This file implements the Module class for the IR library.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/IR/Module.h"
  13. #include "SymbolTableListTraitsImpl.h"
  14. #include "llvm/ADT/Optional.h"
  15. #include "llvm/ADT/SmallPtrSet.h"
  16. #include "llvm/ADT/SmallString.h"
  17. #include "llvm/ADT/SmallVector.h"
  18. #include "llvm/ADT/StringMap.h"
  19. #include "llvm/ADT/StringRef.h"
  20. #include "llvm/ADT/Twine.h"
  21. #include "llvm/IR/Attributes.h"
  22. #include "llvm/IR/Comdat.h"
  23. #include "llvm/IR/Constants.h"
  24. #include "llvm/IR/DataLayout.h"
  25. #include "llvm/IR/DebugInfoMetadata.h"
  26. #include "llvm/IR/DerivedTypes.h"
  27. #include "llvm/IR/Function.h"
  28. #include "llvm/IR/GVMaterializer.h"
  29. #include "llvm/IR/GlobalAlias.h"
  30. #include "llvm/IR/GlobalIFunc.h"
  31. #include "llvm/IR/GlobalValue.h"
  32. #include "llvm/IR/GlobalVariable.h"
  33. #include "llvm/IR/LLVMContext.h"
  34. #include "llvm/IR/Metadata.h"
  35. #include "llvm/IR/SymbolTableListTraits.h"
  36. #include "llvm/IR/Type.h"
  37. #include "llvm/IR/TypeFinder.h"
  38. #include "llvm/IR/Value.h"
  39. #include "llvm/IR/ValueSymbolTable.h"
  40. #include "llvm/Pass.h"
  41. #include "llvm/Support/Casting.h"
  42. #include "llvm/Support/CodeGen.h"
  43. #include "llvm/Support/Error.h"
  44. #include "llvm/Support/MemoryBuffer.h"
  45. #include "llvm/Support/Path.h"
  46. #include "llvm/Support/RandomNumberGenerator.h"
  47. #include "llvm/Support/VersionTuple.h"
  48. #include <algorithm>
  49. #include <cassert>
  50. #include <cstdint>
  51. #include <memory>
  52. #include <utility>
  53. #include <vector>
  54. using namespace llvm;
  55. //===----------------------------------------------------------------------===//
  56. // Methods to implement the globals and functions lists.
  57. //
  58. // Explicit instantiations of SymbolTableListTraits since some of the methods
  59. // are not in the public header file.
  60. template class llvm::SymbolTableListTraits<Function>;
  61. template class llvm::SymbolTableListTraits<GlobalVariable>;
  62. template class llvm::SymbolTableListTraits<GlobalAlias>;
  63. template class llvm::SymbolTableListTraits<GlobalIFunc>;
  64. //===----------------------------------------------------------------------===//
  65. // Primitive Module methods.
  66. //
  67. Module::Module(StringRef MID, LLVMContext &C)
  68. : Context(C), Materializer(), ModuleID(MID), SourceFileName(MID), DL("") {
  69. ValSymTab = new ValueSymbolTable();
  70. NamedMDSymTab = new StringMap<NamedMDNode *>();
  71. Context.addModule(this);
  72. }
  73. Module::~Module() {
  74. Context.removeModule(this);
  75. dropAllReferences();
  76. GlobalList.clear();
  77. FunctionList.clear();
  78. AliasList.clear();
  79. IFuncList.clear();
  80. NamedMDList.clear();
  81. delete ValSymTab;
  82. delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
  83. }
  84. std::unique_ptr<RandomNumberGenerator> Module::createRNG(const Pass* P) const {
  85. SmallString<32> Salt(P->getPassName());
  86. // This RNG is guaranteed to produce the same random stream only
  87. // when the Module ID and thus the input filename is the same. This
  88. // might be problematic if the input filename extension changes
  89. // (e.g. from .c to .bc or .ll).
  90. //
  91. // We could store this salt in NamedMetadata, but this would make
  92. // the parameter non-const. This would unfortunately make this
  93. // interface unusable by any Machine passes, since they only have a
  94. // const reference to their IR Module. Alternatively we can always
  95. // store salt metadata from the Module constructor.
  96. Salt += sys::path::filename(getModuleIdentifier());
  97. return std::unique_ptr<RandomNumberGenerator>(new RandomNumberGenerator(Salt));
  98. }
  99. /// getNamedValue - Return the first global value in the module with
  100. /// the specified name, of arbitrary type. This method returns null
  101. /// if a global with the specified name is not found.
  102. GlobalValue *Module::getNamedValue(StringRef Name) const {
  103. return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
  104. }
  105. /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
  106. /// This ID is uniqued across modules in the current LLVMContext.
  107. unsigned Module::getMDKindID(StringRef Name) const {
  108. return Context.getMDKindID(Name);
  109. }
  110. /// getMDKindNames - Populate client supplied SmallVector with the name for
  111. /// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
  112. /// so it is filled in as an empty string.
  113. void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
  114. return Context.getMDKindNames(Result);
  115. }
  116. void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const {
  117. return Context.getOperandBundleTags(Result);
  118. }
  119. //===----------------------------------------------------------------------===//
  120. // Methods for easy access to the functions in the module.
  121. //
  122. // getOrInsertFunction - Look up the specified function in the module symbol
  123. // table. If it does not exist, add a prototype for the function and return
  124. // it. This is nice because it allows most passes to get away with not handling
  125. // the symbol table directly for this common task.
  126. //
  127. FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty,
  128. AttributeList AttributeList) {
  129. // See if we have a definition for the specified function already.
  130. GlobalValue *F = getNamedValue(Name);
  131. if (!F) {
  132. // Nope, add it
  133. Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage,
  134. DL.getProgramAddressSpace(), Name);
  135. if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
  136. New->setAttributes(AttributeList);
  137. FunctionList.push_back(New);
  138. return {Ty, New}; // Return the new prototype.
  139. }
  140. // If the function exists but has the wrong type, return a bitcast to the
  141. // right type.
  142. auto *PTy = PointerType::get(Ty, F->getAddressSpace());
  143. if (F->getType() != PTy)
  144. return {Ty, ConstantExpr::getBitCast(F, PTy)};
  145. // Otherwise, we just found the existing function or a prototype.
  146. return {Ty, F};
  147. }
  148. FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty) {
  149. return getOrInsertFunction(Name, Ty, AttributeList());
  150. }
  151. // getFunction - Look up the specified function in the module symbol table.
  152. // If it does not exist, return null.
  153. //
  154. Function *Module::getFunction(StringRef Name) const {
  155. return dyn_cast_or_null<Function>(getNamedValue(Name));
  156. }
  157. //===----------------------------------------------------------------------===//
  158. // Methods for easy access to the global variables in the module.
  159. //
  160. /// getGlobalVariable - Look up the specified global variable in the module
  161. /// symbol table. If it does not exist, return null. The type argument
  162. /// should be the underlying type of the global, i.e., it should not have
  163. /// the top-level PointerType, which represents the address of the global.
  164. /// If AllowLocal is set to true, this function will return types that
  165. /// have an local. By default, these types are not returned.
  166. ///
  167. GlobalVariable *Module::getGlobalVariable(StringRef Name,
  168. bool AllowLocal) const {
  169. if (GlobalVariable *Result =
  170. dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
  171. if (AllowLocal || !Result->hasLocalLinkage())
  172. return Result;
  173. return nullptr;
  174. }
  175. /// getOrInsertGlobal - Look up the specified global in the module symbol table.
  176. /// 1. If it does not exist, add a declaration of the global and return it.
  177. /// 2. Else, the global exists but has the wrong type: return the function
  178. /// with a constantexpr cast to the right type.
  179. /// 3. Finally, if the existing global is the correct declaration, return the
  180. /// existing global.
  181. Constant *Module::getOrInsertGlobal(
  182. StringRef Name, Type *Ty,
  183. function_ref<GlobalVariable *()> CreateGlobalCallback) {
  184. // See if we have a definition for the specified global already.
  185. GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
  186. if (!GV)
  187. GV = CreateGlobalCallback();
  188. assert(GV && "The CreateGlobalCallback is expected to create a global");
  189. // If the variable exists but has the wrong type, return a bitcast to the
  190. // right type.
  191. Type *GVTy = GV->getType();
  192. PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
  193. if (GVTy != PTy)
  194. return ConstantExpr::getBitCast(GV, PTy);
  195. // Otherwise, we just found the existing function or a prototype.
  196. return GV;
  197. }
  198. // Overload to construct a global variable using its constructor's defaults.
  199. Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
  200. return getOrInsertGlobal(Name, Ty, [&] {
  201. return new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
  202. nullptr, Name);
  203. });
  204. }
  205. //===----------------------------------------------------------------------===//
  206. // Methods for easy access to the global variables in the module.
  207. //
  208. // getNamedAlias - Look up the specified global in the module symbol table.
  209. // If it does not exist, return null.
  210. //
  211. GlobalAlias *Module::getNamedAlias(StringRef Name) const {
  212. return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
  213. }
  214. GlobalIFunc *Module::getNamedIFunc(StringRef Name) const {
  215. return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name));
  216. }
  217. /// getNamedMetadata - Return the first NamedMDNode in the module with the
  218. /// specified name. This method returns null if a NamedMDNode with the
  219. /// specified name is not found.
  220. NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
  221. SmallString<256> NameData;
  222. StringRef NameRef = Name.toStringRef(NameData);
  223. return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
  224. }
  225. /// getOrInsertNamedMetadata - Return the first named MDNode in the module
  226. /// with the specified name. This method returns a new NamedMDNode if a
  227. /// NamedMDNode with the specified name is not found.
  228. NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
  229. NamedMDNode *&NMD =
  230. (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
  231. if (!NMD) {
  232. NMD = new NamedMDNode(Name);
  233. NMD->setParent(this);
  234. NamedMDList.push_back(NMD);
  235. }
  236. return NMD;
  237. }
  238. /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
  239. /// delete it.
  240. void Module::eraseNamedMetadata(NamedMDNode *NMD) {
  241. static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
  242. NamedMDList.erase(NMD->getIterator());
  243. }
  244. bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
  245. if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
  246. uint64_t Val = Behavior->getLimitedValue();
  247. if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
  248. MFB = static_cast<ModFlagBehavior>(Val);
  249. return true;
  250. }
  251. }
  252. return false;
  253. }
  254. /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
  255. void Module::
  256. getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
  257. const NamedMDNode *ModFlags = getModuleFlagsMetadata();
  258. if (!ModFlags) return;
  259. for (const MDNode *Flag : ModFlags->operands()) {
  260. ModFlagBehavior MFB;
  261. if (Flag->getNumOperands() >= 3 &&
  262. isValidModFlagBehavior(Flag->getOperand(0), MFB) &&
  263. dyn_cast_or_null<MDString>(Flag->getOperand(1))) {
  264. // Check the operands of the MDNode before accessing the operands.
  265. // The verifier will actually catch these failures.
  266. MDString *Key = cast<MDString>(Flag->getOperand(1));
  267. Metadata *Val = Flag->getOperand(2);
  268. Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
  269. }
  270. }
  271. }
  272. /// Return the corresponding value if Key appears in module flags, otherwise
  273. /// return null.
  274. Metadata *Module::getModuleFlag(StringRef Key) const {
  275. SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
  276. getModuleFlagsMetadata(ModuleFlags);
  277. for (const ModuleFlagEntry &MFE : ModuleFlags) {
  278. if (Key == MFE.Key->getString())
  279. return MFE.Val;
  280. }
  281. return nullptr;
  282. }
  283. /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
  284. /// represents module-level flags. This method returns null if there are no
  285. /// module-level flags.
  286. NamedMDNode *Module::getModuleFlagsMetadata() const {
  287. return getNamedMetadata("llvm.module.flags");
  288. }
  289. /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
  290. /// represents module-level flags. If module-level flags aren't found, it
  291. /// creates the named metadata that contains them.
  292. NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
  293. return getOrInsertNamedMetadata("llvm.module.flags");
  294. }
  295. /// addModuleFlag - Add a module-level flag to the module-level flags
  296. /// metadata. It will create the module-level flags named metadata if it doesn't
  297. /// already exist.
  298. void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
  299. Metadata *Val) {
  300. Type *Int32Ty = Type::getInt32Ty(Context);
  301. Metadata *Ops[3] = {
  302. ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
  303. MDString::get(Context, Key), Val};
  304. getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
  305. }
  306. void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
  307. Constant *Val) {
  308. addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
  309. }
  310. void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
  311. uint32_t Val) {
  312. Type *Int32Ty = Type::getInt32Ty(Context);
  313. addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
  314. }
  315. void Module::addModuleFlag(MDNode *Node) {
  316. assert(Node->getNumOperands() == 3 &&
  317. "Invalid number of operands for module flag!");
  318. assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
  319. isa<MDString>(Node->getOperand(1)) &&
  320. "Invalid operand types for module flag!");
  321. getOrInsertModuleFlagsMetadata()->addOperand(Node);
  322. }
  323. void Module::setDataLayout(StringRef Desc) {
  324. DL.reset(Desc);
  325. }
  326. void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
  327. const DataLayout &Module::getDataLayout() const { return DL; }
  328. DICompileUnit *Module::debug_compile_units_iterator::operator*() const {
  329. return cast<DICompileUnit>(CUs->getOperand(Idx));
  330. }
  331. DICompileUnit *Module::debug_compile_units_iterator::operator->() const {
  332. return cast<DICompileUnit>(CUs->getOperand(Idx));
  333. }
  334. void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
  335. while (CUs && (Idx < CUs->getNumOperands()) &&
  336. ((*this)->getEmissionKind() == DICompileUnit::NoDebug))
  337. ++Idx;
  338. }
  339. //===----------------------------------------------------------------------===//
  340. // Methods to control the materialization of GlobalValues in the Module.
  341. //
  342. void Module::setMaterializer(GVMaterializer *GVM) {
  343. assert(!Materializer &&
  344. "Module already has a GVMaterializer. Call materializeAll"
  345. " to clear it out before setting another one.");
  346. Materializer.reset(GVM);
  347. }
  348. Error Module::materialize(GlobalValue *GV) {
  349. if (!Materializer)
  350. return Error::success();
  351. return Materializer->materialize(GV);
  352. }
  353. Error Module::materializeAll() {
  354. if (!Materializer)
  355. return Error::success();
  356. std::unique_ptr<GVMaterializer> M = std::move(Materializer);
  357. return M->materializeModule();
  358. }
  359. Error Module::materializeMetadata() {
  360. if (!Materializer)
  361. return Error::success();
  362. return Materializer->materializeMetadata();
  363. }
  364. //===----------------------------------------------------------------------===//
  365. // Other module related stuff.
  366. //
  367. std::vector<StructType *> Module::getIdentifiedStructTypes() const {
  368. // If we have a materializer, it is possible that some unread function
  369. // uses a type that is currently not visible to a TypeFinder, so ask
  370. // the materializer which types it created.
  371. if (Materializer)
  372. return Materializer->getIdentifiedStructTypes();
  373. std::vector<StructType *> Ret;
  374. TypeFinder SrcStructTypes;
  375. SrcStructTypes.run(*this, true);
  376. Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
  377. return Ret;
  378. }
  379. // dropAllReferences() - This function causes all the subelements to "let go"
  380. // of all references that they are maintaining. This allows one to 'delete' a
  381. // whole module at a time, even though there may be circular references... first
  382. // all references are dropped, and all use counts go to zero. Then everything
  383. // is deleted for real. Note that no operations are valid on an object that
  384. // has "dropped all references", except operator delete.
  385. //
  386. void Module::dropAllReferences() {
  387. for (Function &F : *this)
  388. F.dropAllReferences();
  389. for (GlobalVariable &GV : globals())
  390. GV.dropAllReferences();
  391. for (GlobalAlias &GA : aliases())
  392. GA.dropAllReferences();
  393. for (GlobalIFunc &GIF : ifuncs())
  394. GIF.dropAllReferences();
  395. }
  396. unsigned Module::getNumberRegisterParameters() const {
  397. auto *Val =
  398. cast_or_null<ConstantAsMetadata>(getModuleFlag("NumRegisterParameters"));
  399. if (!Val)
  400. return 0;
  401. return cast<ConstantInt>(Val->getValue())->getZExtValue();
  402. }
  403. unsigned Module::getDwarfVersion() const {
  404. auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
  405. if (!Val)
  406. return 0;
  407. return cast<ConstantInt>(Val->getValue())->getZExtValue();
  408. }
  409. unsigned Module::getCodeViewFlag() const {
  410. auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
  411. if (!Val)
  412. return 0;
  413. return cast<ConstantInt>(Val->getValue())->getZExtValue();
  414. }
  415. unsigned Module::getInstructionCount() {
  416. unsigned NumInstrs = 0;
  417. for (Function &F : FunctionList)
  418. NumInstrs += F.getInstructionCount();
  419. return NumInstrs;
  420. }
  421. Comdat *Module::getOrInsertComdat(StringRef Name) {
  422. auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
  423. Entry.second.Name = &Entry;
  424. return &Entry.second;
  425. }
  426. PICLevel::Level Module::getPICLevel() const {
  427. auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
  428. if (!Val)
  429. return PICLevel::NotPIC;
  430. return static_cast<PICLevel::Level>(
  431. cast<ConstantInt>(Val->getValue())->getZExtValue());
  432. }
  433. void Module::setPICLevel(PICLevel::Level PL) {
  434. addModuleFlag(ModFlagBehavior::Max, "PIC Level", PL);
  435. }
  436. PIELevel::Level Module::getPIELevel() const {
  437. auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level"));
  438. if (!Val)
  439. return PIELevel::Default;
  440. return static_cast<PIELevel::Level>(
  441. cast<ConstantInt>(Val->getValue())->getZExtValue());
  442. }
  443. void Module::setPIELevel(PIELevel::Level PL) {
  444. addModuleFlag(ModFlagBehavior::Max, "PIE Level", PL);
  445. }
  446. Optional<CodeModel::Model> Module::getCodeModel() const {
  447. auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Code Model"));
  448. if (!Val)
  449. return None;
  450. return static_cast<CodeModel::Model>(
  451. cast<ConstantInt>(Val->getValue())->getZExtValue());
  452. }
  453. void Module::setCodeModel(CodeModel::Model CL) {
  454. // Linking object files with different code models is undefined behavior
  455. // because the compiler would have to generate additional code (to span
  456. // longer jumps) if a larger code model is used with a smaller one.
  457. // Therefore we will treat attempts to mix code models as an error.
  458. addModuleFlag(ModFlagBehavior::Error, "Code Model", CL);
  459. }
  460. void Module::setProfileSummary(Metadata *M) {
  461. addModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M);
  462. }
  463. Metadata *Module::getProfileSummary() {
  464. return getModuleFlag("ProfileSummary");
  465. }
  466. void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) {
  467. OwnedMemoryBuffer = std::move(MB);
  468. }
  469. bool Module::getRtLibUseGOT() const {
  470. auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("RtLibUseGOT"));
  471. return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0);
  472. }
  473. void Module::setRtLibUseGOT() {
  474. addModuleFlag(ModFlagBehavior::Max, "RtLibUseGOT", 1);
  475. }
  476. void Module::setSDKVersion(const VersionTuple &V) {
  477. SmallVector<unsigned, 3> Entries;
  478. Entries.push_back(V.getMajor());
  479. if (auto Minor = V.getMinor()) {
  480. Entries.push_back(*Minor);
  481. if (auto Subminor = V.getSubminor())
  482. Entries.push_back(*Subminor);
  483. // Ignore the 'build' component as it can't be represented in the object
  484. // file.
  485. }
  486. addModuleFlag(ModFlagBehavior::Warning, "SDK Version",
  487. ConstantDataArray::get(Context, Entries));
  488. }
  489. VersionTuple Module::getSDKVersion() const {
  490. auto *CM = dyn_cast_or_null<ConstantAsMetadata>(getModuleFlag("SDK Version"));
  491. if (!CM)
  492. return {};
  493. auto *Arr = dyn_cast_or_null<ConstantDataArray>(CM->getValue());
  494. if (!Arr)
  495. return {};
  496. auto getVersionComponent = [&](unsigned Index) -> Optional<unsigned> {
  497. if (Index >= Arr->getNumElements())
  498. return None;
  499. return (unsigned)Arr->getElementAsInteger(Index);
  500. };
  501. auto Major = getVersionComponent(0);
  502. if (!Major)
  503. return {};
  504. VersionTuple Result = VersionTuple(*Major);
  505. if (auto Minor = getVersionComponent(1)) {
  506. Result = VersionTuple(*Major, *Minor);
  507. if (auto Subminor = getVersionComponent(2)) {
  508. Result = VersionTuple(*Major, *Minor, *Subminor);
  509. }
  510. }
  511. return Result;
  512. }
  513. GlobalVariable *llvm::collectUsedGlobalVariables(
  514. const Module &M, SmallPtrSetImpl<GlobalValue *> &Set, bool CompilerUsed) {
  515. const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
  516. GlobalVariable *GV = M.getGlobalVariable(Name);
  517. if (!GV || !GV->hasInitializer())
  518. return GV;
  519. const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
  520. for (Value *Op : Init->operands()) {
  521. GlobalValue *G = cast<GlobalValue>(Op->stripPointerCastsNoFollowAliases());
  522. Set.insert(G);
  523. }
  524. return GV;
  525. }