Module.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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/STLExtras.h"
  16. #include "llvm/ADT/SmallPtrSet.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/DebugInfoMetadata.h"
  22. #include "llvm/IR/GVMaterializer.h"
  23. #include "llvm/IR/InstrTypes.h"
  24. #include "llvm/IR/LLVMContext.h"
  25. #include "llvm/IR/TypeFinder.h"
  26. #include "llvm/Support/Dwarf.h"
  27. #include "llvm/Support/Error.h"
  28. #include "llvm/Support/MemoryBuffer.h"
  29. #include "llvm/Support/Path.h"
  30. #include "llvm/Support/RandomNumberGenerator.h"
  31. #include <algorithm>
  32. #include <cstdlib>
  33. using namespace llvm;
  34. //===----------------------------------------------------------------------===//
  35. // Methods to implement the globals and functions lists.
  36. //
  37. // Explicit instantiations of SymbolTableListTraits since some of the methods
  38. // are not in the public header file.
  39. template class llvm::SymbolTableListTraits<Function>;
  40. template class llvm::SymbolTableListTraits<GlobalVariable>;
  41. template class llvm::SymbolTableListTraits<GlobalAlias>;
  42. template class llvm::SymbolTableListTraits<GlobalIFunc>;
  43. //===----------------------------------------------------------------------===//
  44. // Primitive Module methods.
  45. //
  46. Module::Module(StringRef MID, LLVMContext &C)
  47. : Context(C), Materializer(), ModuleID(MID), SourceFileName(MID), DL("") {
  48. ValSymTab = new ValueSymbolTable();
  49. NamedMDSymTab = new StringMap<NamedMDNode *>();
  50. Context.addModule(this);
  51. }
  52. Module::~Module() {
  53. Context.removeModule(this);
  54. dropAllReferences();
  55. GlobalList.clear();
  56. FunctionList.clear();
  57. AliasList.clear();
  58. IFuncList.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. void Module::getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const {
  96. return Context.getOperandBundleTags(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, FunctionType *Ty,
  107. AttributeList AttributeList) {
  108. // See if we have a definition for the specified function already.
  109. GlobalValue *F = getNamedValue(Name);
  110. if (!F) {
  111. // Nope, add it
  112. Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
  113. if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
  114. New->setAttributes(AttributeList);
  115. FunctionList.push_back(New);
  116. return New; // Return the new prototype.
  117. }
  118. // If the function exists but has the wrong type, return a bitcast to the
  119. // right type.
  120. if (F->getType() != PointerType::getUnqual(Ty))
  121. return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
  122. // Otherwise, we just found the existing function or a prototype.
  123. return F;
  124. }
  125. Constant *Module::getOrInsertFunction(StringRef Name,
  126. FunctionType *Ty) {
  127. return getOrInsertFunction(Name, Ty, AttributeList());
  128. }
  129. // getFunction - Look up the specified function in the module symbol table.
  130. // If it does not exist, return null.
  131. //
  132. Function *Module::getFunction(StringRef Name) const {
  133. return dyn_cast_or_null<Function>(getNamedValue(Name));
  134. }
  135. //===----------------------------------------------------------------------===//
  136. // Methods for easy access to the global variables in the module.
  137. //
  138. /// getGlobalVariable - Look up the specified global variable in the module
  139. /// symbol table. If it does not exist, return null. The type argument
  140. /// should be the underlying type of the global, i.e., it should not have
  141. /// the top-level PointerType, which represents the address of the global.
  142. /// If AllowLocal is set to true, this function will return types that
  143. /// have an local. By default, these types are not returned.
  144. ///
  145. GlobalVariable *Module::getGlobalVariable(StringRef Name,
  146. bool AllowLocal) const {
  147. if (GlobalVariable *Result =
  148. dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
  149. if (AllowLocal || !Result->hasLocalLinkage())
  150. return Result;
  151. return nullptr;
  152. }
  153. /// getOrInsertGlobal - Look up the specified global in the module symbol table.
  154. /// 1. If it does not exist, add a declaration of the global and return it.
  155. /// 2. Else, the global exists but has the wrong type: return the function
  156. /// with a constantexpr cast to the right type.
  157. /// 3. Finally, if the existing global is the correct declaration, return the
  158. /// existing global.
  159. Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
  160. // See if we have a definition for the specified global already.
  161. GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
  162. if (!GV) {
  163. // Nope, add it
  164. GlobalVariable *New =
  165. new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
  166. nullptr, Name);
  167. return New; // Return the new declaration.
  168. }
  169. // If the variable exists but has the wrong type, return a bitcast to the
  170. // right type.
  171. Type *GVTy = GV->getType();
  172. PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
  173. if (GVTy != PTy)
  174. return ConstantExpr::getBitCast(GV, PTy);
  175. // Otherwise, we just found the existing function or a prototype.
  176. return GV;
  177. }
  178. //===----------------------------------------------------------------------===//
  179. // Methods for easy access to the global variables in the module.
  180. //
  181. // getNamedAlias - Look up the specified global in the module symbol table.
  182. // If it does not exist, return null.
  183. //
  184. GlobalAlias *Module::getNamedAlias(StringRef Name) const {
  185. return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
  186. }
  187. GlobalIFunc *Module::getNamedIFunc(StringRef Name) const {
  188. return dyn_cast_or_null<GlobalIFunc>(getNamedValue(Name));
  189. }
  190. /// getNamedMetadata - Return the first NamedMDNode in the module with the
  191. /// specified name. This method returns null if a NamedMDNode with the
  192. /// specified name is not found.
  193. NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
  194. SmallString<256> NameData;
  195. StringRef NameRef = Name.toStringRef(NameData);
  196. return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
  197. }
  198. /// getOrInsertNamedMetadata - Return the first named MDNode in the module
  199. /// with the specified name. This method returns a new NamedMDNode if a
  200. /// NamedMDNode with the specified name is not found.
  201. NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
  202. NamedMDNode *&NMD =
  203. (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
  204. if (!NMD) {
  205. NMD = new NamedMDNode(Name);
  206. NMD->setParent(this);
  207. NamedMDList.push_back(NMD);
  208. }
  209. return NMD;
  210. }
  211. /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
  212. /// delete it.
  213. void Module::eraseNamedMetadata(NamedMDNode *NMD) {
  214. static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
  215. NamedMDList.erase(NMD->getIterator());
  216. }
  217. bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
  218. if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
  219. uint64_t Val = Behavior->getLimitedValue();
  220. if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
  221. MFB = static_cast<ModFlagBehavior>(Val);
  222. return true;
  223. }
  224. }
  225. return false;
  226. }
  227. /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
  228. void Module::
  229. getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
  230. const NamedMDNode *ModFlags = getModuleFlagsMetadata();
  231. if (!ModFlags) return;
  232. for (const MDNode *Flag : ModFlags->operands()) {
  233. ModFlagBehavior MFB;
  234. if (Flag->getNumOperands() >= 3 &&
  235. isValidModFlagBehavior(Flag->getOperand(0), MFB) &&
  236. dyn_cast_or_null<MDString>(Flag->getOperand(1))) {
  237. // Check the operands of the MDNode before accessing the operands.
  238. // The verifier will actually catch these failures.
  239. MDString *Key = cast<MDString>(Flag->getOperand(1));
  240. Metadata *Val = Flag->getOperand(2);
  241. Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
  242. }
  243. }
  244. }
  245. /// Return the corresponding value if Key appears in module flags, otherwise
  246. /// return null.
  247. Metadata *Module::getModuleFlag(StringRef Key) const {
  248. SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
  249. getModuleFlagsMetadata(ModuleFlags);
  250. for (const ModuleFlagEntry &MFE : ModuleFlags) {
  251. if (Key == MFE.Key->getString())
  252. return MFE.Val;
  253. }
  254. return nullptr;
  255. }
  256. /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
  257. /// represents module-level flags. This method returns null if there are no
  258. /// module-level flags.
  259. NamedMDNode *Module::getModuleFlagsMetadata() const {
  260. return getNamedMetadata("llvm.module.flags");
  261. }
  262. /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
  263. /// represents module-level flags. If module-level flags aren't found, it
  264. /// creates the named metadata that contains them.
  265. NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
  266. return getOrInsertNamedMetadata("llvm.module.flags");
  267. }
  268. /// addModuleFlag - Add a module-level flag to the module-level flags
  269. /// metadata. It will create the module-level flags named metadata if it doesn't
  270. /// already exist.
  271. void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
  272. Metadata *Val) {
  273. Type *Int32Ty = Type::getInt32Ty(Context);
  274. Metadata *Ops[3] = {
  275. ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
  276. MDString::get(Context, Key), Val};
  277. getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
  278. }
  279. void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
  280. Constant *Val) {
  281. addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
  282. }
  283. void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
  284. uint32_t Val) {
  285. Type *Int32Ty = Type::getInt32Ty(Context);
  286. addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
  287. }
  288. void Module::addModuleFlag(MDNode *Node) {
  289. assert(Node->getNumOperands() == 3 &&
  290. "Invalid number of operands for module flag!");
  291. assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
  292. isa<MDString>(Node->getOperand(1)) &&
  293. "Invalid operand types for module flag!");
  294. getOrInsertModuleFlagsMetadata()->addOperand(Node);
  295. }
  296. void Module::setDataLayout(StringRef Desc) {
  297. DL.reset(Desc);
  298. }
  299. void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
  300. const DataLayout &Module::getDataLayout() const { return DL; }
  301. DICompileUnit *Module::debug_compile_units_iterator::operator*() const {
  302. return cast<DICompileUnit>(CUs->getOperand(Idx));
  303. }
  304. DICompileUnit *Module::debug_compile_units_iterator::operator->() const {
  305. return cast<DICompileUnit>(CUs->getOperand(Idx));
  306. }
  307. void Module::debug_compile_units_iterator::SkipNoDebugCUs() {
  308. while (CUs && (Idx < CUs->getNumOperands()) &&
  309. ((*this)->getEmissionKind() == DICompileUnit::NoDebug))
  310. ++Idx;
  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 materializeAll"
  318. " to clear it out before setting another one.");
  319. Materializer.reset(GVM);
  320. }
  321. Error Module::materialize(GlobalValue *GV) {
  322. if (!Materializer)
  323. return Error::success();
  324. return Materializer->materialize(GV);
  325. }
  326. Error Module::materializeAll() {
  327. if (!Materializer)
  328. return Error::success();
  329. std::unique_ptr<GVMaterializer> M = std::move(Materializer);
  330. return M->materializeModule();
  331. }
  332. Error Module::materializeMetadata() {
  333. if (!Materializer)
  334. return Error::success();
  335. return Materializer->materializeMetadata();
  336. }
  337. //===----------------------------------------------------------------------===//
  338. // Other module related stuff.
  339. //
  340. std::vector<StructType *> Module::getIdentifiedStructTypes() const {
  341. // If we have a materializer, it is possible that some unread function
  342. // uses a type that is currently not visible to a TypeFinder, so ask
  343. // the materializer which types it created.
  344. if (Materializer)
  345. return Materializer->getIdentifiedStructTypes();
  346. std::vector<StructType *> Ret;
  347. TypeFinder SrcStructTypes;
  348. SrcStructTypes.run(*this, true);
  349. Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
  350. return Ret;
  351. }
  352. // dropAllReferences() - This function causes all the subelements to "let go"
  353. // of all references that they are maintaining. This allows one to 'delete' a
  354. // whole module at a time, even though there may be circular references... first
  355. // all references are dropped, and all use counts go to zero. Then everything
  356. // is deleted for real. Note that no operations are valid on an object that
  357. // has "dropped all references", except operator delete.
  358. //
  359. void Module::dropAllReferences() {
  360. for (Function &F : *this)
  361. F.dropAllReferences();
  362. for (GlobalVariable &GV : globals())
  363. GV.dropAllReferences();
  364. for (GlobalAlias &GA : aliases())
  365. GA.dropAllReferences();
  366. for (GlobalIFunc &GIF : ifuncs())
  367. GIF.dropAllReferences();
  368. }
  369. unsigned Module::getNumberRegisterParameters() const {
  370. auto *Val =
  371. cast_or_null<ConstantAsMetadata>(getModuleFlag("NumRegisterParameters"));
  372. if (!Val)
  373. return 0;
  374. return cast<ConstantInt>(Val->getValue())->getZExtValue();
  375. }
  376. unsigned Module::getDwarfVersion() const {
  377. auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
  378. if (!Val)
  379. return 0;
  380. return cast<ConstantInt>(Val->getValue())->getZExtValue();
  381. }
  382. unsigned Module::getCodeViewFlag() const {
  383. auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("CodeView"));
  384. if (!Val)
  385. return 0;
  386. return cast<ConstantInt>(Val->getValue())->getZExtValue();
  387. }
  388. Comdat *Module::getOrInsertComdat(StringRef Name) {
  389. auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
  390. Entry.second.Name = &Entry;
  391. return &Entry.second;
  392. }
  393. PICLevel::Level Module::getPICLevel() const {
  394. auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
  395. if (!Val)
  396. return PICLevel::NotPIC;
  397. return static_cast<PICLevel::Level>(
  398. cast<ConstantInt>(Val->getValue())->getZExtValue());
  399. }
  400. void Module::setPICLevel(PICLevel::Level PL) {
  401. addModuleFlag(ModFlagBehavior::Error, "PIC Level", PL);
  402. }
  403. PIELevel::Level Module::getPIELevel() const {
  404. auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIE Level"));
  405. if (!Val)
  406. return PIELevel::Default;
  407. return static_cast<PIELevel::Level>(
  408. cast<ConstantInt>(Val->getValue())->getZExtValue());
  409. }
  410. void Module::setPIELevel(PIELevel::Level PL) {
  411. addModuleFlag(ModFlagBehavior::Error, "PIE Level", PL);
  412. }
  413. void Module::setProfileSummary(Metadata *M) {
  414. addModuleFlag(ModFlagBehavior::Error, "ProfileSummary", M);
  415. }
  416. Metadata *Module::getProfileSummary() {
  417. return getModuleFlag("ProfileSummary");
  418. }
  419. void Module::setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB) {
  420. OwnedMemoryBuffer = std::move(MB);
  421. }
  422. GlobalVariable *llvm::collectUsedGlobalVariables(
  423. const Module &M, SmallPtrSetImpl<GlobalValue *> &Set, bool CompilerUsed) {
  424. const char *Name = CompilerUsed ? "llvm.compiler.used" : "llvm.used";
  425. GlobalVariable *GV = M.getGlobalVariable(Name);
  426. if (!GV || !GV->hasInitializer())
  427. return GV;
  428. const ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
  429. for (Value *Op : Init->operands()) {
  430. GlobalValue *G = cast<GlobalValue>(Op->stripPointerCastsNoFollowAliases());
  431. Set.insert(G);
  432. }
  433. return GV;
  434. }