2
0

Module.cpp 18 KB

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