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