Module.cpp 15 KB

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