Module.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  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/SmallString.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/ADT/StringMap.h"
  18. #include "llvm/ADT/StringRef.h"
  19. #include "llvm/ADT/Twine.h"
  20. #include "llvm/IR/Attributes.h"
  21. #include "llvm/IR/Comdat.h"
  22. #include "llvm/IR/Constants.h"
  23. #include "llvm/IR/DataLayout.h"
  24. #include "llvm/IR/DebugInfoMetadata.h"
  25. #include "llvm/IR/DerivedTypes.h"
  26. #include "llvm/IR/Function.h"
  27. #include "llvm/IR/GVMaterializer.h"
  28. #include "llvm/IR/GlobalAlias.h"
  29. #include "llvm/IR/GlobalIFunc.h"
  30. #include "llvm/IR/GlobalValue.h"
  31. #include "llvm/IR/GlobalVariable.h"
  32. #include "llvm/IR/LLVMContext.h"
  33. #include "llvm/IR/Metadata.h"
  34. #include "llvm/IR/ModuleSummaryIndex.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/Support/Casting.h"
  41. #include "llvm/Support/CodeGen.h"
  42. #include "llvm/Support/Error.h"
  43. #include "llvm/Support/MemoryBuffer.h"
  44. #include "llvm/Support/Path.h"
  45. #include "llvm/Support/RandomNumberGenerator.h"
  46. #include "llvm/Support/VersionTuple.h"
  47. #include <algorithm>
  48. #include <cassert>
  49. #include <cstdint>
  50. #include <memory>
  51. #include <utility>
  52. #include <vector>
  53. using namespace llvm;
  54. //===----------------------------------------------------------------------===//
  55. // Methods to implement the globals and functions lists.
  56. //
  57. // Explicit instantiations of SymbolTableListTraits since some of the methods
  58. // are not in the public header file.
  59. template class llvm::SymbolTableListTraits<Function>;
  60. template class llvm::SymbolTableListTraits<GlobalVariable>;
  61. template class llvm::SymbolTableListTraits<GlobalAlias>;
  62. template class llvm::SymbolTableListTraits<GlobalIFunc>;
  63. //===----------------------------------------------------------------------===//
  64. // Primitive Module methods.
  65. //
  66. Module::Module(StringRef MID, LLVMContext &C)
  67. : Context(C), ValSymTab(std::make_unique<ValueSymbolTable>(-1)),
  68. Materializer(), ModuleID(std::string(MID)),
  69. SourceFileName(std::string(MID)), DL("") {
  70. Context.addModule(this);
  71. }
  72. Module::~Module() {
  73. Context.removeModule(this);
  74. dropAllReferences();
  75. GlobalList.clear();
  76. FunctionList.clear();
  77. AliasList.clear();
  78. IFuncList.clear();
  79. }
  80. std::unique_ptr<RandomNumberGenerator>
  81. Module::createRNG(const StringRef Name) const {
  82. SmallString<32> Salt(Name);
  83. // This RNG is guaranteed to produce the same random stream only
  84. // when the Module ID and thus the input filename is the same. This
  85. // might be problematic if the input filename extension changes
  86. // (e.g. from .c to .bc or .ll).
  87. //
  88. // We could store this salt in NamedMetadata, but this would make
  89. // the parameter non-const. This would unfortunately make this
  90. // interface unusable by any Machine passes, since they only have a
  91. // const reference to their IR Module. Alternatively we can always
  92. // store salt metadata from the Module constructor.
  93. Salt += sys::path::filename(getModuleIdentifier());
  94. return std::unique_ptr<RandomNumberGenerator>(
  95. new RandomNumberGenerator(Salt));
  96. }
  97. /// getNamedValue - Return the first global value in the module with
  98. /// the specified name, of arbitrary type. This method returns null
  99. /// if a global with the specified name is not found.
  100. GlobalValue *Module::getNamedValue(StringRef Name) const {
  101. return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
  102. }
  103. unsigned Module::getNumNamedValues() const {
  104. return getValueSymbolTable().size();
  105. }
  106. /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
  107. /// This ID is uniqued across modules in the current LLVMContext.
  108. unsigned Module::getMDKindID(StringRef Name) const {
  109. return Context.getMDKindID(Name);
  110. }
  111. /// getMDKindNames - Populate client supplied SmallVector with the name for
  112. /// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
  113. /// so it is filled in as an empty string.
  114. void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
  115. return Context.getMDKindNames(Result);
  116. }
  117. void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const {
  118. return Context.getOperandBundleTags(Result);
  119. }
  120. //===----------------------------------------------------------------------===//
  121. // Methods for easy access to the functions in the module.
  122. //
  123. // getOrInsertFunction - Look up the specified function in the module symbol
  124. // table. If it does not exist, add a prototype for the function and return
  125. // it. This is nice because it allows most passes to get away with not handling
  126. // the symbol table directly for this common task.
  127. //
  128. FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty,
  129. AttributeList AttributeList) {
  130. // See if we have a definition for the specified function already.
  131. GlobalValue *F = getNamedValue(Name);
  132. if (!F) {
  133. // Nope, add it
  134. Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage,
  135. DL.getProgramAddressSpace(), Name);
  136. if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
  137. New->setAttributes(AttributeList);
  138. FunctionList.push_back(New);
  139. return {Ty, New}; // Return the new prototype.
  140. }
  141. // If the function exists but has the wrong type, return a bitcast to the
  142. // right type.
  143. auto *PTy = PointerType::get(Ty, F->getAddressSpace());
  144. if (F->getType() != PTy)
  145. return {Ty, ConstantExpr::getBitCast(F, PTy)};
  146. // Otherwise, we just found the existing function or a prototype.
  147. return {Ty, F};
  148. }
  149. FunctionCallee Module::getOrInsertFunction(StringRef Name, FunctionType *Ty) {
  150. return getOrInsertFunction(Name, Ty, AttributeList());
  151. }
  152. // getFunction - Look up the specified function in the module symbol table.
  153. // If it does not exist, return null.
  154. //
  155. Function *Module::getFunction(StringRef Name) const {
  156. return dyn_cast_or_null<Function>(getNamedValue(Name));
  157. }
  158. //===----------------------------------------------------------------------===//
  159. // Methods for easy access to the global variables in the module.
  160. //
  161. /// getGlobalVariable - Look up the specified global variable in the module
  162. /// symbol table. If it does not exist, return null. The type argument
  163. /// should be the underlying type of the global, i.e., it should not have
  164. /// the top-level PointerType, which represents the address of the global.
  165. /// If AllowLocal is set to true, this function will return types that
  166. /// have an local. By default, these types are not returned.
  167. ///
  168. GlobalVariable *Module::getGlobalVariable(StringRef Name,
  169. bool AllowLocal) const {
  170. if (GlobalVariable *Result =
  171. dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
  172. if (AllowLocal || !Result->hasLocalLinkage())
  173. return Result;
  174. return nullptr;
  175. }
  176. /// getOrInsertGlobal - Look up the specified global in the module symbol table.
  177. /// 1. If it does not exist, add a declaration of the global and return it.
  178. /// 2. Else, the global exists but has the wrong type: return the function
  179. /// with a constantexpr cast to the right type.
  180. /// 3. Finally, if the existing global is the correct declaration, return the
  181. /// existing global.
  182. Constant *Module::getOrInsertGlobal(
  183. StringRef Name, Type *Ty,
  184. function_ref<GlobalVariable *()> CreateGlobalCallback) {
  185. // See if we have a definition for the specified global already.
  186. GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
  187. if (!GV)
  188. GV = CreateGlobalCallback();
  189. assert(GV && "The CreateGlobalCallback is expected to create a global");
  190. // If the variable exists but has the wrong type, return a bitcast to the
  191. // right type.
  192. Type *GVTy = GV->getType();
  193. PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
  194. if (GVTy != PTy)
  195. return ConstantExpr::getBitCast(GV, PTy);
  196. // Otherwise, we just found the existing function or a prototype.
  197. return GV;
  198. }
  199. // Overload to construct a global variable using its constructor's defaults.
  200. Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
  201. return getOrInsertGlobal(Name, Ty, [&] {
  202. return new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
  203. nullptr, Name);
  204. });
  205. }
  206. //===----------------------------------------------------------------------===//
  207. // Methods for easy access to the global variables in the module.
  208. //
  209. // getNamedAlias - Look up the specified global in the module symbol table.
  210. // If it does not exist, return null.
  211. //
  212. GlobalAlias *Module::getNamedAlias(StringRef Name) const {
  213. return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
  214. }
  215. GlobalIFunc *Module::getNamedIFunc(StringRef Name) const {
  216. return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name));
  217. }
  218. /// getNamedMetadata - Return the first NamedMDNode in the module with the
  219. /// specified name. This method returns null if a NamedMDNode with the
  220. /// specified name is not found.
  221. NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
  222. SmallString<256> NameData;
  223. StringRef NameRef = Name.toStringRef(NameData);
  224. return NamedMDSymTab.lookup(NameRef);
  225. }
  226. /// getOrInsertNamedMetadata - Return the first named MDNode in the module
  227. /// with the specified name. This method returns a new NamedMDNode if a
  228. /// NamedMDNode with the specified name is not found.
  229. NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
  230. NamedMDNode *&NMD = 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. 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. bool Module::isValidModuleFlag(const MDNode &ModFlag, ModFlagBehavior &MFB,
  255. MDString *&Key, Metadata *&Val) {
  256. if (ModFlag.getNumOperands() < 3)
  257. return false;
  258. if (!isValidModFlagBehavior(ModFlag.getOperand(0), MFB))
  259. return false;
  260. MDString *K = dyn_cast_or_null<MDString>(ModFlag.getOperand(1));
  261. if (!K)
  262. return false;
  263. Key = K;
  264. Val = ModFlag.getOperand(2);
  265. return true;
  266. }
  267. /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
  268. void Module::
  269. getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
  270. const NamedMDNode *ModFlags = getModuleFlagsMetadata();
  271. if (!ModFlags) return;
  272. for (const MDNode *Flag : ModFlags->operands()) {
  273. ModFlagBehavior MFB;
  274. MDString *Key = nullptr;
  275. Metadata *Val = nullptr;
  276. if (isValidModuleFlag(*Flag, MFB, Key, Val)) {
  277. // Check the operands of the MDNode before accessing the operands.
  278. // The verifier will actually catch these failures.
  279. Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
  280. }
  281. }
  282. }
  283. /// Return the corresponding value if Key appears in module flags, otherwise
  284. /// return null.
  285. Metadata *Module::getModuleFlag(StringRef Key) const {
  286. SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
  287. getModuleFlagsMetadata(ModuleFlags);
  288. for (const ModuleFlagEntry &MFE : ModuleFlags) {
  289. if (Key == MFE.Key->getString())
  290. return MFE.Val;
  291. }
  292. return nullptr;
  293. }
  294. /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
  295. /// represents module-level flags. This method returns null if there are no
  296. /// module-level flags.
  297. NamedMDNode *Module::getModuleFlagsMetadata() const {
  298. return getNamedMetadata("llvm.module.flags");
  299. }
  300. /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
  301. /// represents module-level flags. If module-level flags aren't found, it
  302. /// creates the named metadata that contains them.
  303. NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
  304. return getOrInsertNamedMetadata("llvm.module.flags");
  305. }
  306. /// addModuleFlag - Add a module-level flag to the module-level flags
  307. /// metadata. It will create the module-level flags named metadata if it doesn't
  308. /// already exist.
  309. void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
  310. Metadata *Val) {
  311. Type *Int32Ty = Type::getInt32Ty(Context);
  312. Metadata *Ops[3] = {
  313. ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
  314. MDString::get(Context, Key), Val};
  315. getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
  316. }
  317. void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
  318. Constant *Val) {
  319. addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
  320. }
  321. void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
  322. uint32_t Val) {
  323. Type *Int32Ty = Type::getInt32Ty(Context);
  324. addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
  325. }
  326. void Module::addModuleFlag(MDNode *Node) {
  327. assert(Node->getNumOperands() == 3 &&
  328. "Invalid number of operands for module flag!");
  329. assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
  330. isa<MDString>(Node->getOperand(1)) &&
  331. "Invalid operand types for module flag!");
  332. getOrInsertModuleFlagsMetadata()->addOperand(Node);
  333. }
  334. void Module::setModuleFlag(ModFlagBehavior Behavior, StringRef Key,
  335. Metadata *Val) {
  336. NamedMDNode *ModFlags = getOrInsertModuleFlagsMetadata();
  337. // Replace the flag if it already exists.
  338. for (unsigned I = 0, E = ModFlags->getNumOperands(); I != E; ++I) {
  339. MDNode *Flag = ModFlags->getOperand(I);
  340. ModFlagBehavior MFB;
  341. MDString *K = nullptr;
  342. Metadata *V = nullptr;
  343. if (isValidModuleFlag(*Flag, MFB, K, V) && K->getString() == Key) {
  344. Flag->replaceOperandWith(2, Val);
  345. return;
  346. }
  347. }
  348. addModuleFlag(Behavior, Key, Val);
  349. }
  350. void Module::setDataLayout(StringRef Desc) {
  351. DL.reset(Desc);
  352. }
  353. void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
  354. const DataLayout &Module::getDataLayout() const { return DL; }
  355. DICompileUnit *Module::debug_compile_units_iterator::operator*() const {
  356. return cast<DICompileUnit>(CUs->getOperand(Idx));
  357. }
  358. DICompileUnit *Module::debug_compile_units_iterator::operator->() const {
  359. return cast<DICompileUnit>(CUs->getOperand(Idx));
  360. }
  361. void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
  362. while (CUs && (Idx < CUs->getNumOperands()) &&
  363. ((*this)->getEmissionKind() == DICompileUnit::NoDebug))
  364. ++Idx;
  365. }
  366. iterator_range<Module::global_object_iterator> Module::global_objects() {
  367. return concat<GlobalObject>(functions(), globals());
  368. }
  369. iterator_range<Module::const_global_object_iterator>
  370. Module::global_objects() const {
  371. return concat<const GlobalObject>(functions(), globals());
  372. }
  373. iterator_range<Module::global_value_iterator> Module::global_values() {
  374. return concat<GlobalValue>(functions(), globals(), aliases(), ifuncs());
  375. }
  376. iterator_range<Module::const_global_value_iterator>
  377. Module::global_values() const {
  378. return concat<const GlobalValue>(functions(), globals(), aliases(), ifuncs());
  379. }
  380. //===----------------------------------------------------------------------===//
  381. // Methods to control the materialization of GlobalValues in the Module.
  382. //
  383. void Module::setMaterializer(GVMaterializer *GVM) {
  384. assert(!Materializer &&
  385. "Module already has a GVMaterializer. Call materializeAll"
  386. " to clear it out before setting another one.");
  387. Materializer.reset(GVM);
  388. }
  389. Error Module::materialize(GlobalValue *GV) {
  390. if (!Materializer)
  391. return Error::success();
  392. return Materializer->materialize(GV);
  393. }
  394. Error Module::materializeAll() {
  395. if (!Materializer)
  396. return Error::success();
  397. std::unique_ptr<GVMaterializer> M = std::move(Materializer);
  398. return M->materializeModule();
  399. }
  400. Error Module::materializeMetadata() {
  401. if (!Materializer)
  402. return Error::success();
  403. return Materializer->materializeMetadata();
  404. }
  405. //===----------------------------------------------------------------------===//
  406. // Other module related stuff.
  407. //
  408. std::vector<StructType *> Module::getIdentifiedStructTypes() const {
  409. // If we have a materializer, it is possible that some unread function
  410. // uses a type that is currently not visible to a TypeFinder, so ask
  411. // the materializer which types it created.
  412. if (Materializer)
  413. return Materializer->getIdentifiedStructTypes();
  414. std::vector<StructType *> Ret;
  415. TypeFinder SrcStructTypes;
  416. SrcStructTypes.run(*this, true);
  417. Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
  418. return Ret;
  419. }
  420. std::string Module::getUniqueIntrinsicName(StringRef BaseName, Intrinsic::ID Id,
  421. const FunctionType *Proto) {
  422. auto Encode = [&BaseName](unsigned Suffix) {
  423. return (Twine(BaseName) + "." + Twine(Suffix)).str();
  424. };
  425. {
  426. // fast path - the prototype is already known
  427. auto UinItInserted = UniquedIntrinsicNames.insert({{Id, Proto}, 0});
  428. if (!UinItInserted.second)
  429. return Encode(UinItInserted.first->second);
  430. }
  431. // Not known yet. A new entry was created with index 0. Check if there already
  432. // exists a matching declaration, or select a new entry.
  433. // Start looking for names with the current known maximum count (or 0).
  434. auto NiidItInserted = CurrentIntrinsicIds.insert({BaseName, 0});
  435. unsigned Count = NiidItInserted.first->second;
  436. // This might be slow if a whole population of intrinsics already existed, but
  437. // we cache the values for later usage.
  438. std::string NewName;
  439. while (true) {
  440. NewName = Encode(Count);
  441. GlobalValue *F = getNamedValue(NewName);
  442. if (!F) {
  443. // Reserve this entry for the new proto
  444. UniquedIntrinsicNames[{Id, Proto}] = Count;
  445. break;
  446. }
  447. // A declaration with this name already exists. Remember it.
  448. FunctionType *FT = dyn_cast<FunctionType>(F->getValueType());
  449. auto UinItInserted = UniquedIntrinsicNames.insert({{Id, FT}, Count});
  450. if (FT == Proto) {
  451. // It was a declaration for our prototype. This entry was allocated in the
  452. // beginning. Update the count to match the existing declaration.
  453. UinItInserted.first->second = Count;
  454. break;
  455. }
  456. ++Count;
  457. }
  458. NiidItInserted.first->second = Count + 1;
  459. return NewName;
  460. }
  461. // dropAllReferences() - This function causes all the subelements to "let go"
  462. // of all references that they are maintaining. This allows one to 'delete' a
  463. // whole module at a time, even though there may be circular references... first
  464. // all references are dropped, and all use counts go to zero. Then everything
  465. // is deleted for real. Note that no operations are valid on an object that
  466. // has "dropped all references", except operator delete.
  467. //
  468. void Module::dropAllReferences() {
  469. for (Function &F : *this)
  470. F.dropAllReferences();
  471. for (GlobalVariable &GV : globals())
  472. GV.dropAllReferences();
  473. for (GlobalAlias &GA : aliases())
  474. GA.dropAllReferences();
  475. for (GlobalIFunc &GIF : ifuncs())
  476. GIF.dropAllReferences();
  477. }
  478. unsigned Module::getNumberRegisterParameters() const {
  479. auto *Val =
  480. cast_or_null<ConstantAsMetadata>(getModuleFlag("NumRegisterParameters"));
  481. if (!Val)
  482. return 0;
  483. return cast<ConstantInt>(Val->getValue())->getZExtValue();
  484. }
  485. unsigned Module::getDwarfVersion() const {
  486. auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
  487. if (!Val)
  488. return 0;
  489. return cast<ConstantInt>(Val->getValue())->getZExtValue();
  490. }
  491. bool Module::isDwarf64() const {
  492. auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("DWARF64"));
  493. return Val && cast<ConstantInt>(Val->getValue())->isOne();
  494. }
  495. unsigned Module::getCodeViewFlag() const {
  496. auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
  497. if (!Val)
  498. return 0;
  499. return cast<ConstantInt>(Val->getValue())->getZExtValue();
  500. }
  501. unsigned Module::getInstructionCount() const {
  502. unsigned NumInstrs = 0;
  503. for (const Function &F : FunctionList)
  504. NumInstrs += F.getInstructionCount();
  505. return NumInstrs;
  506. }
  507. Comdat *Module::getOrInsertComdat(StringRef Name) {
  508. auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
  509. Entry.second.Name = &Entry;
  510. return &Entry.second;
  511. }
  512. PICLevel::Level Module::getPICLevel() const {
  513. auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
  514. if (!Val)
  515. return PICLevel::NotPIC;
  516. return static_cast<PICLevel::Level>(
  517. cast<ConstantInt>(Val->getValue())->getZExtValue());
  518. }
  519. void Module::setPICLevel(PICLevel::Level PL) {
  520. addModuleFlag(ModFlagBehavior::Max, "PIC Level", PL);
  521. }
  522. PIELevel::Level Module::getPIELevel() const {
  523. auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level"));
  524. if (!Val)
  525. return PIELevel::Default;
  526. return static_cast<PIELevel::Level>(
  527. cast<ConstantInt>(Val->getValue())->getZExtValue());
  528. }
  529. void Module::setPIELevel(PIELevel::Level PL) {
  530. addModuleFlag(ModFlagBehavior::Max, "PIE Level", PL);
  531. }
  532. Optional<CodeModel::Model> Module::getCodeModel() const {
  533. auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Code Model"));
  534. if (!Val)
  535. return None;
  536. return static_cast<CodeModel::Model>(
  537. cast<ConstantInt>(Val->getValue())->getZExtValue());
  538. }
  539. void Module::setCodeModel(CodeModel::Model CL) {
  540. // Linking object files with different code models is undefined behavior
  541. // because the compiler would have to generate additional code (to span
  542. // longer jumps) if a larger code model is used with a smaller one.
  543. // Therefore we will treat attempts to mix code models as an error.
  544. addModuleFlag(ModFlagBehavior::Error, "Code Model", CL);
  545. }
  546. void Module::setProfileSummary(Metadata *M, ProfileSummary::Kind Kind) {
  547. if (Kind == ProfileSummary::PSK_CSInstr)
  548. setModuleFlag(ModFlagBehavior::Error, "CSProfileSummary", M);
  549. else
  550. setModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M);
  551. }
  552. Metadata *Module::getProfileSummary(bool IsCS) const {
  553. return (IsCS ? getModuleFlag("CSProfileSummary")
  554. : getModuleFlag("ProfileSummary"));
  555. }
  556. bool Module::getSemanticInterposition() const {
  557. Metadata *MF = getModuleFlag("SemanticInterposition");
  558. auto *Val = cast_or_null<ConstantAsMetadata>(MF);
  559. if (!Val)
  560. return false;
  561. return cast<ConstantInt>(Val->getValue())->getZExtValue();
  562. }
  563. void Module::setSemanticInterposition(bool SI) {
  564. addModuleFlag(ModFlagBehavior::Error, "SemanticInterposition", SI);
  565. }
  566. void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) {
  567. OwnedMemoryBuffer = std::move(MB);
  568. }
  569. bool Module::getRtLibUseGOT() const {
  570. auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("RtLibUseGOT"));
  571. return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0);
  572. }
  573. void Module::setRtLibUseGOT() {
  574. addModuleFlag(ModFlagBehavior::Max, "RtLibUseGOT", 1);
  575. }
  576. bool Module::getUwtable() const {
  577. auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("uwtable"));
  578. return Val && (cast<ConstantInt>(Val->getValue())->getZExtValue() > 0);
  579. }
  580. void Module::setUwtable() { addModuleFlag(ModFlagBehavior::Max, "uwtable", 1); }
  581. FramePointerKind Module::getFramePointer() const {
  582. auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("frame-pointer"));
  583. return static_cast<FramePointerKind>(
  584. Val ? cast<ConstantInt>(Val->getValue())->getZExtValue() : 0);
  585. }
  586. void Module::setFramePointer(FramePointerKind Kind) {
  587. addModuleFlag(ModFlagBehavior::Max, "frame-pointer", static_cast<int>(Kind));
  588. }
  589. StringRef Module::getStackProtectorGuard() const {
  590. Metadata *MD = getModuleFlag("stack-protector-guard");
  591. if (auto *MDS = dyn_cast_or_null<MDString>(MD))
  592. return MDS->getString();
  593. return {};
  594. }
  595. void Module::setStackProtectorGuard(StringRef Kind) {
  596. MDString *ID = MDString::get(getContext(), Kind);
  597. addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard", ID);
  598. }
  599. StringRef Module::getStackProtectorGuardReg() const {
  600. Metadata *MD = getModuleFlag("stack-protector-guard-reg");
  601. if (auto *MDS = dyn_cast_or_null<MDString>(MD))
  602. return MDS->getString();
  603. return {};
  604. }
  605. void Module::setStackProtectorGuardReg(StringRef Reg) {
  606. MDString *ID = MDString::get(getContext(), Reg);
  607. addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-reg", ID);
  608. }
  609. int Module::getStackProtectorGuardOffset() const {
  610. Metadata *MD = getModuleFlag("stack-protector-guard-offset");
  611. if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
  612. return CI->getSExtValue();
  613. return INT_MAX;
  614. }
  615. void Module::setStackProtectorGuardOffset(int Offset) {
  616. addModuleFlag(ModFlagBehavior::Error, "stack-protector-guard-offset", Offset);
  617. }
  618. unsigned Module::getOverrideStackAlignment() const {
  619. Metadata *MD = getModuleFlag("override-stack-alignment");
  620. if (auto *CI = mdconst::dyn_extract_or_null<ConstantInt>(MD))
  621. return CI->getZExtValue();
  622. return 0;
  623. }
  624. void Module::setOverrideStackAlignment(unsigned Align) {
  625. addModuleFlag(ModFlagBehavior::Error, "override-stack-alignment", Align);
  626. }
  627. void Module::setSDKVersion(const VersionTuple &V) {
  628. SmallVector<unsigned, 3> Entries;
  629. Entries.push_back(V.getMajor());
  630. if (auto Minor = V.getMinor()) {
  631. Entries.push_back(*Minor);
  632. if (auto Subminor = V.getSubminor())
  633. Entries.push_back(*Subminor);
  634. // Ignore the 'build' component as it can't be represented in the object
  635. // file.
  636. }
  637. addModuleFlag(ModFlagBehavior::Warning, "SDK Version",
  638. ConstantDataArray::get(Context, Entries));
  639. }
  640. static VersionTuple getSDKVersionMD(Metadata *MD) {
  641. auto *CM = dyn_cast_or_null<ConstantAsMetadata>(MD);
  642. if (!CM)
  643. return {};
  644. auto *Arr = dyn_cast_or_null<ConstantDataArray>(CM->getValue());
  645. if (!Arr)
  646. return {};
  647. auto getVersionComponent = [&](unsigned Index) -> Optional<unsigned> {
  648. if (Index >= Arr->getNumElements())
  649. return None;
  650. return (unsigned)Arr->getElementAsInteger(Index);
  651. };
  652. auto Major = getVersionComponent(0);
  653. if (!Major)
  654. return {};
  655. VersionTuple Result = VersionTuple(*Major);
  656. if (auto Minor = getVersionComponent(1)) {
  657. Result = VersionTuple(*Major, *Minor);
  658. if (auto Subminor = getVersionComponent(2)) {
  659. Result = VersionTuple(*Major, *Minor, *Subminor);
  660. }
  661. }
  662. return Result;
  663. }
  664. VersionTuple Module::getSDKVersion() const {
  665. return getSDKVersionMD(getModuleFlag("SDK Version"));
  666. }
  667. GlobalVariable *llvm::collectUsedGlobalVariables(
  668. const Module &M, SmallVectorImpl<GlobalValue *> &Vec, bool CompilerUsed) {
  669. const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
  670. GlobalVariable *GV = M.getGlobalVariable(Name);
  671. if (!GV || !GV->hasInitializer())
  672. return GV;
  673. const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
  674. for (Value *Op : Init->operands()) {
  675. GlobalValue *G = cast<GlobalValue>(Op->stripPointerCasts());
  676. Vec.push_back(G);
  677. }
  678. return GV;
  679. }
  680. void Module::setPartialSampleProfileRatio(const ModuleSummaryIndex &Index) {
  681. if (auto *SummaryMD = getProfileSummary(/*IsCS*/ false)) {
  682. std::unique_ptr<ProfileSummary> ProfileSummary(
  683. ProfileSummary::getFromMD(SummaryMD));
  684. if (ProfileSummary) {
  685. if (ProfileSummary->getKind() != ProfileSummary::PSK_Sample ||
  686. !ProfileSummary->isPartialProfile())
  687. return;
  688. uint64_t BlockCount = Index.getBlockCount();
  689. uint32_t NumCounts = ProfileSummary->getNumCounts();
  690. if (!NumCounts)
  691. return;
  692. double Ratio = (double)BlockCount / NumCounts;
  693. ProfileSummary->setPartialProfileRatio(Ratio);
  694. setProfileSummary(ProfileSummary->getMD(getContext()),
  695. ProfileSummary::PSK_Sample);
  696. }
  697. }
  698. }
  699. StringRef Module::getDarwinTargetVariantTriple() const {
  700. if (const auto *MD = getModuleFlag("darwin.target_variant.triple"))
  701. return cast<MDString>(MD)->getString();
  702. return "";
  703. }
  704. VersionTuple Module::getDarwinTargetVariantSDKVersion() const {
  705. return getSDKVersionMD(getModuleFlag("darwin.target_variant.SDK Version"));
  706. }