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