Module.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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/LeakDetector.h"
  25. #include <algorithm>
  26. #include <cstdarg>
  27. #include <cstdlib>
  28. using namespace llvm;
  29. //===----------------------------------------------------------------------===//
  30. // Methods to implement the globals and functions lists.
  31. //
  32. // Explicit instantiations of SymbolTableListTraits since some of the methods
  33. // are not in the public header file.
  34. template class llvm::SymbolTableListTraits<Function, Module>;
  35. template class llvm::SymbolTableListTraits<GlobalVariable, Module>;
  36. template class llvm::SymbolTableListTraits<GlobalAlias, Module>;
  37. //===----------------------------------------------------------------------===//
  38. // Primitive Module methods.
  39. //
  40. Module::Module(StringRef MID, LLVMContext &C)
  41. : Context(C), Materializer(), ModuleID(MID), DL("") {
  42. ValSymTab = new ValueSymbolTable();
  43. NamedMDSymTab = new StringMap<NamedMDNode *>();
  44. Context.addModule(this);
  45. }
  46. Module::~Module() {
  47. Context.removeModule(this);
  48. dropAllReferences();
  49. GlobalList.clear();
  50. FunctionList.clear();
  51. AliasList.clear();
  52. NamedMDList.clear();
  53. delete ValSymTab;
  54. delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
  55. }
  56. /// getNamedValue - Return the first global value in the module with
  57. /// the specified name, of arbitrary type. This method returns null
  58. /// if a global with the specified name is not found.
  59. GlobalValue *Module::getNamedValue(StringRef Name) const {
  60. return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
  61. }
  62. /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
  63. /// This ID is uniqued across modules in the current LLVMContext.
  64. unsigned Module::getMDKindID(StringRef Name) const {
  65. return Context.getMDKindID(Name);
  66. }
  67. /// getMDKindNames - Populate client supplied SmallVector with the name for
  68. /// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
  69. /// so it is filled in as an empty string.
  70. void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
  71. return Context.getMDKindNames(Result);
  72. }
  73. //===----------------------------------------------------------------------===//
  74. // Methods for easy access to the functions in the module.
  75. //
  76. // getOrInsertFunction - Look up the specified function in the module symbol
  77. // table. If it does not exist, add a prototype for the function and return
  78. // it. This is nice because it allows most passes to get away with not handling
  79. // the symbol table directly for this common task.
  80. //
  81. Constant *Module::getOrInsertFunction(StringRef Name,
  82. FunctionType *Ty,
  83. AttributeSet AttributeList) {
  84. // See if we have a definition for the specified function already.
  85. GlobalValue *F = getNamedValue(Name);
  86. if (!F) {
  87. // Nope, add it
  88. Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
  89. if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
  90. New->setAttributes(AttributeList);
  91. FunctionList.push_back(New);
  92. return New; // Return the new prototype.
  93. }
  94. // If the function exists but has the wrong type, return a bitcast to the
  95. // right type.
  96. if (F->getType() != PointerType::getUnqual(Ty))
  97. return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
  98. // Otherwise, we just found the existing function or a prototype.
  99. return F;
  100. }
  101. Constant *Module::getOrInsertFunction(StringRef Name,
  102. FunctionType *Ty) {
  103. return getOrInsertFunction(Name, Ty, AttributeSet());
  104. }
  105. // getOrInsertFunction - Look up the specified function in the module symbol
  106. // table. If it does not exist, add a prototype for the function and return it.
  107. // This version of the method takes a null terminated list of function
  108. // arguments, which makes it easier for clients to use.
  109. //
  110. Constant *Module::getOrInsertFunction(StringRef Name,
  111. AttributeSet AttributeList,
  112. Type *RetTy, ...) {
  113. va_list Args;
  114. va_start(Args, RetTy);
  115. // Build the list of argument types...
  116. std::vector<Type*> ArgTys;
  117. while (Type *ArgTy = va_arg(Args, Type*))
  118. ArgTys.push_back(ArgTy);
  119. va_end(Args);
  120. // Build the function type and chain to the other getOrInsertFunction...
  121. return getOrInsertFunction(Name,
  122. FunctionType::get(RetTy, ArgTys, false),
  123. AttributeList);
  124. }
  125. Constant *Module::getOrInsertFunction(StringRef Name,
  126. Type *RetTy, ...) {
  127. va_list Args;
  128. va_start(Args, RetTy);
  129. // Build the list of argument types...
  130. std::vector<Type*> ArgTys;
  131. while (Type *ArgTy = va_arg(Args, Type*))
  132. ArgTys.push_back(ArgTy);
  133. va_end(Args);
  134. // Build the function type and chain to the other getOrInsertFunction...
  135. return getOrInsertFunction(Name,
  136. FunctionType::get(RetTy, ArgTys, false),
  137. AttributeSet());
  138. }
  139. // getFunction - Look up the specified function in the module symbol table.
  140. // If it does not exist, return null.
  141. //
  142. Function *Module::getFunction(StringRef Name) const {
  143. return dyn_cast_or_null<Function>(getNamedValue(Name));
  144. }
  145. //===----------------------------------------------------------------------===//
  146. // Methods for easy access to the global variables in the module.
  147. //
  148. /// getGlobalVariable - Look up the specified global variable in the module
  149. /// symbol table. If it does not exist, return null. The type argument
  150. /// should be the underlying type of the global, i.e., it should not have
  151. /// the top-level PointerType, which represents the address of the global.
  152. /// If AllowLocal is set to true, this function will return types that
  153. /// have an local. By default, these types are not returned.
  154. ///
  155. GlobalVariable *Module::getGlobalVariable(StringRef Name, bool AllowLocal) {
  156. if (GlobalVariable *Result =
  157. dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
  158. if (AllowLocal || !Result->hasLocalLinkage())
  159. return Result;
  160. return nullptr;
  161. }
  162. /// getOrInsertGlobal - Look up the specified global in the module symbol table.
  163. /// 1. If it does not exist, add a declaration of the global and return it.
  164. /// 2. Else, the global exists but has the wrong type: return the function
  165. /// with a constantexpr cast to the right type.
  166. /// 3. Finally, if the existing global is the correct declaration, return the
  167. /// existing global.
  168. Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
  169. // See if we have a definition for the specified global already.
  170. GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
  171. if (!GV) {
  172. // Nope, add it
  173. GlobalVariable *New =
  174. new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
  175. nullptr, Name);
  176. return New; // Return the new declaration.
  177. }
  178. // If the variable exists but has the wrong type, return a bitcast to the
  179. // right type.
  180. Type *GVTy = GV->getType();
  181. PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
  182. if (GVTy != PTy)
  183. return ConstantExpr::getBitCast(GV, PTy);
  184. // Otherwise, we just found the existing function or a prototype.
  185. return GV;
  186. }
  187. //===----------------------------------------------------------------------===//
  188. // Methods for easy access to the global variables in the module.
  189. //
  190. // getNamedAlias - Look up the specified global in the module symbol table.
  191. // If it does not exist, return null.
  192. //
  193. GlobalAlias *Module::getNamedAlias(StringRef Name) const {
  194. return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
  195. }
  196. /// getNamedMetadata - Return the first NamedMDNode in the module with the
  197. /// specified name. This method returns null if a NamedMDNode with the
  198. /// specified name is not found.
  199. NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
  200. SmallString<256> NameData;
  201. StringRef NameRef = Name.toStringRef(NameData);
  202. return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
  203. }
  204. /// getOrInsertNamedMetadata - Return the first named MDNode in the module
  205. /// with the specified name. This method returns a new NamedMDNode if a
  206. /// NamedMDNode with the specified name is not found.
  207. NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
  208. NamedMDNode *&NMD =
  209. (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
  210. if (!NMD) {
  211. NMD = new NamedMDNode(Name);
  212. NMD->setParent(this);
  213. NamedMDList.push_back(NMD);
  214. }
  215. return NMD;
  216. }
  217. /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
  218. /// delete it.
  219. void Module::eraseNamedMetadata(NamedMDNode *NMD) {
  220. static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
  221. NamedMDList.erase(NMD);
  222. }
  223. /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
  224. void Module::
  225. getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
  226. const NamedMDNode *ModFlags = getModuleFlagsMetadata();
  227. if (!ModFlags) return;
  228. for (const MDNode *Flag : ModFlags->operands()) {
  229. if (Flag->getNumOperands() >= 3 && isa<ConstantInt>(Flag->getOperand(0)) &&
  230. isa<MDString>(Flag->getOperand(1))) {
  231. // Check the operands of the MDNode before accessing the operands.
  232. // The verifier will actually catch these failures.
  233. ConstantInt *Behavior = cast<ConstantInt>(Flag->getOperand(0));
  234. MDString *Key = cast<MDString>(Flag->getOperand(1));
  235. Value *Val = Flag->getOperand(2);
  236. Flags.push_back(ModuleFlagEntry(ModFlagBehavior(Behavior->getZExtValue()),
  237. Key, Val));
  238. }
  239. }
  240. }
  241. /// Return the corresponding value if Key appears in module flags, otherwise
  242. /// return null.
  243. Value *Module::getModuleFlag(StringRef Key) const {
  244. SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
  245. getModuleFlagsMetadata(ModuleFlags);
  246. for (const ModuleFlagEntry &MFE : ModuleFlags) {
  247. if (Key == MFE.Key->getString())
  248. return MFE.Val;
  249. }
  250. return nullptr;
  251. }
  252. /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
  253. /// represents module-level flags. This method returns null if there are no
  254. /// module-level flags.
  255. NamedMDNode *Module::getModuleFlagsMetadata() const {
  256. return getNamedMetadata("llvm.module.flags");
  257. }
  258. /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
  259. /// represents module-level flags. If module-level flags aren't found, it
  260. /// creates the named metadata that contains them.
  261. NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
  262. return getOrInsertNamedMetadata("llvm.module.flags");
  263. }
  264. /// addModuleFlag - Add a module-level flag to the module-level flags
  265. /// metadata. It will create the module-level flags named metadata if it doesn't
  266. /// already exist.
  267. void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
  268. Value *Val) {
  269. Type *Int32Ty = Type::getInt32Ty(Context);
  270. Value *Ops[3] = {
  271. ConstantInt::get(Int32Ty, Behavior), MDString::get(Context, Key), Val
  272. };
  273. getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
  274. }
  275. void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
  276. uint32_t Val) {
  277. Type *Int32Ty = Type::getInt32Ty(Context);
  278. addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
  279. }
  280. void Module::addModuleFlag(MDNode *Node) {
  281. assert(Node->getNumOperands() == 3 &&
  282. "Invalid number of operands for module flag!");
  283. assert(isa<ConstantInt>(Node->getOperand(0)) &&
  284. isa<MDString>(Node->getOperand(1)) &&
  285. "Invalid operand types for module flag!");
  286. getOrInsertModuleFlagsMetadata()->addOperand(Node);
  287. }
  288. void Module::setDataLayout(StringRef Desc) {
  289. DL.reset(Desc);
  290. if (Desc.empty()) {
  291. DataLayoutStr = "";
  292. } else {
  293. DataLayoutStr = DL.getStringRepresentation();
  294. // DataLayoutStr is now equivalent to Desc, but since the representation
  295. // is not unique, they may not be identical.
  296. }
  297. }
  298. void Module::setDataLayout(const DataLayout *Other) {
  299. if (!Other) {
  300. DataLayoutStr = "";
  301. DL.reset("");
  302. } else {
  303. DL = *Other;
  304. DataLayoutStr = DL.getStringRepresentation();
  305. }
  306. }
  307. const DataLayout *Module::getDataLayout() const {
  308. if (DataLayoutStr.empty())
  309. return nullptr;
  310. return &DL;
  311. }
  312. //===----------------------------------------------------------------------===//
  313. // Methods to control the materialization of GlobalValues in the Module.
  314. //
  315. void Module::setMaterializer(GVMaterializer *GVM) {
  316. assert(!Materializer &&
  317. "Module already has a GVMaterializer. Call MaterializeAllPermanently"
  318. " to clear it out before setting another one.");
  319. Materializer.reset(GVM);
  320. }
  321. bool Module::isMaterializable(const GlobalValue *GV) const {
  322. if (Materializer)
  323. return Materializer->isMaterializable(GV);
  324. return false;
  325. }
  326. bool Module::isDematerializable(const GlobalValue *GV) const {
  327. if (Materializer)
  328. return Materializer->isDematerializable(GV);
  329. return false;
  330. }
  331. bool Module::Materialize(GlobalValue *GV, std::string *ErrInfo) {
  332. if (!Materializer)
  333. return false;
  334. error_code EC = Materializer->Materialize(GV);
  335. if (!EC)
  336. return false;
  337. if (ErrInfo)
  338. *ErrInfo = EC.message();
  339. return true;
  340. }
  341. void Module::Dematerialize(GlobalValue *GV) {
  342. if (Materializer)
  343. return Materializer->Dematerialize(GV);
  344. }
  345. error_code Module::materializeAll() {
  346. if (!Materializer)
  347. return error_code::success();
  348. return Materializer->MaterializeModule(this);
  349. }
  350. error_code Module::materializeAllPermanently() {
  351. if (error_code EC = materializeAll())
  352. return EC;
  353. Materializer.reset();
  354. return error_code::success();
  355. }
  356. //===----------------------------------------------------------------------===//
  357. // Other module related stuff.
  358. //
  359. // dropAllReferences() - This function causes all the subelements to "let go"
  360. // of all references that they are maintaining. This allows one to 'delete' a
  361. // whole module at a time, even though there may be circular references... first
  362. // all references are dropped, and all use counts go to zero. Then everything
  363. // is deleted for real. Note that no operations are valid on an object that
  364. // has "dropped all references", except operator delete.
  365. //
  366. void Module::dropAllReferences() {
  367. for(Module::iterator I = begin(), E = end(); I != E; ++I)
  368. I->dropAllReferences();
  369. for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
  370. I->dropAllReferences();
  371. for(Module::alias_iterator I = alias_begin(), E = alias_end(); I != E; ++I)
  372. I->dropAllReferences();
  373. }