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