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