Module.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. //===-- Module.cpp - Implement the Module class ---------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the Module class for the IR library.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/IR/Module.h"
  14. #include "SymbolTableListTraitsImpl.h"
  15. #include "llvm/ADT/DenseSet.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/ADT/SmallString.h"
  18. #include "llvm/ADT/StringExtras.h"
  19. #include "llvm/IR/Constants.h"
  20. #include "llvm/IR/DerivedTypes.h"
  21. #include "llvm/IR/GVMaterializer.h"
  22. #include "llvm/IR/InstrTypes.h"
  23. #include "llvm/IR/LLVMContext.h"
  24. #include "llvm/IR/TypeFinder.h"
  25. #include "llvm/Support/Dwarf.h"
  26. #include "llvm/Support/Path.h"
  27. #include "llvm/Support/RandomNumberGenerator.h"
  28. #include <algorithm>
  29. #include <cstdarg>
  30. #include <cstdlib>
  31. using namespace llvm;
  32. //===----------------------------------------------------------------------===//
  33. // Methods to implement the globals and functions lists.
  34. //
  35. // Explicit instantiations of SymbolTableListTraits since some of the methods
  36. // are not in the public header file.
  37. template class llvm::SymbolTableListTraits<Function>;
  38. template class llvm::SymbolTableListTraits<GlobalVariable>;
  39. template class llvm::SymbolTableListTraits<GlobalAlias>;
  40. //===----------------------------------------------------------------------===//
  41. // Primitive Module methods.
  42. //
  43. Module::Module(StringRef MID, LLVMContext &C)
  44. : Context(C), Materializer(), ModuleID(MID), DL("") {
  45. ValSymTab = new ValueSymbolTable();
  46. NamedMDSymTab = new StringMap<NamedMDNode *>();
  47. Context.addModule(this);
  48. }
  49. Module::~Module() {
  50. Context.removeModule(this);
  51. dropAllReferences();
  52. GlobalList.clear();
  53. FunctionList.clear();
  54. AliasList.clear();
  55. NamedMDList.clear();
  56. delete ValSymTab;
  57. delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
  58. }
  59. RandomNumberGenerator *Module::createRNG(const Pass* P) const {
  60. SmallString<32> Salt(P->getPassName());
  61. // This RNG is guaranteed to produce the same random stream only
  62. // when the Module ID and thus the input filename is the same. This
  63. // might be problematic if the input filename extension changes
  64. // (e.g. from .c to .bc or .ll).
  65. //
  66. // We could store this salt in NamedMetadata, but this would make
  67. // the parameter non-const. This would unfortunately make this
  68. // interface unusable by any Machine passes, since they only have a
  69. // const reference to their IR Module. Alternatively we can always
  70. // store salt metadata from the Module constructor.
  71. Salt += sys::path::filename(getModuleIdentifier());
  72. return new RandomNumberGenerator(Salt);
  73. }
  74. /// getNamedValue - Return the first global value in the module with
  75. /// the specified name, of arbitrary type. This method returns null
  76. /// if a global with the specified name is not found.
  77. GlobalValue *Module::getNamedValue(StringRef Name) const {
  78. return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
  79. }
  80. /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
  81. /// This ID is uniqued across modules in the current LLVMContext.
  82. unsigned Module::getMDKindID(StringRef Name) const {
  83. return Context.getMDKindID(Name);
  84. }
  85. /// getMDKindNames - Populate client supplied SmallVector with the name for
  86. /// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
  87. /// so it is filled in as an empty string.
  88. void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
  89. return Context.getMDKindNames(Result);
  90. }
  91. void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const {
  92. return Context.getOperandBundleTags(Result);
  93. }
  94. //===----------------------------------------------------------------------===//
  95. // Methods for easy access to the functions in the module.
  96. //
  97. // getOrInsertFunction - Look up the specified function in the module symbol
  98. // table. If it does not exist, add a prototype for the function and return
  99. // it. This is nice because it allows most passes to get away with not handling
  100. // the symbol table directly for this common task.
  101. //
  102. Constant *Module::getOrInsertFunction(StringRef Name,
  103. FunctionType *Ty,
  104. AttributeSet AttributeList) {
  105. // See if we have a definition for the specified function already.
  106. GlobalValue *F = getNamedValue(Name);
  107. if (!F) {
  108. // Nope, add it
  109. Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
  110. if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
  111. New->setAttributes(AttributeList);
  112. FunctionList.push_back(New);
  113. return New; // Return the new prototype.
  114. }
  115. // If the function exists but has the wrong type, return a bitcast to the
  116. // right type.
  117. if (F->getType() != PointerType::getUnqual(Ty))
  118. return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
  119. // Otherwise, we just found the existing function or a prototype.
  120. return F;
  121. }
  122. Constant *Module::getOrInsertFunction(StringRef Name,
  123. FunctionType *Ty) {
  124. return getOrInsertFunction(Name, Ty, AttributeSet());
  125. }
  126. // getOrInsertFunction - Look up the specified function in the module symbol
  127. // table. If it does not exist, add a prototype for the function and return it.
  128. // This version of the method takes a null terminated list of function
  129. // arguments, which makes it easier for clients to use.
  130. //
  131. Constant *Module::getOrInsertFunction(StringRef Name,
  132. AttributeSet AttributeList,
  133. Type *RetTy, ...) {
  134. va_list Args;
  135. va_start(Args, RetTy);
  136. // Build the list of argument types...
  137. std::vector<Type*> ArgTys;
  138. while (Type *ArgTy = va_arg(Args, Type*))
  139. ArgTys.push_back(ArgTy);
  140. va_end(Args);
  141. // Build the function type and chain to the other getOrInsertFunction...
  142. return getOrInsertFunction(Name,
  143. FunctionType::get(RetTy, ArgTys, false),
  144. AttributeList);
  145. }
  146. Constant *Module::getOrInsertFunction(StringRef Name,
  147. Type *RetTy, ...) {
  148. va_list Args;
  149. va_start(Args, RetTy);
  150. // Build the list of argument types...
  151. std::vector<Type*> ArgTys;
  152. while (Type *ArgTy = va_arg(Args, Type*))
  153. ArgTys.push_back(ArgTy);
  154. va_end(Args);
  155. // Build the function type and chain to the other getOrInsertFunction...
  156. return getOrInsertFunction(Name,
  157. FunctionType::get(RetTy, ArgTys, false),
  158. AttributeSet());
  159. }
  160. // getFunction - Look up the specified function in the module symbol table.
  161. // If it does not exist, return null.
  162. //
  163. Function *Module::getFunction(StringRef Name) const {
  164. return dyn_cast_or_null<Function>(getNamedValue(Name));
  165. }
  166. //===----------------------------------------------------------------------===//
  167. // Methods for easy access to the global variables in the module.
  168. //
  169. /// getGlobalVariable - Look up the specified global variable in the module
  170. /// symbol table. If it does not exist, return null. The type argument
  171. /// should be the underlying type of the global, i.e., it should not have
  172. /// the top-level PointerType, which represents the address of the global.
  173. /// If AllowLocal is set to true, this function will return types that
  174. /// have an local. By default, these types are not returned.
  175. ///
  176. GlobalVariable *Module::getGlobalVariable(StringRef Name, bool AllowLocal) {
  177. if (GlobalVariable *Result =
  178. dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
  179. if (AllowLocal || !Result->hasLocalLinkage())
  180. return Result;
  181. return nullptr;
  182. }
  183. /// getOrInsertGlobal - Look up the specified global in the module symbol table.
  184. /// 1. If it does not exist, add a declaration of the global and return it.
  185. /// 2. Else, the global exists but has the wrong type: return the function
  186. /// with a constantexpr cast to the right type.
  187. /// 3. Finally, if the existing global is the correct declaration, return the
  188. /// existing global.
  189. Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
  190. // See if we have a definition for the specified global already.
  191. GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
  192. if (!GV) {
  193. // Nope, add it
  194. GlobalVariable *New =
  195. new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
  196. nullptr, Name);
  197. return New; // Return the new declaration.
  198. }
  199. // If the variable exists but has the wrong type, return a bitcast to the
  200. // right type.
  201. Type *GVTy = GV->getType();
  202. PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
  203. if (GVTy != PTy)
  204. return ConstantExpr::getBitCast(GV, PTy);
  205. // Otherwise, we just found the existing function or a prototype.
  206. return GV;
  207. }
  208. //===----------------------------------------------------------------------===//
  209. // Methods for easy access to the global variables in the module.
  210. //
  211. // getNamedAlias - Look up the specified global in the module symbol table.
  212. // If it does not exist, return null.
  213. //
  214. GlobalAlias *Module::getNamedAlias(StringRef Name) const {
  215. return dyn_cast_or_null<GlobalAlias>(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. //===----------------------------------------------------------------------===//
  329. // Methods to control the materialization of GlobalValues in the Module.
  330. //
  331. void Module::setMaterializer(GVMaterializer *GVM) {
  332. assert(!Materializer &&
  333. "Module already has a GVMaterializer. Call materializeAll"
  334. " to clear it out before setting another one.");
  335. Materializer.reset(GVM);
  336. }
  337. std::error_code Module::materialize(GlobalValue *GV) {
  338. if (!Materializer)
  339. return std::error_code();
  340. return Materializer->materialize(GV);
  341. }
  342. std::error_code Module::materializeAll() {
  343. if (!Materializer)
  344. return std::error_code();
  345. std::unique_ptr<GVMaterializer> M = std::move(Materializer);
  346. return M->materializeModule();
  347. }
  348. std::error_code Module::materializeMetadata() {
  349. if (!Materializer)
  350. return std::error_code();
  351. return Materializer->materializeMetadata();
  352. }
  353. //===----------------------------------------------------------------------===//
  354. // Other module related stuff.
  355. //
  356. std::vector<StructType *> Module::getIdentifiedStructTypes() const {
  357. // If we have a materializer, it is possible that some unread function
  358. // uses a type that is currently not visible to a TypeFinder, so ask
  359. // the materializer which types it created.
  360. if (Materializer)
  361. return Materializer->getIdentifiedStructTypes();
  362. std::vector<StructType *> Ret;
  363. TypeFinder SrcStructTypes;
  364. SrcStructTypes.run(*this, true);
  365. Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
  366. return Ret;
  367. }
  368. // dropAllReferences() - This function causes all the subelements to "let go"
  369. // of all references that they are maintaining. This allows one to 'delete' a
  370. // whole module at a time, even though there may be circular references... first
  371. // all references are dropped, and all use counts go to zero. Then everything
  372. // is deleted for real. Note that no operations are valid on an object that
  373. // has "dropped all references", except operator delete.
  374. //
  375. void Module::dropAllReferences() {
  376. for (Function &F : *this)
  377. F.dropAllReferences();
  378. for (GlobalVariable &GV : globals())
  379. GV.dropAllReferences();
  380. for (GlobalAlias &GA : aliases())
  381. GA.dropAllReferences();
  382. }
  383. unsigned Module::getDwarfVersion() const {
  384. auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
  385. if (!Val)
  386. return 0;
  387. return cast<ConstantInt>(Val->getValue())->getZExtValue();
  388. }
  389. unsigned Module::getCodeViewFlag() const {
  390. auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
  391. if (!Val)
  392. return 0;
  393. return cast<ConstantInt>(Val->getValue())->getZExtValue();
  394. }
  395. Comdat *Module::getOrInsertComdat(StringRef Name) {
  396. auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
  397. Entry.second.Name = &Entry;
  398. return &Entry.second;
  399. }
  400. PICLevel::Level Module::getPICLevel() const {
  401. auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
  402. if (!Val)
  403. return PICLevel::Default;
  404. return static_cast<PICLevel::Level>(
  405. cast<ConstantInt>(Val->getValue())->getZExtValue());
  406. }
  407. void Module::setPICLevel(PICLevel::Level PL) {
  408. addModuleFlag(ModFlagBehavior::Error, "PIC Level", PL);
  409. }
  410. void Module::setMaximumFunctionCount(uint64_t Count) {
  411. addModuleFlag(ModFlagBehavior::Error, "MaxFunctionCount", Count);
  412. }
  413. Optional<uint64_t> Module::getMaximumFunctionCount() {
  414. auto *Val =
  415. cast_or_null<ConstantAsMetadata>(getModuleFlag("MaxFunctionCount"));
  416. if (!Val)
  417. return None;
  418. return cast<ConstantInt>(Val->getValue())->getZExtValue();
  419. }