LLVM 22.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
38using ValueToValueMapTy = ValueMap<const Value *, WeakTrackingVH>;
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
119 return RemapFlags(unsigned(LHS) | unsigned(RHS));
120}
121
122/// Context for (re-)mapping values (and metadata).
123///
124/// A shared context used for mapping and remapping of Value and Metadata
125/// instances using \a ValueToValueMapTy, \a RemapFlags, \a
126/// ValueMapTypeRemapper, \a ValueMaterializer, and \a IdentityMD.
127///
128/// There are a number of top-level entry points:
129/// - \a mapValue() (and \a mapConstant());
130/// - \a mapMetadata() (and \a mapMDNode());
131/// - \a remapInstruction();
132/// - \a remapFunction(); and
133/// - \a remapGlobalObjectMetadata().
134///
135/// The \a ValueMaterializer can be used as a callback, but cannot invoke any
136/// of these top-level functions recursively. Instead, callbacks should use
137/// one of the following to schedule work lazily in the \a ValueMapper
138/// instance:
139/// - \a scheduleMapGlobalInitializer()
140/// - \a scheduleMapAppendingVariable()
141/// - \a scheduleMapGlobalAlias()
142/// - \a scheduleMapGlobalIFunc()
143/// - \a scheduleRemapFunction()
144///
145/// Sometimes a callback needs a different mapping context. Such a context can
146/// be registered using \a registerAlternateMappingContext(), which takes an
147/// alternate \a ValueToValueMapTy and \a ValueMaterializer and returns a ID to
148/// pass into the schedule*() functions.
149///
150/// If an \a IdentityMD predicate is optionally provided, \a Metadata for which
151/// the predicate returns true will be mapped onto itself in \a VM on first use.
152///
153/// TODO: lib/Linker really doesn't need the \a ValueHandle in the \a
154/// ValueToValueMapTy. We should template \a ValueMapper (and its
155/// implementation classes), and explicitly instantiate on two concrete
156/// instances of \a ValueMap (one as \a ValueToValueMap, and one with raw \a
157/// Value pointers). It may be viable to do away with \a TrackingMDRef in the
158/// \a Metadata side map for the lib/Linker case as well, in which case we'll
159/// need a new template parameter on \a ValueMap.
160///
161/// TODO: Update callers of \a RemapInstruction() and \a MapValue() (etc.) to
162/// use \a ValueMapper directly.
164 void *pImpl;
165
166public:
168 ValueMapTypeRemapper *TypeMapper = nullptr,
169 ValueMaterializer *Materializer = nullptr,
170 const MetadataPredicate *IdentityMD = nullptr);
172 ValueMapper(const ValueMapper &) = delete;
176
177 /// Register an alternate mapping context.
178 ///
179 /// Returns a MappingContextID that can be used with the various schedule*()
180 /// API to switch in a different value map on-the-fly.
181 LLVM_ABI unsigned
183 ValueMaterializer *Materializer = nullptr);
184
185 /// Add to the current \a RemapFlags.
186 ///
187 /// \note Like the top-level mapping functions, \a addFlags() must be called
188 /// at the top level, not during a callback in a \a ValueMaterializer.
189 LLVM_ABI void addFlags(RemapFlags Flags);
190
193
194 LLVM_ABI Value *mapValue(const Value &V);
196
203
205 unsigned MappingContextID = 0);
207 Constant *InitPrefix,
208 bool IsOldCtorDtor,
209 ArrayRef<Constant *> NewMembers,
210 unsigned MappingContextID = 0);
212 unsigned MappingContextID = 0);
214 unsigned MappingContextID = 0);
216 unsigned MappingContextID = 0);
217};
218
219/// Look up or compute a value in the value map.
220///
221/// Return a mapped value for a function-local value (Argument, Instruction,
222/// BasicBlock), or compute and memoize a value for a Constant.
223///
224/// 1. If \c V is in VM, return the result.
225/// 2. Else if \c V can be materialized with \c Materializer, do so, memoize
226/// it in \c VM, and return it.
227/// 3. Else if \c V is a function-local value, return nullptr.
228/// 4. Else if \c V is a \a GlobalValue, return \c nullptr or \c V depending
229/// on \a RF_NullMapMissingGlobalValues.
230/// 5. Else if \c V is a \a MetadataAsValue wrapping a LocalAsMetadata,
231/// recurse on the local SSA value, and return nullptr or "metadata !{}" on
232/// missing depending on RF_IgnoreMissingValues.
233/// 6. Else if \c V is a \a MetadataAsValue, rewrap the return of \a
234/// MapMetadata().
235/// 7. Else, compute the equivalent constant, and return it.
236inline Value *MapValue(const Value *V, ValueToValueMapTy &VM,
237 RemapFlags Flags = RF_None,
238 ValueMapTypeRemapper *TypeMapper = nullptr,
239 ValueMaterializer *Materializer = nullptr,
240 const MetadataPredicate *IdentityMD = nullptr) {
241 return ValueMapper(VM, Flags, TypeMapper, Materializer, IdentityMD)
242 .mapValue(*V);
243}
244
245/// Lookup or compute a mapping for a piece of metadata.
246///
247/// Compute and memoize a mapping for \c MD.
248///
249/// 1. If \c MD is mapped, return it.
250/// 2. Else if \a RF_NoModuleLevelChanges or \c MD is an \a MDString, return
251/// \c MD.
252/// 3. Else if \c MD is a \a ConstantAsMetadata, call \a MapValue() and
253/// re-wrap its return (returning nullptr on nullptr).
254/// 4. Else if \c IdentityMD predicate returns true for \c MD then add an
255/// identity mapping for it and return it.
256/// 5. Else, \c MD is an \a MDNode. These are remapped, along with their
257/// transitive operands. Distinct nodes are duplicated or moved depending
258/// on \a RF_MoveDistinctNodes. Uniqued nodes are remapped like constants.
259///
260/// \note \a LocalAsMetadata is completely unsupported by \a MapMetadata.
261/// Instead, use \a MapValue() with its wrapping \a MetadataAsValue instance.
263 RemapFlags Flags = RF_None,
264 ValueMapTypeRemapper *TypeMapper = nullptr,
265 ValueMaterializer *Materializer = nullptr,
266 const MetadataPredicate *IdentityMD = nullptr) {
267 return ValueMapper(VM, Flags, TypeMapper, Materializer, IdentityMD)
268 .mapMetadata(*MD);
269}
270
271/// Version of MapMetadata with type safety for MDNode.
273 RemapFlags Flags = RF_None,
274 ValueMapTypeRemapper *TypeMapper = nullptr,
275 ValueMaterializer *Materializer = nullptr,
276 const MetadataPredicate *IdentityMD = nullptr) {
277 return ValueMapper(VM, Flags, TypeMapper, Materializer, IdentityMD)
278 .mapMDNode(*MD);
279}
280
281/// Convert the instruction operands from referencing the current values into
282/// those specified by VM.
283///
284/// If \a RF_IgnoreMissingLocals is set and an operand can't be found via \a
285/// MapValue(), use the old value. Otherwise assert that this doesn't happen.
286///
287/// Note that \a MapValue() only returns \c nullptr for SSA values missing from
288/// \c VM.
290 RemapFlags Flags = RF_None,
291 ValueMapTypeRemapper *TypeMapper = nullptr,
292 ValueMaterializer *Materializer = nullptr,
293 const MetadataPredicate *IdentityMD = nullptr) {
294 ValueMapper(VM, Flags, TypeMapper, Materializer, IdentityMD)
296}
297
298/// Remap source location atom. Called by RemapInstruction. This updates the
299/// instruction's atom group number if it has been mapped (e.g. with
300/// llvm::mapAtomInstance), which is necessary to distinguish source code
301/// atoms on duplicated code paths.
302LLVM_ABI void RemapSourceAtom(Instruction *I, ValueToValueMapTy &VM);
303
304/// Remap the Values used in the DbgRecord \a DR using the value map \a
305/// VM.
307 RemapFlags Flags = RF_None,
308 ValueMapTypeRemapper *TypeMapper = nullptr,
309 ValueMaterializer *Materializer = nullptr,
310 const MetadataPredicate *IdentityMD = nullptr) {
311 ValueMapper(VM, Flags, TypeMapper, Materializer, IdentityMD)
312 .remapDbgRecord(M, *DR);
313}
314
315/// Remap the Values used in the DbgRecords \a Range using the value map \a
316/// VM.
320 RemapFlags Flags = RF_None,
321 ValueMapTypeRemapper *TypeMapper = nullptr,
322 ValueMaterializer *Materializer = nullptr,
323 const MetadataPredicate *IdentityMD = nullptr) {
324 ValueMapper(VM, Flags, TypeMapper, Materializer, IdentityMD)
326}
327
328/// Remap the operands, metadata, arguments, and instructions of a function.
329///
330/// Calls \a MapValue() on prefix data, prologue data, and personality
331/// function; calls \a MapMetadata() on each attached MDNode; remaps the
332/// argument types using the provided \c TypeMapper; and calls \a
333/// RemapInstruction() on every instruction.
335 RemapFlags Flags = RF_None,
336 ValueMapTypeRemapper *TypeMapper = nullptr,
337 ValueMaterializer *Materializer = nullptr,
338 const MetadataPredicate *IdentityMD = nullptr) {
339 ValueMapper(VM, Flags, TypeMapper, Materializer, IdentityMD).remapFunction(F);
340}
341
342/// Version of MapValue with type safety for Constant.
344 RemapFlags Flags = RF_None,
345 ValueMapTypeRemapper *TypeMapper = nullptr,
346 ValueMaterializer *Materializer = nullptr,
347 const MetadataPredicate *IdentityMD = nullptr) {
348 return ValueMapper(VM, Flags, TypeMapper, Materializer, IdentityMD)
349 .mapConstant(*V);
350}
351
352} // end namespace llvm
353
354#endif // LLVM_TRANSFORMS_UTILS_VALUEMAPPER_H
RelocType Type
Definition: COFFYAML.cpp:410
#define LLVM_ABI
Definition: Compiler.h:213
dxil translate DXIL Translate Metadata
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
Machine Check Debug Module
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:41
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:1077
Root of the metadata hierarchy.
Definition: Metadata.h:63
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:2196
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:541
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
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.
Context for (re-)mapping values (and metadata).
Definition: ValueMapper.h:163
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 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 scheduleMapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix, bool IsOldCtorDtor, ArrayRef< Constant * > NewMembers, unsigned MappingContextID=0)
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 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.
typename ilist_select_iterator_type< OptionsT::has_iterator_bits, OptionsT, false, false >::type iterator
Definition: simple_ilist.h:97
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
simple_ilist< DbgRecord >::iterator DbgRecordIterator
Definition: ValueMapper.h:39
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.
Definition: ValueMapper.h:317
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.
Definition: ValueMapper.h:108
@ 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.
Definition: ValueMapper.h:115
@ RF_ReuseAndMutateDistinctMDs
Instruct the remapper to reuse and mutate distinct metadata (remapping them in place) instead of clon...
Definition: ValueMapper.h:104
std::function< bool(const Metadata *)> MetadataPredicate
Definition: ValueMapper.h:41
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.
Definition: ValueMapper.h:289
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.
Definition: ValueMapper.h:306
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.
Definition: ValueMapper.h:236
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.
Definition: ValueMapper.h:334
APInt operator|(APInt a, const APInt &b)
Definition: APInt.h:2143
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.
Definition: ValueMapper.h:262
#define N