Module.h 35 KB

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