Module.h 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/Module.h - C++ class to represent a VM module -------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. /// @file
  15. /// Module.h This file contains the declarations for the Module class.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_IR_MODULE_H
  19. #define LLVM_IR_MODULE_H
  20. #include "llvm-c/Types.h"
  21. #include "llvm/ADT/STLExtras.h"
  22. #include "llvm/ADT/StringMap.h"
  23. #include "llvm/ADT/StringRef.h"
  24. #include "llvm/ADT/iterator_range.h"
  25. #include "llvm/IR/Attributes.h"
  26. #include "llvm/IR/Comdat.h"
  27. #include "llvm/IR/DataLayout.h"
  28. #include "llvm/IR/Function.h"
  29. #include "llvm/IR/GlobalAlias.h"
  30. #include "llvm/IR/GlobalIFunc.h"
  31. #include "llvm/IR/GlobalVariable.h"
  32. #include "llvm/IR/Metadata.h"
  33. #include "llvm/IR/ProfileSummary.h"
  34. #include "llvm/IR/SymbolTableListTraits.h"
  35. #include "llvm/Support/CBindingWrapping.h"
  36. #include "llvm/Support/CodeGen.h"
  37. #include <cstddef>
  38. #include <cstdint>
  39. #include <iterator>
  40. #include <memory>
  41. #include <optional>
  42. #include <string>
  43. #include <vector>
  44. namespace llvm {
  45. class Error;
  46. class FunctionType;
  47. class GVMaterializer;
  48. class LLVMContext;
  49. class MemoryBuffer;
  50. class ModuleSummaryIndex;
  51. class RandomNumberGenerator;
  52. class StructType;
  53. class VersionTuple;
  54. /// A Module instance is used to store all the information related to an
  55. /// LLVM module. Modules are the top level container of all other LLVM
  56. /// Intermediate Representation (IR) objects. Each module directly contains a
  57. /// list of globals variables, a list of functions, a list of libraries (or
  58. /// other modules) this module depends on, a symbol table, and various data
  59. /// about the target's characteristics.
  60. ///
  61. /// A module maintains a GlobalList object that is used to hold all
  62. /// constant references to global variables in the module. When a global
  63. /// variable is destroyed, it should have no entries in the GlobalList.
  64. /// The main container class for the LLVM Intermediate Representation.
  65. class LLVM_EXTERNAL_VISIBILITY Module {
  66. /// @name Types And Enumerations
  67. /// @{
  68. public:
  69. /// The type for the list of global variables.
  70. using GlobalListType = SymbolTableList<GlobalVariable>;
  71. /// The type for the list of functions.
  72. using FunctionListType = SymbolTableList<Function>;
  73. /// The type for the list of aliases.
  74. using AliasListType = SymbolTableList<GlobalAlias>;
  75. /// The type for the list of ifuncs.
  76. using IFuncListType = SymbolTableList<GlobalIFunc>;
  77. /// The type for the list of named metadata.
  78. using NamedMDListType = ilist<NamedMDNode>;
  79. /// The type of the comdat "symbol" table.
  80. using ComdatSymTabType = StringMap<Comdat>;
  81. /// The type for mapping names to named metadata.
  82. using NamedMDSymTabType = StringMap<NamedMDNode *>;
  83. /// The Global Variable iterator.
  84. using global_iterator = GlobalListType::iterator;
  85. /// The Global Variable constant iterator.
  86. using const_global_iterator = GlobalListType::const_iterator;
  87. /// The Function iterators.
  88. using iterator = FunctionListType::iterator;
  89. /// The Function constant iterator
  90. using const_iterator = FunctionListType::const_iterator;
  91. /// The Function reverse iterator.
  92. using reverse_iterator = FunctionListType::reverse_iterator;
  93. /// The Function constant reverse iterator.
  94. using const_reverse_iterator = FunctionListType::const_reverse_iterator;
  95. /// The Global Alias iterators.
  96. using alias_iterator = AliasListType::iterator;
  97. /// The Global Alias constant iterator
  98. using const_alias_iterator = AliasListType::const_iterator;
  99. /// The Global IFunc iterators.
  100. using ifunc_iterator = IFuncListType::iterator;
  101. /// The Global IFunc constant iterator
  102. using const_ifunc_iterator = IFuncListType::const_iterator;
  103. /// The named metadata iterators.
  104. using named_metadata_iterator = NamedMDListType::iterator;
  105. /// The named metadata constant iterators.
  106. using const_named_metadata_iterator = NamedMDListType::const_iterator;
  107. /// This enumeration defines the supported behaviors of module flags.
  108. enum ModFlagBehavior {
  109. /// Emits an error if two values disagree, otherwise the resulting value is
  110. /// that of the operands.
  111. Error = 1,
  112. /// Emits a warning if two values disagree. The result value will be the
  113. /// operand for the flag from the first module being linked.
  114. Warning = 2,
  115. /// Adds a requirement that another module flag be present and have a
  116. /// specified value after linking is performed. The value must be a metadata
  117. /// pair, where the first element of the pair is the ID of the module flag
  118. /// to be restricted, and the second element of the pair is the value the
  119. /// module flag should be restricted to. This behavior can be used to
  120. /// restrict the allowable results (via triggering of an error) of linking
  121. /// IDs with the **Override** behavior.
  122. Require = 3,
  123. /// Uses the specified value, regardless of the behavior or value of the
  124. /// other module. If both modules specify **Override**, but the values
  125. /// differ, an error will be emitted.
  126. Override = 4,
  127. /// Appends the two values, which are required to be metadata nodes.
  128. Append = 5,
  129. /// Appends the two values, which are required to be metadata
  130. /// nodes. However, duplicate entries in the second list are dropped
  131. /// during the append operation.
  132. AppendUnique = 6,
  133. /// Takes the max of the two values, which are required to be integers.
  134. Max = 7,
  135. /// Takes the min of the two values, which are required to be integers.
  136. Min = 8,
  137. // Markers:
  138. ModFlagBehaviorFirstVal = Error,
  139. ModFlagBehaviorLastVal = Min
  140. };
  141. /// Checks if Metadata represents a valid ModFlagBehavior, and stores the
  142. /// converted result in MFB.
  143. static bool isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB);
  144. /// Check if the given module flag metadata represents a valid module flag,
  145. /// and store the flag behavior, the key string and the value metadata.
  146. static bool isValidModuleFlag(const MDNode &ModFlag, ModFlagBehavior &MFB,
  147. MDString *&Key, Metadata *&Val);
  148. struct ModuleFlagEntry {
  149. ModFlagBehavior Behavior;
  150. MDString *Key;
  151. Metadata *Val;
  152. ModuleFlagEntry(ModFlagBehavior B, MDString *K, Metadata *V)
  153. : Behavior(B), Key(K), Val(V) {}
  154. };
  155. /// @}
  156. /// @name Member Variables
  157. /// @{
  158. private:
  159. LLVMContext &Context; ///< The LLVMContext from which types and
  160. ///< constants are allocated.
  161. GlobalListType GlobalList; ///< The Global Variables in the module
  162. FunctionListType FunctionList; ///< The Functions in the module
  163. AliasListType AliasList; ///< The Aliases in the module
  164. IFuncListType IFuncList; ///< The IFuncs in the module
  165. NamedMDListType NamedMDList; ///< The named metadata in the module
  166. std::string GlobalScopeAsm; ///< Inline Asm at global scope.
  167. std::unique_ptr<ValueSymbolTable> ValSymTab; ///< Symbol table for values
  168. ComdatSymTabType ComdatSymTab; ///< Symbol table for COMDATs
  169. std::unique_ptr<MemoryBuffer>
  170. OwnedMemoryBuffer; ///< Memory buffer directly owned by this
  171. ///< module, for legacy clients only.
  172. std::unique_ptr<GVMaterializer>
  173. Materializer; ///< Used to materialize GlobalValues
  174. std::string ModuleID; ///< Human readable identifier for the module
  175. std::string SourceFileName; ///< Original source file name for module,
  176. ///< recorded in bitcode.
  177. std::string TargetTriple; ///< Platform target triple Module compiled on
  178. ///< Format: (arch)(sub)-(vendor)-(sys0-(abi)
  179. NamedMDSymTabType NamedMDSymTab; ///< NamedMDNode names.
  180. DataLayout DL; ///< DataLayout associated with the module
  181. StringMap<unsigned>
  182. CurrentIntrinsicIds; ///< Keep track of the current unique id count for
  183. ///< the specified intrinsic basename.
  184. DenseMap<std::pair<Intrinsic::ID, const FunctionType *>, unsigned>
  185. UniquedIntrinsicNames; ///< Keep track of uniqued names of intrinsics
  186. ///< based on unnamed types. The combination of
  187. ///< ID and FunctionType maps to the extension that
  188. ///< is used to make the intrinsic name unique.
  189. friend class Constant;
  190. /// @}
  191. /// @name Constructors
  192. /// @{
  193. public:
  194. /// The Module constructor. Note that there is no default constructor. You
  195. /// must provide a name for the module upon construction.
  196. explicit Module(StringRef ModuleID, LLVMContext& C);
  197. /// The module destructor. This will dropAllReferences.
  198. ~Module();
  199. /// @}
  200. /// @name Module Level Accessors
  201. /// @{
  202. /// Get the module identifier which is, essentially, the name of the module.
  203. /// @returns the module identifier as a string
  204. const std::string &getModuleIdentifier() const { return ModuleID; }
  205. /// Returns the number of non-debug IR instructions in the module.
  206. /// This is equivalent to the sum of the IR instruction counts of each
  207. /// function contained in the module.
  208. unsigned getInstructionCount() const;
  209. /// Get the module's original source file name. When compiling from
  210. /// bitcode, this is taken from a bitcode record where it was recorded.
  211. /// For other compiles it is the same as the ModuleID, which would
  212. /// contain the source file name.
  213. const std::string &getSourceFileName() const { return SourceFileName; }
  214. /// Get a short "name" for the module.
  215. ///
  216. /// This is useful for debugging or logging. It is essentially a convenience
  217. /// wrapper around getModuleIdentifier().
  218. StringRef getName() const { return ModuleID; }
  219. /// Get the data layout string for the module's target platform. This is
  220. /// equivalent to getDataLayout()->getStringRepresentation().
  221. const std::string &getDataLayoutStr() const {
  222. return DL.getStringRepresentation();
  223. }
  224. /// Get the data layout for the module's target platform.
  225. const DataLayout &getDataLayout() const;
  226. /// Get the target triple which is a string describing the target host.
  227. /// @returns a string containing the target triple.
  228. const std::string &getTargetTriple() const { return TargetTriple; }
  229. /// Get the global data context.
  230. /// @returns LLVMContext - a container for LLVM's global information
  231. LLVMContext &getContext() const { return Context; }
  232. /// Get any module-scope inline assembly blocks.
  233. /// @returns a string containing the module-scope inline assembly blocks.
  234. const std::string &getModuleInlineAsm() const { return GlobalScopeAsm; }
  235. /// Get a RandomNumberGenerator salted for use with this module. The
  236. /// RNG can be seeded via -rng-seed=<uint64> and is salted with the
  237. /// ModuleID and the provided pass salt. The returned RNG should not
  238. /// be shared across threads or passes.
  239. ///
  240. /// A unique RNG per pass ensures a reproducible random stream even
  241. /// when other randomness consuming passes are added or removed. In
  242. /// addition, the random stream will be reproducible across LLVM
  243. /// versions when the pass does not change.
  244. std::unique_ptr<RandomNumberGenerator> createRNG(const StringRef Name) const;
  245. /// Return true if size-info optimization remark is enabled, false
  246. /// otherwise.
  247. bool shouldEmitInstrCountChangedRemark() {
  248. return getContext().getDiagHandlerPtr()->isAnalysisRemarkEnabled(
  249. "size-info");
  250. }
  251. /// @}
  252. /// @name Module Level Mutators
  253. /// @{
  254. /// Set the module identifier.
  255. void setModuleIdentifier(StringRef ID) { ModuleID = std::string(ID); }
  256. /// Set the module's original source file name.
  257. void setSourceFileName(StringRef Name) { SourceFileName = std::string(Name); }
  258. /// Set the data layout
  259. void setDataLayout(StringRef Desc);
  260. void setDataLayout(const DataLayout &Other);
  261. /// Set the target triple.
  262. void setTargetTriple(StringRef T) { TargetTriple = std::string(T); }
  263. /// Set the module-scope inline assembly blocks.
  264. /// A trailing newline is added if the input doesn't have one.
  265. void setModuleInlineAsm(StringRef Asm) {
  266. GlobalScopeAsm = std::string(Asm);
  267. if (!GlobalScopeAsm.empty() && GlobalScopeAsm.back() != '\n')
  268. GlobalScopeAsm += '\n';
  269. }
  270. /// Append to the module-scope inline assembly blocks.
  271. /// A trailing newline is added if the input doesn't have one.
  272. void appendModuleInlineAsm(StringRef Asm) {
  273. GlobalScopeAsm += Asm;
  274. if (!GlobalScopeAsm.empty() && GlobalScopeAsm.back() != '\n')
  275. GlobalScopeAsm += '\n';
  276. }
  277. /// @}
  278. /// @name Generic Value Accessors
  279. /// @{
  280. /// Return the global value in the module with the specified name, of
  281. /// arbitrary type. This method returns null if a global with the specified
  282. /// name is not found.
  283. GlobalValue *getNamedValue(StringRef Name) const;
  284. /// Return the number of global values in the module.
  285. unsigned getNumNamedValues() const;
  286. /// Return a unique non-zero ID for the specified metadata kind. This ID is
  287. /// uniqued across modules in the current LLVMContext.
  288. unsigned getMDKindID(StringRef Name) const;
  289. /// Populate client supplied SmallVector with the name for custom metadata IDs
  290. /// registered in this LLVMContext.
  291. void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
  292. /// Populate client supplied SmallVector with the bundle tags registered in
  293. /// this LLVMContext. The bundle tags are ordered by increasing bundle IDs.
  294. /// \see LLVMContext::getOperandBundleTagID
  295. void getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const;
  296. std::vector<StructType *> getIdentifiedStructTypes() const;
  297. /// Return a unique name for an intrinsic whose mangling is based on an
  298. /// unnamed type. The Proto represents the function prototype.
  299. std::string getUniqueIntrinsicName(StringRef BaseName, Intrinsic::ID Id,
  300. const FunctionType *Proto);
  301. /// @}
  302. /// @name Function Accessors
  303. /// @{
  304. /// Look up the specified function in the module symbol table. Four
  305. /// possibilities:
  306. /// 1. If it does not exist, add a prototype for the function and return it.
  307. /// 2. Otherwise, if the existing function has the correct prototype, return
  308. /// the existing function.
  309. /// 3. Finally, the function exists but has the wrong prototype: return the
  310. /// function with a constantexpr cast to the right prototype.
  311. ///
  312. /// In all cases, the returned value is a FunctionCallee wrapper around the
  313. /// 'FunctionType *T' passed in, as well as a 'Value*' either of the Function or
  314. /// the bitcast to the function.
  315. ///
  316. /// Note: For library calls getOrInsertLibFunc() should be used instead.
  317. FunctionCallee getOrInsertFunction(StringRef Name, FunctionType *T,
  318. AttributeList AttributeList);
  319. FunctionCallee getOrInsertFunction(StringRef Name, FunctionType *T);
  320. /// Look up the specified function in the module symbol table. If it does not
  321. /// exist, add a prototype for the function and return it. This function
  322. /// guarantees to return a constant of pointer to the specified function type
  323. /// or a ConstantExpr BitCast of that type if the named function has a
  324. /// different type. This version of the method takes a list of
  325. /// function arguments, which makes it easier for clients to use.
  326. template <typename... ArgsTy>
  327. FunctionCallee getOrInsertFunction(StringRef Name,
  328. AttributeList AttributeList, Type *RetTy,
  329. ArgsTy... Args) {
  330. SmallVector<Type*, sizeof...(ArgsTy)> ArgTys{Args...};
  331. return getOrInsertFunction(Name,
  332. FunctionType::get(RetTy, ArgTys, false),
  333. AttributeList);
  334. }
  335. /// Same as above, but without the attributes.
  336. template <typename... ArgsTy>
  337. FunctionCallee getOrInsertFunction(StringRef Name, Type *RetTy,
  338. ArgsTy... Args) {
  339. return getOrInsertFunction(Name, AttributeList{}, RetTy, Args...);
  340. }
  341. // Avoid an incorrect ordering that'd otherwise compile incorrectly.
  342. template <typename... ArgsTy>
  343. FunctionCallee
  344. getOrInsertFunction(StringRef Name, AttributeList AttributeList,
  345. FunctionType *Invalid, ArgsTy... Args) = delete;
  346. /// Look up the specified function in the module symbol table. If it does not
  347. /// exist, return null.
  348. Function *getFunction(StringRef Name) const;
  349. /// @}
  350. /// @name Global Variable Accessors
  351. /// @{
  352. /// Look up the specified global variable in the module symbol table. If it
  353. /// does not exist, return null. If AllowInternal is set to true, this
  354. /// function will return types that have InternalLinkage. By default, these
  355. /// types are not returned.
  356. GlobalVariable *getGlobalVariable(StringRef Name) const {
  357. return getGlobalVariable(Name, false);
  358. }
  359. GlobalVariable *getGlobalVariable(StringRef Name, bool AllowInternal) const;
  360. GlobalVariable *getGlobalVariable(StringRef Name,
  361. bool AllowInternal = false) {
  362. return static_cast<const Module *>(this)->getGlobalVariable(Name,
  363. AllowInternal);
  364. }
  365. /// Return the global variable in the module with the specified name, of
  366. /// arbitrary type. This method returns null if a global with the specified
  367. /// name is not found.
  368. const GlobalVariable *getNamedGlobal(StringRef Name) const {
  369. return getGlobalVariable(Name, true);
  370. }
  371. GlobalVariable *getNamedGlobal(StringRef Name) {
  372. return const_cast<GlobalVariable *>(
  373. static_cast<const Module *>(this)->getNamedGlobal(Name));
  374. }
  375. /// Look up the specified global in the module symbol table.
  376. /// If it does not exist, invoke a callback to create a declaration of the
  377. /// global and return it. The global is constantexpr casted to the expected
  378. /// type if necessary.
  379. Constant *
  380. getOrInsertGlobal(StringRef Name, Type *Ty,
  381. function_ref<GlobalVariable *()> CreateGlobalCallback);
  382. /// Look up the specified global in the module symbol table. If required, this
  383. /// overload constructs the global variable using its constructor's defaults.
  384. Constant *getOrInsertGlobal(StringRef Name, Type *Ty);
  385. /// @}
  386. /// @name Global Alias Accessors
  387. /// @{
  388. /// Return the global alias in the module with the specified name, of
  389. /// arbitrary type. This method returns null if a global with the specified
  390. /// name is not found.
  391. GlobalAlias *getNamedAlias(StringRef Name) const;
  392. /// @}
  393. /// @name Global IFunc Accessors
  394. /// @{
  395. /// Return the global ifunc in the module with the specified name, of
  396. /// arbitrary type. This method returns null if a global with the specified
  397. /// name is not found.
  398. GlobalIFunc *getNamedIFunc(StringRef Name) const;
  399. /// @}
  400. /// @name Named Metadata Accessors
  401. /// @{
  402. /// Return the first NamedMDNode in the module with the specified name. This
  403. /// method returns null if a NamedMDNode with the specified name is not found.
  404. NamedMDNode *getNamedMetadata(const Twine &Name) const;
  405. /// Return the named MDNode in the module with the specified name. This method
  406. /// returns a new NamedMDNode if a NamedMDNode with the specified name is not
  407. /// found.
  408. NamedMDNode *getOrInsertNamedMetadata(StringRef Name);
  409. /// Remove the given NamedMDNode from this module and delete it.
  410. void eraseNamedMetadata(NamedMDNode *NMD);
  411. /// @}
  412. /// @name Comdat Accessors
  413. /// @{
  414. /// Return the Comdat in the module with the specified name. It is created
  415. /// if it didn't already exist.
  416. Comdat *getOrInsertComdat(StringRef Name);
  417. /// @}
  418. /// @name Module Flags Accessors
  419. /// @{
  420. /// Returns the module flags in the provided vector.
  421. void getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const;
  422. /// Return the corresponding value if Key appears in module flags, otherwise
  423. /// return null.
  424. Metadata *getModuleFlag(StringRef Key) const;
  425. /// Returns the NamedMDNode in the module that represents module-level flags.
  426. /// This method returns null if there are no module-level flags.
  427. NamedMDNode *getModuleFlagsMetadata() const;
  428. /// Returns the NamedMDNode in the module that represents module-level flags.
  429. /// If module-level flags aren't found, it creates the named metadata that
  430. /// contains them.
  431. NamedMDNode *getOrInsertModuleFlagsMetadata();
  432. /// Add a module-level flag to the module-level flags metadata. It will create
  433. /// the module-level flags named metadata if it doesn't already exist.
  434. void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Metadata *Val);
  435. void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Constant *Val);
  436. void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, uint32_t Val);
  437. void addModuleFlag(MDNode *Node);
  438. /// Like addModuleFlag but replaces the old module flag if it already exists.
  439. void setModuleFlag(ModFlagBehavior Behavior, StringRef Key, Metadata *Val);
  440. /// @}
  441. /// @name Materialization
  442. /// @{
  443. /// Sets the GVMaterializer to GVM. This module must not yet have a
  444. /// Materializer. To reset the materializer for a module that already has one,
  445. /// call materializeAll first. Destroying this module will destroy
  446. /// its materializer without materializing any more GlobalValues. Without
  447. /// destroying the Module, there is no way to detach or destroy a materializer
  448. /// without materializing all the GVs it controls, to avoid leaving orphan
  449. /// unmaterialized GVs.
  450. void setMaterializer(GVMaterializer *GVM);
  451. /// Retrieves the GVMaterializer, if any, for this Module.
  452. GVMaterializer *getMaterializer() const { return Materializer.get(); }
  453. bool isMaterialized() const { return !getMaterializer(); }
  454. /// Make sure the GlobalValue is fully read.
  455. llvm::Error materialize(GlobalValue *GV);
  456. /// Make sure all GlobalValues in this Module are fully read and clear the
  457. /// Materializer.
  458. llvm::Error materializeAll();
  459. llvm::Error materializeMetadata();
  460. /// @}
  461. /// @name Direct access to the globals list, functions list, and symbol table
  462. /// @{
  463. /// Get the Module's list of global variables (constant).
  464. const GlobalListType &getGlobalList() const { return GlobalList; }
  465. /// Get the Module's list of global variables.
  466. GlobalListType &getGlobalList() { return GlobalList; }
  467. static GlobalListType Module::*getSublistAccess(GlobalVariable*) {
  468. return &Module::GlobalList;
  469. }
  470. /// Get the Module's list of functions (constant).
  471. const FunctionListType &getFunctionList() const { return FunctionList; }
  472. /// Get the Module's list of functions.
  473. FunctionListType &getFunctionList() { return FunctionList; }
  474. static FunctionListType Module::*getSublistAccess(Function*) {
  475. return &Module::FunctionList;
  476. }
  477. /// Get the Module's list of aliases (constant).
  478. const AliasListType &getAliasList() const { return AliasList; }
  479. /// Get the Module's list of aliases.
  480. AliasListType &getAliasList() { return AliasList; }
  481. static AliasListType Module::*getSublistAccess(GlobalAlias*) {
  482. return &Module::AliasList;
  483. }
  484. /// Get the Module's list of ifuncs (constant).
  485. const IFuncListType &getIFuncList() const { return IFuncList; }
  486. /// Get the Module's list of ifuncs.
  487. IFuncListType &getIFuncList() { return IFuncList; }
  488. static IFuncListType Module::*getSublistAccess(GlobalIFunc*) {
  489. return &Module::IFuncList;
  490. }
  491. /// Get the Module's list of named metadata (constant).
  492. const NamedMDListType &getNamedMDList() const { return NamedMDList; }
  493. /// Get the Module's list of named metadata.
  494. NamedMDListType &getNamedMDList() { return NamedMDList; }
  495. static NamedMDListType Module::*getSublistAccess(NamedMDNode*) {
  496. return &Module::NamedMDList;
  497. }
  498. /// Get the symbol table of global variable and function identifiers
  499. const ValueSymbolTable &getValueSymbolTable() const { return *ValSymTab; }
  500. /// Get the Module's symbol table of global variable and function identifiers.
  501. ValueSymbolTable &getValueSymbolTable() { return *ValSymTab; }
  502. /// Get the Module's symbol table for COMDATs (constant).
  503. const ComdatSymTabType &getComdatSymbolTable() const { return ComdatSymTab; }
  504. /// Get the Module's symbol table for COMDATs.
  505. ComdatSymTabType &getComdatSymbolTable() { return ComdatSymTab; }
  506. /// @}
  507. /// @name Global Variable Iteration
  508. /// @{
  509. global_iterator global_begin() { return GlobalList.begin(); }
  510. const_global_iterator global_begin() const { return GlobalList.begin(); }
  511. global_iterator global_end () { return GlobalList.end(); }
  512. const_global_iterator global_end () const { return GlobalList.end(); }
  513. size_t global_size () const { return GlobalList.size(); }
  514. bool global_empty() const { return GlobalList.empty(); }
  515. iterator_range<global_iterator> globals() {
  516. return make_range(global_begin(), global_end());
  517. }
  518. iterator_range<const_global_iterator> globals() const {
  519. return make_range(global_begin(), global_end());
  520. }
  521. /// @}
  522. /// @name Function Iteration
  523. /// @{
  524. iterator begin() { return FunctionList.begin(); }
  525. const_iterator begin() const { return FunctionList.begin(); }
  526. iterator end () { return FunctionList.end(); }
  527. const_iterator end () const { return FunctionList.end(); }
  528. reverse_iterator rbegin() { return FunctionList.rbegin(); }
  529. const_reverse_iterator rbegin() const{ return FunctionList.rbegin(); }
  530. reverse_iterator rend() { return FunctionList.rend(); }
  531. const_reverse_iterator rend() const { return FunctionList.rend(); }
  532. size_t size() const { return FunctionList.size(); }
  533. bool empty() const { return FunctionList.empty(); }
  534. iterator_range<iterator> functions() {
  535. return make_range(begin(), end());
  536. }
  537. iterator_range<const_iterator> functions() const {
  538. return make_range(begin(), end());
  539. }
  540. /// @}
  541. /// @name Alias Iteration
  542. /// @{
  543. alias_iterator alias_begin() { return AliasList.begin(); }
  544. const_alias_iterator alias_begin() const { return AliasList.begin(); }
  545. alias_iterator alias_end () { return AliasList.end(); }
  546. const_alias_iterator alias_end () const { return AliasList.end(); }
  547. size_t alias_size () const { return AliasList.size(); }
  548. bool alias_empty() const { return AliasList.empty(); }
  549. iterator_range<alias_iterator> aliases() {
  550. return make_range(alias_begin(), alias_end());
  551. }
  552. iterator_range<const_alias_iterator> aliases() const {
  553. return make_range(alias_begin(), alias_end());
  554. }
  555. /// @}
  556. /// @name IFunc Iteration
  557. /// @{
  558. ifunc_iterator ifunc_begin() { return IFuncList.begin(); }
  559. const_ifunc_iterator ifunc_begin() const { return IFuncList.begin(); }
  560. ifunc_iterator ifunc_end () { return IFuncList.end(); }
  561. const_ifunc_iterator ifunc_end () const { return IFuncList.end(); }
  562. size_t ifunc_size () const { return IFuncList.size(); }
  563. bool ifunc_empty() const { return IFuncList.empty(); }
  564. iterator_range<ifunc_iterator> ifuncs() {
  565. return make_range(ifunc_begin(), ifunc_end());
  566. }
  567. iterator_range<const_ifunc_iterator> ifuncs() const {
  568. return make_range(ifunc_begin(), ifunc_end());
  569. }
  570. /// @}
  571. /// @name Convenience iterators
  572. /// @{
  573. using global_object_iterator =
  574. concat_iterator<GlobalObject, iterator, global_iterator>;
  575. using const_global_object_iterator =
  576. concat_iterator<const GlobalObject, const_iterator,
  577. const_global_iterator>;
  578. iterator_range<global_object_iterator> global_objects();
  579. iterator_range<const_global_object_iterator> global_objects() const;
  580. using global_value_iterator =
  581. concat_iterator<GlobalValue, iterator, global_iterator, alias_iterator,
  582. ifunc_iterator>;
  583. using const_global_value_iterator =
  584. concat_iterator<const GlobalValue, const_iterator, const_global_iterator,
  585. const_alias_iterator, const_ifunc_iterator>;
  586. iterator_range<global_value_iterator> global_values();
  587. iterator_range<const_global_value_iterator> global_values() const;
  588. /// @}
  589. /// @name Named Metadata Iteration
  590. /// @{
  591. named_metadata_iterator named_metadata_begin() { return NamedMDList.begin(); }
  592. const_named_metadata_iterator named_metadata_begin() const {
  593. return NamedMDList.begin();
  594. }
  595. named_metadata_iterator named_metadata_end() { return NamedMDList.end(); }
  596. const_named_metadata_iterator named_metadata_end() const {
  597. return NamedMDList.end();
  598. }
  599. size_t named_metadata_size() const { return NamedMDList.size(); }
  600. bool named_metadata_empty() const { return NamedMDList.empty(); }
  601. iterator_range<named_metadata_iterator> named_metadata() {
  602. return make_range(named_metadata_begin(), named_metadata_end());
  603. }
  604. iterator_range<const_named_metadata_iterator> named_metadata() const {
  605. return make_range(named_metadata_begin(), named_metadata_end());
  606. }
  607. /// An iterator for DICompileUnits that skips those marked NoDebug.
  608. class debug_compile_units_iterator {
  609. NamedMDNode *CUs;
  610. unsigned Idx;
  611. void SkipNoDebugCUs();
  612. public:
  613. using iterator_category = std::input_iterator_tag;
  614. using value_type = DICompileUnit *;
  615. using difference_type = std::ptrdiff_t;
  616. using pointer = value_type *;
  617. using reference = value_type &;
  618. explicit debug_compile_units_iterator(NamedMDNode *CUs, unsigned Idx)
  619. : CUs(CUs), Idx(Idx) {
  620. SkipNoDebugCUs();
  621. }
  622. debug_compile_units_iterator &operator++() {
  623. ++Idx;
  624. SkipNoDebugCUs();
  625. return *this;
  626. }
  627. debug_compile_units_iterator operator++(int) {
  628. debug_compile_units_iterator T(*this);
  629. ++Idx;
  630. return T;
  631. }
  632. bool operator==(const debug_compile_units_iterator &I) const {
  633. return Idx == I.Idx;
  634. }
  635. bool operator!=(const debug_compile_units_iterator &I) const {
  636. return Idx != I.Idx;
  637. }
  638. DICompileUnit *operator*() const;
  639. DICompileUnit *operator->() const;
  640. };
  641. debug_compile_units_iterator debug_compile_units_begin() const {
  642. auto *CUs = getNamedMetadata("llvm.dbg.cu");
  643. return debug_compile_units_iterator(CUs, 0);
  644. }
  645. debug_compile_units_iterator debug_compile_units_end() const {
  646. auto *CUs = getNamedMetadata("llvm.dbg.cu");
  647. return debug_compile_units_iterator(CUs, CUs ? CUs->getNumOperands() : 0);
  648. }
  649. /// Return an iterator for all DICompileUnits listed in this Module's
  650. /// llvm.dbg.cu named metadata node and aren't explicitly marked as
  651. /// NoDebug.
  652. iterator_range<debug_compile_units_iterator> debug_compile_units() const {
  653. auto *CUs = getNamedMetadata("llvm.dbg.cu");
  654. return make_range(
  655. debug_compile_units_iterator(CUs, 0),
  656. debug_compile_units_iterator(CUs, CUs ? CUs->getNumOperands() : 0));
  657. }
  658. /// @}
  659. /// Destroy ConstantArrays in LLVMContext if they are not used.
  660. /// ConstantArrays constructed during linking can cause quadratic memory
  661. /// explosion. Releasing all unused constants can cause a 20% LTO compile-time
  662. /// slowdown for a large application.
  663. ///
  664. /// NOTE: Constants are currently owned by LLVMContext. This can then only
  665. /// be called where all uses of the LLVMContext are understood.
  666. void dropTriviallyDeadConstantArrays();
  667. /// @name Utility functions for printing and dumping Module objects
  668. /// @{
  669. /// Print the module to an output stream with an optional
  670. /// AssemblyAnnotationWriter. If \c ShouldPreserveUseListOrder, then include
  671. /// uselistorder directives so that use-lists can be recreated when reading
  672. /// the assembly.
  673. void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW,
  674. bool ShouldPreserveUseListOrder = false,
  675. bool IsForDebug = false) const;
  676. /// Dump the module to stderr (for debugging).
  677. void dump() const;
  678. /// This function causes all the subinstructions to "let go" of all references
  679. /// that they are maintaining. This allows one to 'delete' a whole class at
  680. /// a time, even though there may be circular references... first all
  681. /// references are dropped, and all use counts go to zero. Then everything
  682. /// is delete'd for real. Note that no operations are valid on an object
  683. /// that has "dropped all references", except operator delete.
  684. void dropAllReferences();
  685. /// @}
  686. /// @name Utility functions for querying Debug information.
  687. /// @{
  688. /// Returns the Number of Register ParametersDwarf Version by checking
  689. /// module flags.
  690. unsigned getNumberRegisterParameters() const;
  691. /// Returns the Dwarf Version by checking module flags.
  692. unsigned getDwarfVersion() const;
  693. /// Returns the DWARF format by checking module flags.
  694. bool isDwarf64() const;
  695. /// Returns the CodeView Version by checking module flags.
  696. /// Returns zero if not present in module.
  697. unsigned getCodeViewFlag() const;
  698. /// @}
  699. /// @name Utility functions for querying and setting PIC level
  700. /// @{
  701. /// Returns the PIC level (small or large model)
  702. PICLevel::Level getPICLevel() const;
  703. /// Set the PIC level (small or large model)
  704. void setPICLevel(PICLevel::Level PL);
  705. /// @}
  706. /// @}
  707. /// @name Utility functions for querying and setting PIE level
  708. /// @{
  709. /// Returns the PIE level (small or large model)
  710. PIELevel::Level getPIELevel() const;
  711. /// Set the PIE level (small or large model)
  712. void setPIELevel(PIELevel::Level PL);
  713. /// @}
  714. /// @}
  715. /// @name Utility function for querying and setting code model
  716. /// @{
  717. /// Returns the code model (tiny, small, kernel, medium or large model)
  718. std::optional<CodeModel::Model> getCodeModel() const;
  719. /// Set the code model (tiny, small, kernel, medium or large)
  720. void setCodeModel(CodeModel::Model CL);
  721. /// @}
  722. /// @name Utility functions for querying and setting PGO summary
  723. /// @{
  724. /// Attach profile summary metadata to this module.
  725. void setProfileSummary(Metadata *M, ProfileSummary::Kind Kind);
  726. /// Returns profile summary metadata. When IsCS is true, use the context
  727. /// sensitive profile summary.
  728. Metadata *getProfileSummary(bool IsCS) const;
  729. /// @}
  730. /// Returns whether semantic interposition is to be respected.
  731. bool getSemanticInterposition() const;
  732. /// Set whether semantic interposition is to be respected.
  733. void setSemanticInterposition(bool);
  734. /// Returns true if PLT should be avoided for RTLib calls.
  735. bool getRtLibUseGOT() const;
  736. /// Set that PLT should be avoid for RTLib calls.
  737. void setRtLibUseGOT();
  738. /// Get/set whether synthesized functions should get the uwtable attribute.
  739. UWTableKind getUwtable() const;
  740. void setUwtable(UWTableKind Kind);
  741. /// Get/set whether synthesized functions should get the "frame-pointer"
  742. /// attribute.
  743. FramePointerKind getFramePointer() const;
  744. void setFramePointer(FramePointerKind Kind);
  745. /// Get/set what kind of stack protector guard to use.
  746. StringRef getStackProtectorGuard() const;
  747. void setStackProtectorGuard(StringRef Kind);
  748. /// Get/set which register to use as the stack protector guard register. The
  749. /// empty string is equivalent to "global". Other values may be "tls" or
  750. /// "sysreg".
  751. StringRef getStackProtectorGuardReg() const;
  752. void setStackProtectorGuardReg(StringRef Reg);
  753. /// Get/set a symbol to use as the stack protector guard.
  754. StringRef getStackProtectorGuardSymbol() const;
  755. void setStackProtectorGuardSymbol(StringRef Symbol);
  756. /// Get/set what offset from the stack protector to use.
  757. int getStackProtectorGuardOffset() const;
  758. void setStackProtectorGuardOffset(int Offset);
  759. /// Get/set the stack alignment overridden from the default.
  760. unsigned getOverrideStackAlignment() const;
  761. void setOverrideStackAlignment(unsigned Align);
  762. /// @name Utility functions for querying and setting the build SDK version
  763. /// @{
  764. /// Attach a build SDK version metadata to this module.
  765. void setSDKVersion(const VersionTuple &V);
  766. /// Get the build SDK version metadata.
  767. ///
  768. /// An empty version is returned if no such metadata is attached.
  769. VersionTuple getSDKVersion() const;
  770. /// @}
  771. /// Take ownership of the given memory buffer.
  772. void setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB);
  773. /// Set the partial sample profile ratio in the profile summary module flag,
  774. /// if applicable.
  775. void setPartialSampleProfileRatio(const ModuleSummaryIndex &Index);
  776. /// Get the target variant triple which is a string describing a variant of
  777. /// the target host platform. For example, Mac Catalyst can be a variant
  778. /// target triple for a macOS target.
  779. /// @returns a string containing the target variant triple.
  780. StringRef getDarwinTargetVariantTriple() const;
  781. /// Set the target variant triple which is a string describing a variant of
  782. /// the target host platform.
  783. void setDarwinTargetVariantTriple(StringRef T);
  784. /// Get the target variant version build SDK version metadata.
  785. ///
  786. /// An empty version is returned if no such metadata is attached.
  787. VersionTuple getDarwinTargetVariantSDKVersion() const;
  788. /// Set the target variant version build SDK version metadata.
  789. void setDarwinTargetVariantSDKVersion(VersionTuple Version);
  790. };
  791. /// Given "llvm.used" or "llvm.compiler.used" as a global name, collect the
  792. /// initializer elements of that global in a SmallVector and return the global
  793. /// itself.
  794. GlobalVariable *collectUsedGlobalVariables(const Module &M,
  795. SmallVectorImpl<GlobalValue *> &Vec,
  796. bool CompilerUsed);
  797. /// An raw_ostream inserter for modules.
  798. inline raw_ostream &operator<<(raw_ostream &O, const Module &M) {
  799. M.print(O, nullptr);
  800. return O;
  801. }
  802. // Create wrappers for C Binding types (see CBindingWrapping.h).
  803. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Module, LLVMModuleRef)
  804. /* LLVMModuleProviderRef exists for historical reasons, but now just holds a
  805. * Module.
  806. */
  807. inline Module *unwrap(LLVMModuleProviderRef MP) {
  808. return reinterpret_cast<Module*>(MP);
  809. }
  810. } // end namespace llvm
  811. #endif // LLVM_IR_MODULE_H
  812. #ifdef __GNUC__
  813. #pragma GCC diagnostic pop
  814. #endif