Module.cpp 17 KB

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