xref: /freebsd/contrib/llvm-project/llvm/include/llvm/IR/Module.h (revision 700637cbb5e582861067a11aaca4d053546871d2)
1 //===- llvm/Module.h - C++ class to represent a VM module -------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// @file
10 /// Module.h This file contains the declarations for the Module class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_IR_MODULE_H
15 #define LLVM_IR_MODULE_H
16 
17 #include "llvm-c/Types.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/iterator_range.h"
22 #include "llvm/IR/Attributes.h"
23 #include "llvm/IR/Comdat.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/GlobalAlias.h"
27 #include "llvm/IR/GlobalIFunc.h"
28 #include "llvm/IR/GlobalVariable.h"
29 #include "llvm/IR/Metadata.h"
30 #include "llvm/IR/ProfileSummary.h"
31 #include "llvm/IR/SymbolTableListTraits.h"
32 #include "llvm/Support/CBindingWrapping.h"
33 #include "llvm/Support/CodeGen.h"
34 #include "llvm/Support/Compiler.h"
35 #include "llvm/TargetParser/Triple.h"
36 #include <cstddef>
37 #include <cstdint>
38 #include <iterator>
39 #include <memory>
40 #include <optional>
41 #include <string>
42 #include <vector>
43 
44 namespace llvm {
45 
46 class Error;
47 class FunctionType;
48 class GVMaterializer;
49 class LLVMContext;
50 class MemoryBuffer;
51 class ModuleSummaryIndex;
52 class RandomNumberGenerator;
53 class StructType;
54 class VersionTuple;
55 
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 GlobalList 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 GlobalList.
66 /// The main container class for the LLVM Intermediate Representation.
67 class LLVM_ABI 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 
86   /// The Global Variable iterator.
87   using global_iterator = GlobalListType::iterator;
88   /// The Global Variable constant iterator.
89   using const_global_iterator = GlobalListType::const_iterator;
90 
91   /// The Function iterators.
92   using iterator = FunctionListType::iterator;
93   /// The Function constant iterator
94   using const_iterator = FunctionListType::const_iterator;
95 
96   /// The Function reverse iterator.
97   using reverse_iterator = FunctionListType::reverse_iterator;
98   /// The Function constant reverse iterator.
99   using const_reverse_iterator = FunctionListType::const_reverse_iterator;
100 
101   /// The Global Alias iterators.
102   using alias_iterator = AliasListType::iterator;
103   /// The Global Alias constant iterator
104   using const_alias_iterator = AliasListType::const_iterator;
105 
106   /// The Global IFunc iterators.
107   using ifunc_iterator = IFuncListType::iterator;
108   /// The Global IFunc constant iterator
109   using const_ifunc_iterator = IFuncListType::const_iterator;
110 
111   /// The named metadata iterators.
112   using named_metadata_iterator = NamedMDListType::iterator;
113   /// The named metadata constant iterators.
114   using const_named_metadata_iterator = NamedMDListType::const_iterator;
115 
116   /// This enumeration defines the supported behaviors of module flags.
117   enum ModFlagBehavior {
118     /// Emits an error if two values disagree, otherwise the resulting value is
119     /// that of the operands.
120     Error = 1,
121 
122     /// Emits a warning if two values disagree. The result value will be the
123     /// operand for the flag from the first module being linked.
124     Warning = 2,
125 
126     /// Adds a requirement that another module flag be present and have a
127     /// specified value after linking is performed. The value must be a metadata
128     /// pair, where the first element of the pair is the ID of the module flag
129     /// to be restricted, and the second element of the pair is the value the
130     /// module flag should be restricted to. This behavior can be used to
131     /// restrict the allowable results (via triggering of an error) of linking
132     /// IDs with the **Override** behavior.
133     Require = 3,
134 
135     /// Uses the specified value, regardless of the behavior or value of the
136     /// other module. If both modules specify **Override**, but the values
137     /// differ, an error will be emitted.
138     Override = 4,
139 
140     /// Appends the two values, which are required to be metadata nodes.
141     Append = 5,
142 
143     /// Appends the two values, which are required to be metadata
144     /// nodes. However, duplicate entries in the second list are dropped
145     /// during the append operation.
146     AppendUnique = 6,
147 
148     /// Takes the max of the two values, which are required to be integers.
149     Max = 7,
150 
151     /// Takes the min of the two values, which are required to be integers.
152     Min = 8,
153 
154     // Markers:
155     ModFlagBehaviorFirstVal = Error,
156     ModFlagBehaviorLastVal = Min
157   };
158 
159   /// Checks if Metadata represents a valid ModFlagBehavior, and stores the
160   /// converted result in MFB.
161   static bool isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB);
162 
163   struct ModuleFlagEntry {
164     ModFlagBehavior Behavior;
165     MDString *Key;
166     Metadata *Val;
167 
ModuleFlagEntryModuleFlagEntry168     ModuleFlagEntry(ModFlagBehavior B, MDString *K, Metadata *V)
169         : Behavior(B), Key(K), Val(V) {}
170   };
171 
172 /// @}
173 /// @name Member Variables
174 /// @{
175 private:
176   LLVMContext &Context;           ///< The LLVMContext from which types and
177                                   ///< constants are allocated.
178   GlobalListType GlobalList;      ///< The Global Variables in the module
179   FunctionListType FunctionList;  ///< The Functions in the module
180   AliasListType AliasList;        ///< The Aliases in the module
181   IFuncListType IFuncList;        ///< The IFuncs in the module
182   NamedMDListType NamedMDList;    ///< The named metadata in the module
183   std::string GlobalScopeAsm;     ///< Inline Asm at global scope.
184   std::unique_ptr<ValueSymbolTable> ValSymTab; ///< Symbol table for values
185   ComdatSymTabType ComdatSymTab;  ///< Symbol table for COMDATs
186   std::unique_ptr<MemoryBuffer>
187   OwnedMemoryBuffer;              ///< Memory buffer directly owned by this
188                                   ///< module, for legacy clients only.
189   std::unique_ptr<GVMaterializer>
190   Materializer;                   ///< Used to materialize GlobalValues
191   std::string ModuleID;           ///< Human readable identifier for the module
192   std::string SourceFileName;     ///< Original source file name for module,
193                                   ///< recorded in bitcode.
194   /// Platform target triple Module compiled on
195   /// Format: (arch)(sub)-(vendor)-(sys)-(abi)
196   // FIXME: Default construction is not the same as empty triple :(
197   Triple TargetTriple = Triple("");
198   NamedMDSymTabType NamedMDSymTab;  ///< NamedMDNode names.
199   DataLayout DL;                  ///< DataLayout associated with the module
200   StringMap<unsigned>
201       CurrentIntrinsicIds; ///< Keep track of the current unique id count for
202                            ///< the specified intrinsic basename.
203   DenseMap<std::pair<Intrinsic::ID, const FunctionType *>, unsigned>
204       UniquedIntrinsicNames; ///< Keep track of uniqued names of intrinsics
205                              ///< based on unnamed types. The combination of
206                              ///< ID and FunctionType maps to the extension that
207                              ///< is used to make the intrinsic name unique.
208 
209   /// llvm.module.flags metadata
210   NamedMDNode *ModuleFlags = nullptr;
211 
212   friend class Constant;
213 
214 /// @}
215 /// @name Constructors
216 /// @{
217 public:
218   /// Used when printing this module in the new debug info format; removes all
219   /// declarations of debug intrinsics that are replaced by non-intrinsic
220   /// records in the new format.
221   void removeDebugIntrinsicDeclarations();
222 
223   /// \see BasicBlock::convertToNewDbgValues.
convertToNewDbgValues()224   void convertToNewDbgValues() {
225     for (auto &F : *this) {
226       F.convertToNewDbgValues();
227     }
228   }
229 
230   /// \see BasicBlock::convertFromNewDbgValues.
convertFromNewDbgValues()231   void convertFromNewDbgValues() {
232     for (auto &F : *this) {
233       F.convertFromNewDbgValues();
234     }
235   }
236 
237   /// The Module constructor. Note that there is no default constructor. You
238   /// must provide a name for the module upon construction.
239   explicit Module(StringRef ModuleID, LLVMContext& C);
240   /// The module destructor. This will dropAllReferences.
241   ~Module();
242 
243   /// Move assignment.
244   Module &operator=(Module &&Other);
245 
246   /// @}
247   /// @name Module Level Accessors
248   /// @{
249 
250   /// Get the module identifier which is, essentially, the name of the module.
251   /// @returns the module identifier as a string
getModuleIdentifier()252   const std::string &getModuleIdentifier() const { return ModuleID; }
253 
254   /// Returns the number of non-debug IR instructions in the module.
255   /// This is equivalent to the sum of the IR instruction counts of each
256   /// function contained in the module.
257   unsigned getInstructionCount() const;
258 
259   /// Get the module's original source file name. When compiling from
260   /// bitcode, this is taken from a bitcode record where it was recorded.
261   /// For other compiles it is the same as the ModuleID, which would
262   /// contain the source file name.
getSourceFileName()263   const std::string &getSourceFileName() const { return SourceFileName; }
264 
265   /// Get a short "name" for the module.
266   ///
267   /// This is useful for debugging or logging. It is essentially a convenience
268   /// wrapper around getModuleIdentifier().
getName()269   StringRef getName() const { return ModuleID; }
270 
271   /// Get the data layout string for the module's target platform. This is
272   /// equivalent to getDataLayout()->getStringRepresentation().
getDataLayoutStr()273   const std::string &getDataLayoutStr() const {
274     return DL.getStringRepresentation();
275   }
276 
277   /// Get the data layout for the module's target platform.
getDataLayout()278   const DataLayout &getDataLayout() const { return DL; }
279 
280   /// Get the target triple which is a string describing the target host.
getTargetTriple()281   const Triple &getTargetTriple() const { return TargetTriple; }
282 
283   /// Get the global data context.
284   /// @returns LLVMContext - a container for LLVM's global information
getContext()285   LLVMContext &getContext() const { return Context; }
286 
287   /// Get any module-scope inline assembly blocks.
288   /// @returns a string containing the module-scope inline assembly blocks.
getModuleInlineAsm()289   const std::string &getModuleInlineAsm() const { return GlobalScopeAsm; }
290 
291   /// Get a RandomNumberGenerator salted for use with this module. The
292   /// RNG can be seeded via -rng-seed=<uint64> and is salted with the
293   /// ModuleID and the provided pass salt. The returned RNG should not
294   /// be shared across threads or passes.
295   ///
296   /// A unique RNG per pass ensures a reproducible random stream even
297   /// when other randomness consuming passes are added or removed. In
298   /// addition, the random stream will be reproducible across LLVM
299   /// versions when the pass does not change.
300   std::unique_ptr<RandomNumberGenerator> createRNG(const StringRef Name) const;
301 
302   /// Return true if size-info optimization remark is enabled, false
303   /// otherwise.
shouldEmitInstrCountChangedRemark()304   bool shouldEmitInstrCountChangedRemark() {
305     return getContext().getDiagHandlerPtr()->isAnalysisRemarkEnabled(
306         "size-info");
307   }
308 
309   /// @}
310   /// @name Module Level Mutators
311   /// @{
312 
313   /// Set the module identifier.
setModuleIdentifier(StringRef ID)314   void setModuleIdentifier(StringRef ID) { ModuleID = std::string(ID); }
315 
316   /// Set the module's original source file name.
setSourceFileName(StringRef Name)317   void setSourceFileName(StringRef Name) { SourceFileName = std::string(Name); }
318 
319   /// Set the data layout
320   void setDataLayout(StringRef Desc);
321   void setDataLayout(const DataLayout &Other);
322 
323   /// Set the target triple.
setTargetTriple(Triple T)324   void setTargetTriple(Triple T) { TargetTriple = std::move(T); }
325 
326   /// Set the module-scope inline assembly blocks.
327   /// A trailing newline is added if the input doesn't have one.
setModuleInlineAsm(StringRef Asm)328   void setModuleInlineAsm(StringRef Asm) {
329     GlobalScopeAsm = std::string(Asm);
330     if (!GlobalScopeAsm.empty() && GlobalScopeAsm.back() != '\n')
331       GlobalScopeAsm += '\n';
332   }
333 
334   /// Append to the module-scope inline assembly blocks.
335   /// A trailing newline is added if the input doesn't have one.
appendModuleInlineAsm(StringRef Asm)336   void appendModuleInlineAsm(StringRef Asm) {
337     GlobalScopeAsm += Asm;
338     if (!GlobalScopeAsm.empty() && GlobalScopeAsm.back() != '\n')
339       GlobalScopeAsm += '\n';
340   }
341 
342 /// @}
343 /// @name Generic Value Accessors
344 /// @{
345 
346   /// Return the global value in the module with the specified name, of
347   /// arbitrary type. This method returns null if a global with the specified
348   /// name is not found.
349   GlobalValue *getNamedValue(StringRef Name) const;
350 
351   /// Return the number of global values in the module.
352   unsigned getNumNamedValues() const;
353 
354   /// Return a unique non-zero ID for the specified metadata kind. This ID is
355   /// uniqued across modules in the current LLVMContext.
356   unsigned getMDKindID(StringRef Name) const;
357 
358   /// Populate client supplied SmallVector with the name for custom metadata IDs
359   /// registered in this LLVMContext.
360   void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
361 
362   /// Populate client supplied SmallVector with the bundle tags registered in
363   /// this LLVMContext.  The bundle tags are ordered by increasing bundle IDs.
364   /// \see LLVMContext::getOperandBundleTagID
365   void getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const;
366 
367   std::vector<StructType *> getIdentifiedStructTypes() const;
368 
369   /// Return a unique name for an intrinsic whose mangling is based on an
370   /// unnamed type. The Proto represents the function prototype.
371   std::string getUniqueIntrinsicName(StringRef BaseName, Intrinsic::ID Id,
372                                      const FunctionType *Proto);
373 
374 /// @}
375 /// @name Function Accessors
376 /// @{
377 
378   /// Look up the specified function in the module symbol table. If it does not
379   /// exist, add a prototype for the function and return it. Otherwise, return
380   /// the existing function.
381   ///
382   /// In all cases, the returned value is a FunctionCallee wrapper around the
383   /// 'FunctionType *T' passed in, as well as the 'Value*' of the Function. The
384   /// function type of the function may differ from the function type stored in
385   /// FunctionCallee if it was previously created with a different type.
386   ///
387   /// Note: For library calls getOrInsertLibFunc() should be used instead.
388   FunctionCallee getOrInsertFunction(StringRef Name, FunctionType *T,
389                                      AttributeList AttributeList);
390 
391   FunctionCallee getOrInsertFunction(StringRef Name, FunctionType *T);
392 
393   /// Same as above, but takes a list of function arguments, which makes it
394   /// easier for clients to use.
395   template <typename... ArgsTy>
getOrInsertFunction(StringRef Name,AttributeList AttributeList,Type * RetTy,ArgsTy...Args)396   FunctionCallee getOrInsertFunction(StringRef Name,
397                                      AttributeList AttributeList, Type *RetTy,
398                                      ArgsTy... Args) {
399     SmallVector<Type*, sizeof...(ArgsTy)> ArgTys{Args...};
400     return getOrInsertFunction(Name,
401                                FunctionType::get(RetTy, ArgTys, false),
402                                AttributeList);
403   }
404 
405   /// Same as above, but without the attributes.
406   template <typename... ArgsTy>
getOrInsertFunction(StringRef Name,Type * RetTy,ArgsTy...Args)407   FunctionCallee getOrInsertFunction(StringRef Name, Type *RetTy,
408                                      ArgsTy... Args) {
409     return getOrInsertFunction(Name, AttributeList{}, RetTy, Args...);
410   }
411 
412   // Avoid an incorrect ordering that'd otherwise compile incorrectly.
413   template <typename... ArgsTy>
414   FunctionCallee
415   getOrInsertFunction(StringRef Name, AttributeList AttributeList,
416                       FunctionType *Invalid, ArgsTy... Args) = delete;
417 
418   /// Look up the specified function in the module symbol table. If it does not
419   /// exist, return null.
420   Function *getFunction(StringRef Name) const;
421 
422 /// @}
423 /// @name Global Variable Accessors
424 /// @{
425 
426   /// Look up the specified global variable in the module symbol table. If it
427   /// does not exist, return null. If AllowInternal is set to true, this
428   /// function will return types that have InternalLinkage. By default, these
429   /// types are not returned.
getGlobalVariable(StringRef Name)430   GlobalVariable *getGlobalVariable(StringRef Name) const {
431     return getGlobalVariable(Name, false);
432   }
433 
434   GlobalVariable *getGlobalVariable(StringRef Name, bool AllowInternal) const;
435 
436   GlobalVariable *getGlobalVariable(StringRef Name,
437                                     bool AllowInternal = false) {
438     return static_cast<const Module *>(this)->getGlobalVariable(Name,
439                                                                 AllowInternal);
440   }
441 
442   /// Return the global variable in the module with the specified name, of
443   /// arbitrary type. This method returns null if a global with the specified
444   /// name is not found.
getNamedGlobal(StringRef Name)445   const GlobalVariable *getNamedGlobal(StringRef Name) const {
446     return getGlobalVariable(Name, true);
447   }
getNamedGlobal(StringRef Name)448   GlobalVariable *getNamedGlobal(StringRef Name) {
449     return const_cast<GlobalVariable *>(
450                        static_cast<const Module *>(this)->getNamedGlobal(Name));
451   }
452 
453   /// Look up the specified global in the module symbol table.
454   /// If it does not exist, invoke a callback to create a declaration of the
455   /// global and return it.
456   GlobalVariable *
457   getOrInsertGlobal(StringRef Name, Type *Ty,
458                     function_ref<GlobalVariable *()> CreateGlobalCallback);
459 
460   /// Look up the specified global in the module symbol table. If required, this
461   /// overload constructs the global variable using its constructor's defaults.
462   GlobalVariable *getOrInsertGlobal(StringRef Name, Type *Ty);
463 
464 /// @}
465 /// @name Global Alias Accessors
466 /// @{
467 
468   /// Return the global alias in the module with the specified name, of
469   /// arbitrary type. This method returns null if a global with the specified
470   /// name is not found.
471   GlobalAlias *getNamedAlias(StringRef Name) const;
472 
473 /// @}
474 /// @name Global IFunc Accessors
475 /// @{
476 
477   /// Return the global ifunc in the module with the specified name, of
478   /// arbitrary type. This method returns null if a global with the specified
479   /// name is not found.
480   GlobalIFunc *getNamedIFunc(StringRef Name) const;
481 
482 /// @}
483 /// @name Named Metadata Accessors
484 /// @{
485 
486   /// Return the first NamedMDNode in the module with the specified name. This
487   /// method returns null if a NamedMDNode with the specified name is not found.
488   NamedMDNode *getNamedMetadata(StringRef Name) const;
489 
490   /// Return the named MDNode in the module with the specified name. This method
491   /// returns a new NamedMDNode if a NamedMDNode with the specified name is not
492   /// found.
493   NamedMDNode *getOrInsertNamedMetadata(StringRef Name);
494 
495   /// Remove the given NamedMDNode from this module and delete it.
496   void eraseNamedMetadata(NamedMDNode *NMD);
497 
498 /// @}
499 /// @name Comdat Accessors
500 /// @{
501 
502   /// Return the Comdat in the module with the specified name. It is created
503   /// if it didn't already exist.
504   Comdat *getOrInsertComdat(StringRef Name);
505 
506 /// @}
507 /// @name Module Flags Accessors
508 /// @{
509 
510   /// Returns the module flags in the provided vector.
511   void getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const;
512 
513   /// Return the corresponding value if Key appears in module flags, otherwise
514   /// return null.
515   Metadata *getModuleFlag(StringRef Key) const;
516 
517   /// Returns the NamedMDNode in the module that represents module-level flags.
518   /// This method returns null if there are no module-level flags.
getModuleFlagsMetadata()519   NamedMDNode *getModuleFlagsMetadata() const { return ModuleFlags; }
520 
521   /// Returns the NamedMDNode in the module that represents module-level flags.
522   /// If module-level flags aren't found, it creates the named metadata that
523   /// contains them.
524   NamedMDNode *getOrInsertModuleFlagsMetadata();
525 
526   /// Add a module-level flag to the module-level flags metadata. It will create
527   /// the module-level flags named metadata if it doesn't already exist.
528   void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Metadata *Val);
529   void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Constant *Val);
530   void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, uint32_t Val);
531   void addModuleFlag(MDNode *Node);
532   /// Like addModuleFlag but replaces the old module flag if it already exists.
533   void setModuleFlag(ModFlagBehavior Behavior, StringRef Key, Metadata *Val);
534   void setModuleFlag(ModFlagBehavior Behavior, StringRef Key, Constant *Val);
535   void setModuleFlag(ModFlagBehavior Behavior, StringRef Key, uint32_t Val);
536 
537   /// @}
538   /// @name Materialization
539   /// @{
540 
541   /// Sets the GVMaterializer to GVM. This module must not yet have a
542   /// Materializer. To reset the materializer for a module that already has one,
543   /// call materializeAll first. Destroying this module will destroy
544   /// its materializer without materializing any more GlobalValues. Without
545   /// destroying the Module, there is no way to detach or destroy a materializer
546   /// without materializing all the GVs it controls, to avoid leaving orphan
547   /// unmaterialized GVs.
548   void setMaterializer(GVMaterializer *GVM);
549   /// Retrieves the GVMaterializer, if any, for this Module.
getMaterializer()550   GVMaterializer *getMaterializer() const { return Materializer.get(); }
isMaterialized()551   bool isMaterialized() const { return !getMaterializer(); }
552 
553   /// Make sure the GlobalValue is fully read.
554   llvm::Error materialize(GlobalValue *GV);
555 
556   /// Make sure all GlobalValues in this Module are fully read and clear the
557   /// Materializer.
558   llvm::Error materializeAll();
559 
560   llvm::Error materializeMetadata();
561 
562   /// Detach global variable \p GV from the list but don't delete it.
removeGlobalVariable(GlobalVariable * GV)563   void removeGlobalVariable(GlobalVariable *GV) { GlobalList.remove(GV); }
564   /// Remove global variable \p GV from the list and delete it.
eraseGlobalVariable(GlobalVariable * GV)565   void eraseGlobalVariable(GlobalVariable *GV) { GlobalList.erase(GV); }
566   /// Insert global variable \p GV at the end of the global variable list and
567   /// take ownership.
insertGlobalVariable(GlobalVariable * GV)568   void insertGlobalVariable(GlobalVariable *GV) {
569     insertGlobalVariable(GlobalList.end(), GV);
570   }
571   /// Insert global variable \p GV into the global variable list before \p
572   /// Where and take ownership.
insertGlobalVariable(GlobalListType::iterator Where,GlobalVariable * GV)573   void insertGlobalVariable(GlobalListType::iterator Where, GlobalVariable *GV) {
574     GlobalList.insert(Where, GV);
575   }
576   // Use global_size() to get the total number of global variables.
577   // Use globals() to get the range of all global variables.
578 
579 private:
580 /// @}
581 /// @name Direct access to the globals list, functions list, and symbol table
582 /// @{
583 
584   /// Get the Module's list of global variables (constant).
getGlobalList()585   const GlobalListType   &getGlobalList() const       { return GlobalList; }
586   /// Get the Module's list of global variables.
getGlobalList()587   GlobalListType         &getGlobalList()             { return GlobalList; }
588 
getSublistAccess(GlobalVariable *)589   static GlobalListType Module::*getSublistAccess(GlobalVariable*) {
590     return &Module::GlobalList;
591   }
592   friend class llvm::SymbolTableListTraits<llvm::GlobalVariable>;
593 
594 public:
595   /// Get the Module's list of functions (constant).
getFunctionList()596   const FunctionListType &getFunctionList() const     { return FunctionList; }
597   /// Get the Module's list of functions.
getFunctionList()598   FunctionListType       &getFunctionList()           { return FunctionList; }
getSublistAccess(Function *)599   static FunctionListType Module::*getSublistAccess(Function*) {
600     return &Module::FunctionList;
601   }
602 
603   /// Detach \p Alias from the list but don't delete it.
removeAlias(GlobalAlias * Alias)604   void removeAlias(GlobalAlias *Alias) { AliasList.remove(Alias); }
605   /// Remove \p Alias from the list and delete it.
eraseAlias(GlobalAlias * Alias)606   void eraseAlias(GlobalAlias *Alias) { AliasList.erase(Alias); }
607   /// Insert \p Alias at the end of the alias list and take ownership.
insertAlias(GlobalAlias * Alias)608   void insertAlias(GlobalAlias *Alias) { AliasList.insert(AliasList.end(), Alias); }
609   // Use alias_size() to get the size of AliasList.
610   // Use aliases() to get a range of all Alias objects in AliasList.
611 
612   /// Detach \p IFunc from the list but don't delete it.
removeIFunc(GlobalIFunc * IFunc)613   void removeIFunc(GlobalIFunc *IFunc) { IFuncList.remove(IFunc); }
614   /// Remove \p IFunc from the list and delete it.
eraseIFunc(GlobalIFunc * IFunc)615   void eraseIFunc(GlobalIFunc *IFunc) { IFuncList.erase(IFunc); }
616   /// Insert \p IFunc at the end of the alias list and take ownership.
insertIFunc(GlobalIFunc * IFunc)617   void insertIFunc(GlobalIFunc *IFunc) { IFuncList.push_back(IFunc); }
618   // Use ifunc_size() to get the number of functions in IFuncList.
619   // Use ifuncs() to get the range of all IFuncs.
620 
621   /// Detach \p MDNode from the list but don't delete it.
removeNamedMDNode(NamedMDNode * MDNode)622   void removeNamedMDNode(NamedMDNode *MDNode) { NamedMDList.remove(MDNode); }
623   /// Remove \p MDNode from the list and delete it.
eraseNamedMDNode(NamedMDNode * MDNode)624   void eraseNamedMDNode(NamedMDNode *MDNode) { NamedMDList.erase(MDNode); }
625   /// Insert \p MDNode at the end of the alias list and take ownership.
insertNamedMDNode(NamedMDNode * MDNode)626   void insertNamedMDNode(NamedMDNode *MDNode) {
627     NamedMDList.push_back(MDNode);
628   }
629   // Use named_metadata_size() to get the size of the named meatadata list.
630   // Use named_metadata() to get the range of all named metadata.
631 
632 private: // Please use functions like insertAlias(), removeAlias() etc.
633   /// Get the Module's list of aliases (constant).
getAliasList()634   const AliasListType    &getAliasList() const        { return AliasList; }
635   /// Get the Module's list of aliases.
getAliasList()636   AliasListType          &getAliasList()              { return AliasList; }
637 
getSublistAccess(GlobalAlias *)638   static AliasListType Module::*getSublistAccess(GlobalAlias*) {
639     return &Module::AliasList;
640   }
641   friend class llvm::SymbolTableListTraits<llvm::GlobalAlias>;
642 
643   /// Get the Module's list of ifuncs (constant).
getIFuncList()644   const IFuncListType    &getIFuncList() const        { return IFuncList; }
645   /// Get the Module's list of ifuncs.
getIFuncList()646   IFuncListType          &getIFuncList()              { return IFuncList; }
647 
getSublistAccess(GlobalIFunc *)648   static IFuncListType Module::*getSublistAccess(GlobalIFunc*) {
649     return &Module::IFuncList;
650   }
651   friend class llvm::SymbolTableListTraits<llvm::GlobalIFunc>;
652 
653   /// Get the Module's list of named metadata (constant).
getNamedMDList()654   const NamedMDListType  &getNamedMDList() const      { return NamedMDList; }
655   /// Get the Module's list of named metadata.
getNamedMDList()656   NamedMDListType        &getNamedMDList()            { return NamedMDList; }
657 
getSublistAccess(NamedMDNode *)658   static NamedMDListType Module::*getSublistAccess(NamedMDNode*) {
659     return &Module::NamedMDList;
660   }
661 
662 public:
663   /// Get the symbol table of global variable and function identifiers
getValueSymbolTable()664   const ValueSymbolTable &getValueSymbolTable() const { return *ValSymTab; }
665   /// Get the Module's symbol table of global variable and function identifiers.
getValueSymbolTable()666   ValueSymbolTable       &getValueSymbolTable()       { return *ValSymTab; }
667 
668   /// Get the Module's symbol table for COMDATs (constant).
getComdatSymbolTable()669   const ComdatSymTabType &getComdatSymbolTable() const { return ComdatSymTab; }
670   /// Get the Module's symbol table for COMDATs.
getComdatSymbolTable()671   ComdatSymTabType &getComdatSymbolTable() { return ComdatSymTab; }
672 
673 /// @}
674 /// @name Global Variable Iteration
675 /// @{
676 
global_begin()677   global_iterator       global_begin()       { return GlobalList.begin(); }
global_begin()678   const_global_iterator global_begin() const { return GlobalList.begin(); }
global_end()679   global_iterator       global_end  ()       { return GlobalList.end(); }
global_end()680   const_global_iterator global_end  () const { return GlobalList.end(); }
global_size()681   size_t                global_size () const { return GlobalList.size(); }
global_empty()682   bool                  global_empty() const { return GlobalList.empty(); }
683 
globals()684   iterator_range<global_iterator> globals() {
685     return make_range(global_begin(), global_end());
686   }
globals()687   iterator_range<const_global_iterator> globals() const {
688     return make_range(global_begin(), global_end());
689   }
690 
691 /// @}
692 /// @name Function Iteration
693 /// @{
694 
begin()695   iterator                begin()       { return FunctionList.begin(); }
begin()696   const_iterator          begin() const { return FunctionList.begin(); }
end()697   iterator                end  ()       { return FunctionList.end();   }
end()698   const_iterator          end  () const { return FunctionList.end();   }
rbegin()699   reverse_iterator        rbegin()      { return FunctionList.rbegin(); }
rbegin()700   const_reverse_iterator  rbegin() const{ return FunctionList.rbegin(); }
rend()701   reverse_iterator        rend()        { return FunctionList.rend(); }
rend()702   const_reverse_iterator  rend() const  { return FunctionList.rend(); }
size()703   size_t                  size() const  { return FunctionList.size(); }
empty()704   bool                    empty() const { return FunctionList.empty(); }
705 
functions()706   iterator_range<iterator> functions() {
707     return make_range(begin(), end());
708   }
functions()709   iterator_range<const_iterator> functions() const {
710     return make_range(begin(), end());
711   }
712 
713 /// @}
714 /// @name Alias Iteration
715 /// @{
716 
alias_begin()717   alias_iterator       alias_begin()            { return AliasList.begin(); }
alias_begin()718   const_alias_iterator alias_begin() const      { return AliasList.begin(); }
alias_end()719   alias_iterator       alias_end  ()            { return AliasList.end();   }
alias_end()720   const_alias_iterator alias_end  () const      { return AliasList.end();   }
alias_size()721   size_t               alias_size () const      { return AliasList.size();  }
alias_empty()722   bool                 alias_empty() const      { return AliasList.empty(); }
723 
aliases()724   iterator_range<alias_iterator> aliases() {
725     return make_range(alias_begin(), alias_end());
726   }
aliases()727   iterator_range<const_alias_iterator> aliases() const {
728     return make_range(alias_begin(), alias_end());
729   }
730 
731 /// @}
732 /// @name IFunc Iteration
733 /// @{
734 
ifunc_begin()735   ifunc_iterator       ifunc_begin()            { return IFuncList.begin(); }
ifunc_begin()736   const_ifunc_iterator ifunc_begin() const      { return IFuncList.begin(); }
ifunc_end()737   ifunc_iterator       ifunc_end  ()            { return IFuncList.end();   }
ifunc_end()738   const_ifunc_iterator ifunc_end  () const      { return IFuncList.end();   }
ifunc_size()739   size_t               ifunc_size () const      { return IFuncList.size();  }
ifunc_empty()740   bool                 ifunc_empty() const      { return IFuncList.empty(); }
741 
ifuncs()742   iterator_range<ifunc_iterator> ifuncs() {
743     return make_range(ifunc_begin(), ifunc_end());
744   }
ifuncs()745   iterator_range<const_ifunc_iterator> ifuncs() const {
746     return make_range(ifunc_begin(), ifunc_end());
747   }
748 
749   /// @}
750   /// @name Convenience iterators
751   /// @{
752 
753   using global_object_iterator =
754       concat_iterator<GlobalObject, iterator, global_iterator>;
755   using const_global_object_iterator =
756       concat_iterator<const GlobalObject, const_iterator,
757                       const_global_iterator>;
758 
759   iterator_range<global_object_iterator> global_objects();
760   iterator_range<const_global_object_iterator> global_objects() const;
761 
762   using global_value_iterator =
763       concat_iterator<GlobalValue, iterator, global_iterator, alias_iterator,
764                       ifunc_iterator>;
765   using const_global_value_iterator =
766       concat_iterator<const GlobalValue, const_iterator, const_global_iterator,
767                       const_alias_iterator, const_ifunc_iterator>;
768 
769   iterator_range<global_value_iterator> global_values();
770   iterator_range<const_global_value_iterator> global_values() const;
771 
772   /// @}
773   /// @name Named Metadata Iteration
774   /// @{
775 
named_metadata_begin()776   named_metadata_iterator named_metadata_begin() { return NamedMDList.begin(); }
named_metadata_begin()777   const_named_metadata_iterator named_metadata_begin() const {
778     return NamedMDList.begin();
779   }
780 
named_metadata_end()781   named_metadata_iterator named_metadata_end() { return NamedMDList.end(); }
named_metadata_end()782   const_named_metadata_iterator named_metadata_end() const {
783     return NamedMDList.end();
784   }
785 
named_metadata_size()786   size_t named_metadata_size() const { return NamedMDList.size();  }
named_metadata_empty()787   bool named_metadata_empty() const { return NamedMDList.empty(); }
788 
named_metadata()789   iterator_range<named_metadata_iterator> named_metadata() {
790     return make_range(named_metadata_begin(), named_metadata_end());
791   }
named_metadata()792   iterator_range<const_named_metadata_iterator> named_metadata() const {
793     return make_range(named_metadata_begin(), named_metadata_end());
794   }
795 
796   /// An iterator for DICompileUnits that skips those marked NoDebug.
797   class debug_compile_units_iterator {
798     NamedMDNode *CUs;
799     unsigned Idx;
800 
801     LLVM_ABI void SkipNoDebugCUs();
802 
803   public:
804     using iterator_category = std::input_iterator_tag;
805     using value_type = DICompileUnit *;
806     using difference_type = std::ptrdiff_t;
807     using pointer = value_type *;
808     using reference = value_type &;
809 
debug_compile_units_iterator(NamedMDNode * CUs,unsigned Idx)810     explicit debug_compile_units_iterator(NamedMDNode *CUs, unsigned Idx)
811         : CUs(CUs), Idx(Idx) {
812       SkipNoDebugCUs();
813     }
814 
815     debug_compile_units_iterator &operator++() {
816       ++Idx;
817       SkipNoDebugCUs();
818       return *this;
819     }
820 
821     debug_compile_units_iterator operator++(int) {
822       debug_compile_units_iterator T(*this);
823       ++Idx;
824       return T;
825     }
826 
827     bool operator==(const debug_compile_units_iterator &I) const {
828       return Idx == I.Idx;
829     }
830 
831     bool operator!=(const debug_compile_units_iterator &I) const {
832       return Idx != I.Idx;
833     }
834 
835     LLVM_ABI DICompileUnit *operator*() const;
836     LLVM_ABI DICompileUnit *operator->() const;
837   };
838 
debug_compile_units_begin()839   debug_compile_units_iterator debug_compile_units_begin() const {
840     auto *CUs = getNamedMetadata("llvm.dbg.cu");
841     return debug_compile_units_iterator(CUs, 0);
842   }
843 
debug_compile_units_end()844   debug_compile_units_iterator debug_compile_units_end() const {
845     auto *CUs = getNamedMetadata("llvm.dbg.cu");
846     return debug_compile_units_iterator(CUs, CUs ? CUs->getNumOperands() : 0);
847   }
848 
849   /// Return an iterator for all DICompileUnits listed in this Module's
850   /// llvm.dbg.cu named metadata node and aren't explicitly marked as
851   /// NoDebug.
debug_compile_units()852   iterator_range<debug_compile_units_iterator> debug_compile_units() const {
853     auto *CUs = getNamedMetadata("llvm.dbg.cu");
854     return make_range(
855         debug_compile_units_iterator(CUs, 0),
856         debug_compile_units_iterator(CUs, CUs ? CUs->getNumOperands() : 0));
857   }
858 /// @}
859 
860 /// @name Utility functions for printing and dumping Module objects
861 /// @{
862 
863   /// Print the module to an output stream with an optional
864   /// AssemblyAnnotationWriter.  If \c ShouldPreserveUseListOrder, then include
865   /// uselistorder directives so that use-lists can be recreated when reading
866   /// the assembly.
867   void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW,
868              bool ShouldPreserveUseListOrder = false,
869              bool IsForDebug = false) const;
870 
871   /// Dump the module to stderr (for debugging).
872   void dump() const;
873 
874   /// This function causes all the subinstructions to "let go" of all references
875   /// that they are maintaining.  This allows one to 'delete' a whole class at
876   /// a time, even though there may be circular references... first all
877   /// references are dropped, and all use counts go to zero.  Then everything
878   /// is delete'd for real.  Note that no operations are valid on an object
879   /// that has "dropped all references", except operator delete.
880   void dropAllReferences();
881 
882 /// @}
883 /// @name Utility functions for querying Debug information.
884 /// @{
885 
886   /// Returns the Number of Register ParametersDwarf Version by checking
887   /// module flags.
888   unsigned getNumberRegisterParameters() const;
889 
890   /// Returns the Dwarf Version by checking module flags.
891   unsigned getDwarfVersion() const;
892 
893   /// Returns the DWARF format by checking module flags.
894   bool isDwarf64() const;
895 
896   /// Returns the CodeView Version by checking module flags.
897   /// Returns zero if not present in module.
898   unsigned getCodeViewFlag() const;
899 
900 /// @}
901 /// @name Utility functions for querying and setting PIC level
902 /// @{
903 
904   /// Returns the PIC level (small or large model)
905   PICLevel::Level getPICLevel() const;
906 
907   /// Set the PIC level (small or large model)
908   void setPICLevel(PICLevel::Level PL);
909 /// @}
910 
911 /// @}
912 /// @name Utility functions for querying and setting PIE level
913 /// @{
914 
915   /// Returns the PIE level (small or large model)
916   PIELevel::Level getPIELevel() const;
917 
918   /// Set the PIE level (small or large model)
919   void setPIELevel(PIELevel::Level PL);
920 /// @}
921 
922   /// @}
923   /// @name Utility function for querying and setting code model
924   /// @{
925 
926   /// Returns the code model (tiny, small, kernel, medium or large model)
927   std::optional<CodeModel::Model> getCodeModel() const;
928 
929   /// Set the code model (tiny, small, kernel, medium or large)
930   void setCodeModel(CodeModel::Model CL);
931   /// @}
932 
933   /// @}
934   /// @name Utility function for querying and setting the large data threshold
935   /// @{
936 
937   /// Returns the large data threshold.
938   std::optional<uint64_t> getLargeDataThreshold() const;
939 
940   /// Set the large data threshold.
941   void setLargeDataThreshold(uint64_t Threshold);
942   /// @}
943 
944   /// @name Utility functions for querying and setting PGO summary
945   /// @{
946 
947   /// Attach profile summary metadata to this module.
948   void setProfileSummary(Metadata *M, ProfileSummary::Kind Kind);
949 
950   /// Returns profile summary metadata. When IsCS is true, use the context
951   /// sensitive profile summary.
952   Metadata *getProfileSummary(bool IsCS) const;
953   /// @}
954 
955   /// Returns whether semantic interposition is to be respected.
956   bool getSemanticInterposition() const;
957 
958   /// Set whether semantic interposition is to be respected.
959   void setSemanticInterposition(bool);
960 
961   /// Returns true if PLT should be avoided for RTLib calls.
962   bool getRtLibUseGOT() const;
963 
964   /// Set that PLT should be avoid for RTLib calls.
965   void setRtLibUseGOT();
966 
967   /// Get/set whether referencing global variables can use direct access
968   /// relocations on ELF targets.
969   bool getDirectAccessExternalData() const;
970   void setDirectAccessExternalData(bool Value);
971 
972   /// Get/set whether synthesized functions should get the uwtable attribute.
973   UWTableKind getUwtable() const;
974   void setUwtable(UWTableKind Kind);
975 
976   /// Get/set whether synthesized functions should get the "frame-pointer"
977   /// attribute.
978   FramePointerKind getFramePointer() const;
979   void setFramePointer(FramePointerKind Kind);
980 
981   /// Get/set what kind of stack protector guard to use.
982   StringRef getStackProtectorGuard() const;
983   void setStackProtectorGuard(StringRef Kind);
984 
985   /// Get/set which register to use as the stack protector guard register. The
986   /// empty string is equivalent to "global". Other values may be "tls" or
987   /// "sysreg".
988   StringRef getStackProtectorGuardReg() const;
989   void setStackProtectorGuardReg(StringRef Reg);
990 
991   /// Get/set a symbol to use as the stack protector guard.
992   StringRef getStackProtectorGuardSymbol() const;
993   void setStackProtectorGuardSymbol(StringRef Symbol);
994 
995   /// Get/set what offset from the stack protector to use.
996   int getStackProtectorGuardOffset() const;
997   void setStackProtectorGuardOffset(int Offset);
998 
999   /// Get/set the stack alignment overridden from the default.
1000   unsigned getOverrideStackAlignment() const;
1001   void setOverrideStackAlignment(unsigned Align);
1002 
1003   unsigned getMaxTLSAlignment() const;
1004 
1005   /// @name Utility functions for querying and setting the build SDK version
1006   /// @{
1007 
1008   /// Attach a build SDK version metadata to this module.
1009   void setSDKVersion(const VersionTuple &V);
1010 
1011   /// Get the build SDK version metadata.
1012   ///
1013   /// An empty version is returned if no such metadata is attached.
1014   VersionTuple getSDKVersion() const;
1015   /// @}
1016 
1017   /// Take ownership of the given memory buffer.
1018   void setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB);
1019 
1020   /// Set the partial sample profile ratio in the profile summary module flag,
1021   /// if applicable.
1022   void setPartialSampleProfileRatio(const ModuleSummaryIndex &Index);
1023 
1024   /// Get the target variant triple which is a string describing a variant of
1025   /// the target host platform. For example, Mac Catalyst can be a variant
1026   /// target triple for a macOS target.
1027   /// @returns a string containing the target variant triple.
1028   StringRef getDarwinTargetVariantTriple() const;
1029 
1030   /// Set the target variant triple which is a string describing a variant of
1031   /// the target host platform.
1032   void setDarwinTargetVariantTriple(StringRef T);
1033 
1034   /// Get the target variant version build SDK version metadata.
1035   ///
1036   /// An empty version is returned if no such metadata is attached.
1037   VersionTuple getDarwinTargetVariantSDKVersion() const;
1038 
1039   /// Set the target variant version build SDK version metadata.
1040   void setDarwinTargetVariantSDKVersion(VersionTuple Version);
1041 
1042   /// Returns target-abi from MDString, null if target-abi is absent.
1043   StringRef getTargetABIFromMD();
1044 
1045   /// Get how unwind v2 (epilog) information should be generated for x64
1046   /// Windows.
1047   WinX64EHUnwindV2Mode getWinX64EHUnwindV2Mode() const;
1048 };
1049 
1050 /// Given "llvm.used" or "llvm.compiler.used" as a global name, collect the
1051 /// initializer elements of that global in a SmallVector and return the global
1052 /// itself.
1053 LLVM_ABI GlobalVariable *
1054 collectUsedGlobalVariables(const Module &M, SmallVectorImpl<GlobalValue *> &Vec,
1055                            bool CompilerUsed);
1056 
1057 /// An raw_ostream inserter for modules.
1058 inline raw_ostream &operator<<(raw_ostream &O, const Module &M) {
1059   M.print(O, nullptr);
1060   return O;
1061 }
1062 
1063 // Create wrappers for C Binding types (see CBindingWrapping.h).
DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Module,LLVMModuleRef)1064 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Module, LLVMModuleRef)
1065 
1066 /* LLVMModuleProviderRef exists for historical reasons, but now just holds a
1067  * Module.
1068  */
1069 inline Module *unwrap(LLVMModuleProviderRef MP) {
1070   return reinterpret_cast<Module*>(MP);
1071 }
1072 
1073 } // end namespace llvm
1074 
1075 #endif // LLVM_IR_MODULE_H
1076