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