LLVM 23.0.0git
ValueMapper.h
Go to the documentation of this file.
1//===- ValueMapper.h - Remapping for constants and metadata -----*- 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// This file defines the MapValue interface which is used by various parts of
10// the Transforms/Utils library to implement cloning and linking facilities.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_TRANSFORMS_UTILS_VALUEMAPPER_H
15#define LLVM_TRANSFORMS_UTILS_VALUEMAPPER_H
16
17#include "llvm/ADT/ArrayRef.h"
20#include "llvm/IR/ValueHandle.h"
21#include "llvm/IR/ValueMap.h"
23
24namespace llvm {
25
26class Constant;
27class DIBuilder;
28class DbgRecord;
29class Function;
30class GlobalVariable;
31class Instruction;
32class MDNode;
33class Metadata;
34class Module;
35class Type;
36class Value;
37
41using MetadataPredicate = std::function<bool(const Metadata *)>;
42
43/// This is a class that can be implemented by clients to remap types when
44/// cloning constants and instructions.
46 virtual void anchor(); // Out of line method.
47
48public:
49 virtual ~ValueMapTypeRemapper() = default;
50
51 /// The client should implement this method if they want to remap types while
52 /// mapping values.
53 virtual Type *remapType(Type *SrcTy) = 0;
54};
55
56/// This is a class that can be implemented by clients to materialize Values on
57/// demand.
59 virtual void anchor(); // Out of line method.
60
61protected:
62 ValueMaterializer() = default;
65 ~ValueMaterializer() = default;
66
67public:
68 /// This method can be implemented to generate a mapped Value on demand. For
69 /// example, if linking lazily. Returns null if the value is not materialized.
70 virtual Value *materialize(Value *V) = 0;
71};
72
73/// These are flags that the value mapping APIs allow.
76
77 /// If this flag is set, the remapper knows that only local values within a
78 /// function (such as an instruction or argument) are mapped, not global
79 /// values like functions and global metadata.
81
82 /// If this flag is set, the remapper ignores missing function-local entries
83 /// (Argument, Instruction, BasicBlock) that are not in the value map. If it
84 /// is unset, it aborts if an operand is asked to be remapped which doesn't
85 /// exist in the mapping.
86 ///
87 /// There are no such assertions in MapValue(), whose results are almost
88 /// unchanged by this flag. This flag mainly changes the assertion behaviour
89 /// in RemapInstruction().
90 ///
91 /// Since an Instruction's metadata operands (even that point to SSA values)
92 /// aren't guaranteed to be dominated by their definitions, MapMetadata will
93 /// return "!{}" instead of "null" for \a LocalAsMetadata instances whose SSA
94 /// values are unmapped when this flag is set. Otherwise, \a MapValue()
95 /// completely ignores this flag.
96 ///
97 /// \a MapMetadata() always ignores this flag.
99
100 /// Instruct the remapper to reuse and mutate distinct metadata (remapping
101 /// them in place) instead of cloning remapped copies. This flag has no
102 /// effect when RF_NoModuleLevelChanges, since that implies an identity
103 /// mapping.
105
106 /// Any global values not in value map are mapped to null instead of mapping
107 /// to self. Illegal if RF_IgnoreMissingLocals is also set.
109
110 /// Do not remap source location atoms. Only safe if to do this if the cloned
111 /// instructions being remapped are inserted into a new function, or an
112 /// existing function where the inlined-at fields are updated. If in doubt,
113 /// don't use this flag. It's used when remapping is known to be un-necessary
114 /// to save some compile-time.
116
117 /// Indicate that we are importing functions, specifically in the context of
118 /// ThinLTO. There is some ad-hoc behavior required in this mode.
120};
121
123 return RemapFlags(unsigned(LHS) | unsigned(RHS));
124}
125
126/// Context for (re-)mapping values (and metadata).
127///
128/// A shared context used for mapping and remapping of Value and Metadata
129/// instances using \a ValueToValueMapTy, \a RemapFlags, \a
130/// ValueMapTypeRemapper, \a ValueMaterializer, and \a IdentityMD.
131///
132/// There are a number of top-level entry points:
133/// - \a mapValue() (and \a mapConstant());
134/// - \a mapMetadata() (and \a mapMDNode());
135/// - \a remapInstruction();
136/// - \a remapFunction(); and
137/// - \a remapGlobalObjectMetadata().
138///
139/// The \a ValueMaterializer can be used as a callback, but cannot invoke any
140/// of these top-level functions recursively. Instead, callbacks should use
141/// one of the following to schedule work lazily in the \a ValueMapper
142/// instance:
143/// - \a scheduleMapGlobalInitializer()
144/// - \a scheduleMapAppendingVariable()
145/// - \a scheduleMapGlobalAlias()
146/// - \a scheduleMapGlobalIFunc()
147/// - \a scheduleRemapFunction()
148///
149/// Sometimes a callback needs a different mapping context. Such a context can
150/// be registered using \a registerAlternateMappingContext(), which takes an
151/// alternate \a ValueToValueMapTy and \a ValueMaterializer and returns a ID to
152/// pass into the schedule*() functions.
153///
154/// If an \a IdentityMD predicate is optionally provided, \a Metadata for which
155/// the predicate returns true will be mapped onto itself in \a VM on first use.
156///
157/// TODO: lib/Linker really doesn't need the \a ValueHandle in the \a
158/// ValueToValueMapTy. We should template \a ValueMapper (and its
159/// implementation classes), and explicitly instantiate on two concrete
160/// instances of \a ValueMap (one as \a ValueToValueMap, and one with raw \a
161/// Value pointers). It may be viable to do away with \a TrackingMDRef in the
162/// \a Metadata side map for the lib/Linker case as well, in which case we'll
163/// need a new template parameter on \a ValueMap.
164///
165/// TODO: Update callers of \a RemapInstruction() and \a MapValue() (etc.) to
166/// use \a ValueMapper directly.
168 void *pImpl;
169
170public:
172 ValueMapTypeRemapper *TypeMapper = nullptr,
173 ValueMaterializer *Materializer = nullptr,
174 const MetadataPredicate *IdentityMD = nullptr);
176 ValueMapper(const ValueMapper &) = delete;
180
181 /// Register an alternate mapping context.
182 ///
183 /// Returns a MappingContextID that can be used with the various schedule*()
184 /// API to switch in a different value map on-the-fly.
185 LLVM_ABI unsigned
187 ValueMaterializer *Materializer = nullptr);
188
189 /// Add to the current \a RemapFlags.
190 ///
191 /// \note Like the top-level mapping functions, \a addFlags() must be called
192 /// at the top level, not during a callback in a \a ValueMaterializer.
193 LLVM_ABI void addFlags(RemapFlags Flags);
194
197
198 LLVM_ABI Value *mapValue(const Value &V);
200
207
209 unsigned MappingContextID = 0);
211 GlobalVariable *OldGV,
212 bool IsOldCtorDtor,
213 ArrayRef<Constant *> NewMembers,
214 unsigned MappingContextID = 0);
216 unsigned MappingContextID = 0);
218 unsigned MappingContextID = 0);
220 unsigned MappingContextID = 0);
221};
222
223/// Look up or compute a value in the value map.
224///
225/// Return a mapped value for a function-local value (Argument, Instruction,
226/// BasicBlock), or compute and memoize a value for a Constant.
227///
228/// 1. If \c V is in VM, return the result.
229/// 2. Else if \c V can be materialized with \c Materializer, do so, memoize
230/// it in \c VM, and return it.
231/// 3. Else if \c V is a function-local value, return nullptr.
232/// 4. Else if \c V is a \a GlobalValue, return \c nullptr or \c V depending
233/// on \a RF_NullMapMissingGlobalValues.
234/// 5. Else if \c V is a \a MetadataAsValue wrapping a LocalAsMetadata,
235/// recurse on the local SSA value, and return nullptr or "metadata !{}" on
236/// missing depending on RF_IgnoreMissingValues.
237/// 6. Else if \c V is a \a MetadataAsValue, rewrap the return of \a
238/// MapMetadata().
239/// 7. Else, compute the equivalent constant, and return it.
240inline Value *MapValue(const Value *V, ValueToValueMapTy &VM,
241 RemapFlags Flags = RF_None,
242 ValueMapTypeRemapper *TypeMapper = nullptr,
243 ValueMaterializer *Materializer = nullptr,
244 const MetadataPredicate *IdentityMD = nullptr) {
245 return ValueMapper(VM, Flags, TypeMapper, Materializer, IdentityMD)
246 .mapValue(*V);
247}
248
249/// Lookup or compute a mapping for a piece of metadata.
250///
251/// Compute and memoize a mapping for \c MD.
252///
253/// 1. If \c MD is mapped, return it.
254/// 2. Else if \a RF_NoModuleLevelChanges or \c MD is an \a MDString, return
255/// \c MD.
256/// 3. Else if \c MD is a \a ConstantAsMetadata, call \a MapValue() and
257/// re-wrap its return (returning nullptr on nullptr).
258/// 4. Else if \c IdentityMD predicate returns true for \c MD then add an
259/// identity mapping for it and return it.
260/// 5. Else, \c MD is an \a MDNode. These are remapped, along with their
261/// transitive operands. Distinct nodes are duplicated or moved depending
262/// on \a RF_MoveDistinctNodes. Uniqued nodes are remapped like constants.
263///
264/// \note \a LocalAsMetadata is completely unsupported by \a MapMetadata.
265/// Instead, use \a MapValue() with its wrapping \a MetadataAsValue instance.
267 RemapFlags Flags = RF_None,
268 ValueMapTypeRemapper *TypeMapper = nullptr,
269 ValueMaterializer *Materializer = nullptr,
270 const MetadataPredicate *IdentityMD = nullptr) {
271 return ValueMapper(VM, Flags, TypeMapper, Materializer, IdentityMD)
272 .mapMetadata(*MD);
273}
274
275/// Version of MapMetadata with type safety for MDNode.
277 RemapFlags Flags = RF_None,
278 ValueMapTypeRemapper *TypeMapper = nullptr,
279 ValueMaterializer *Materializer = nullptr,
280 const MetadataPredicate *IdentityMD = nullptr) {
281 return ValueMapper(VM, Flags, TypeMapper, Materializer, IdentityMD)
282 .mapMDNode(*MD);
283}
284
285/// Convert the instruction operands from referencing the current values into
286/// those specified by VM.
287///
288/// If \a RF_IgnoreMissingLocals is set and an operand can't be found via \a
289/// MapValue(), use the old value. Otherwise assert that this doesn't happen.
290///
291/// Note that \a MapValue() only returns \c nullptr for SSA values missing from
292/// \c VM.
294 RemapFlags Flags = RF_None,
295 ValueMapTypeRemapper *TypeMapper = nullptr,
296 ValueMaterializer *Materializer = nullptr,
297 const MetadataPredicate *IdentityMD = nullptr) {
298 ValueMapper(VM, Flags, TypeMapper, Materializer, IdentityMD)
300}
301
302/// Remap source location atom. Called by RemapInstruction. This updates the
303/// instruction's atom group number if it has been mapped (e.g. with
304/// llvm::mapAtomInstance), which is necessary to distinguish source code
305/// atoms on duplicated code paths.
306LLVM_ABI void RemapSourceAtom(Instruction *I, ValueToValueMapTy &VM);
307
308/// Remap the Values used in the DbgRecord \a DR using the value map \a
309/// VM.
311 RemapFlags Flags = RF_None,
312 ValueMapTypeRemapper *TypeMapper = nullptr,
313 ValueMaterializer *Materializer = nullptr,
314 const MetadataPredicate *IdentityMD = nullptr) {
315 ValueMapper(VM, Flags, TypeMapper, Materializer, IdentityMD)
316 .remapDbgRecord(M, *DR);
317}
318
319/// Remap the Values used in the DbgRecords \a Range using the value map \a
320/// VM.
324 RemapFlags Flags = RF_None,
325 ValueMapTypeRemapper *TypeMapper = nullptr,
326 ValueMaterializer *Materializer = nullptr,
327 const MetadataPredicate *IdentityMD = nullptr) {
328 ValueMapper(VM, Flags, TypeMapper, Materializer, IdentityMD)
330}
331
332/// Remap the operands, metadata, arguments, and instructions of a function.
333///
334/// Calls \a MapValue() on prefix data, prologue data, and personality
335/// function; calls \a MapMetadata() on each attached MDNode; remaps the
336/// argument types using the provided \c TypeMapper; and calls \a
337/// RemapInstruction() on every instruction.
339 RemapFlags Flags = RF_None,
340 ValueMapTypeRemapper *TypeMapper = nullptr,
341 ValueMaterializer *Materializer = nullptr,
342 const MetadataPredicate *IdentityMD = nullptr) {
343 ValueMapper(VM, Flags, TypeMapper, Materializer, IdentityMD).remapFunction(F);
344}
345
346/// Version of MapValue with type safety for Constant.
348 RemapFlags Flags = RF_None,
349 ValueMapTypeRemapper *TypeMapper = nullptr,
350 ValueMaterializer *Materializer = nullptr,
351 const MetadataPredicate *IdentityMD = nullptr) {
352 return ValueMapper(VM, Flags, TypeMapper, Materializer, IdentityMD)
353 .mapConstant(*V);
354}
355
356} // end namespace llvm
357
358#endif // LLVM_TRANSFORMS_UTILS_VALUEMAPPER_H
#define LLVM_ABI
Definition Compiler.h:213
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
This file defines the SmallPtrSet class.
Value * RHS
Value * LHS
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
This is an important base class in LLVM.
Definition Constant.h:43
Base class for non-instruction debug metadata records that have positions within IR.
Metadata node.
Definition Metadata.h:1080
Root of the metadata hierarchy.
Definition Metadata.h:64
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
Interface for looking up the initializer for a variable name, used by Init::resolveReferences.
Definition Record.h:2199
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
This is a class that can be implemented by clients to remap types when cloning constants and instruct...
Definition ValueMapper.h:45
virtual ~ValueMapTypeRemapper()=default
virtual Type * remapType(Type *SrcTy)=0
The client should implement this method if they want to remap types while mapping values.
See the file comment.
Definition ValueMap.h:84
Context for (re-)mapping values (and metadata).
LLVM_ABI void remapDbgRecord(Module *M, DbgRecord &V)
LLVM_ABI ~ValueMapper()
LLVM_ABI void remapDbgRecordRange(Module *M, iterator_range< DbgRecordIterator > Range)
LLVM_ABI MDNode * mapMDNode(const MDNode &N)
LLVM_ABI Metadata * mapMetadata(const Metadata &MD)
ValueMapper & operator=(const ValueMapper &)=delete
LLVM_ABI void remapInstruction(Instruction &I)
ValueMapper(ValueMapper &&)=delete
LLVM_ABI void scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init, unsigned MappingContextID=0)
LLVM_ABI void scheduleRemapFunction(Function &F, unsigned MappingContextID=0)
LLVM_ABI ValueMapper(ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
LLVM_ABI void scheduleMapGlobalIFunc(GlobalIFunc &GI, Constant &Resolver, unsigned MappingContextID=0)
LLVM_ABI unsigned registerAlternateMappingContext(ValueToValueMapTy &VM, ValueMaterializer *Materializer=nullptr)
Register an alternate mapping context.
ValueMapper(const ValueMapper &)=delete
LLVM_ABI void remapFunction(Function &F)
LLVM_ABI Constant * mapConstant(const Constant &C)
ValueMapper & operator=(ValueMapper &&)=delete
LLVM_ABI void scheduleMapGlobalAlias(GlobalAlias &GA, Constant &Aliasee, unsigned MappingContextID=0)
LLVM_ABI void remapGlobalObjectMetadata(GlobalObject &GO)
LLVM_ABI Value * mapValue(const Value &V)
LLVM_ABI void scheduleMapAppendingVariable(GlobalVariable &GV, GlobalVariable *OldGV, bool IsOldCtorDtor, ArrayRef< Constant * > NewMembers, unsigned MappingContextID=0)
LLVM_ABI void addFlags(RemapFlags Flags)
Add to the current RemapFlags.
This is a class that can be implemented by clients to materialize Values on demand.
Definition ValueMapper.h:58
ValueMaterializer & operator=(const ValueMaterializer &)=default
virtual Value * materialize(Value *V)=0
This method can be implemented to generate a mapped Value on demand.
ValueMaterializer(const ValueMaterializer &)=default
LLVM Value Representation.
Definition Value.h:75
A range adaptor for a pair of iterators.
ilist_select_iterator_type< OptionsT, false, false > iterator
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
This is an optimization pass for GlobalISel generic memory operations.
std::function< bool(const Metadata *)> MetadataPredicate
Definition ValueMapper.h:41
void RemapDbgRecordRange(Module *M, iterator_range< DbgRecordIterator > Range, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Remap the Values used in the DbgRecords Range using the value map VM.
RemapFlags
These are flags that the value mapping APIs allow.
Definition ValueMapper.h:74
@ RF_IgnoreMissingLocals
If this flag is set, the remapper ignores missing function-local entries (Argument,...
Definition ValueMapper.h:98
@ RF_NullMapMissingGlobalValues
Any global values not in value map are mapped to null instead of mapping to self.
@ RF_None
Definition ValueMapper.h:75
@ RF_NoModuleLevelChanges
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
Definition ValueMapper.h:80
@ RF_DoNotRemapAtoms
Do not remap source location atoms.
@ RF_Importing
Indicate that we are importing functions, specifically in the context of ThinLTO.
@ RF_ReuseAndMutateDistinctMDs
Instruct the remapper to reuse and mutate distinct metadata (remapping them in place) instead of clon...
SmallPtrSet< const Metadata *, 16 > MetadataSetTy
Definition ValueMapper.h:40
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Convert the instruction operands from referencing the current values into those specified by VM.
void RemapDbgRecord(Module *M, DbgRecord *DR, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Remap the Values used in the DbgRecord DR using the value map VM.
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
Value * MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Look up or compute a value in the value map.
void RemapFunction(Function &F, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Remap the operands, metadata, arguments, and instructions of a function.
simple_ilist< DbgRecord >::iterator DbgRecordIterator
Definition ValueMapper.h:39
APInt operator|(APInt a, const APInt &b)
Definition APInt.h:2172
LLVM_ABI void RemapSourceAtom(Instruction *I, ValueToValueMapTy &VM)
Remap source location atom.
Metadata * MapMetadata(const Metadata *MD, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Lookup or compute a mapping for a piece of metadata.
#define N