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"
18 #include "llvm/IR/ValueHandle.h"
19 #include "llvm/IR/ValueMap.h"
20 
21 namespace llvm {
22 
23 class Constant;
24 class Function;
25 class GlobalVariable;
26 class Instruction;
27 class MDNode;
28 class Metadata;
29 class Type;
30 class Value;
31 
32 using ValueToValueMapTy = ValueMap<const Value *, WeakTrackingVH>;
33 
34 /// This is a class that can be implemented by clients to remap types when
35 /// cloning constants and instructions.
36 class ValueMapTypeRemapper {
37   virtual void anchor(); // Out of line method.
38 
39 public:
40   virtual ~ValueMapTypeRemapper() = default;
41 
42   /// The client should implement this method if they want to remap types while
43   /// mapping values.
44   virtual Type *remapType(Type *SrcTy) = 0;
45 };
46 
47 /// This is a class that can be implemented by clients to materialize Values on
48 /// demand.
49 class ValueMaterializer {
50   virtual void anchor(); // Out of line method.
51 
52 protected:
53   ValueMaterializer() = default;
54   ValueMaterializer(const ValueMaterializer &) = default;
55   ValueMaterializer &operator=(const ValueMaterializer &) = default;
56   ~ValueMaterializer() = default;
57 
58 public:
59   /// This method can be implemented to generate a mapped Value on demand. For
60   /// example, if linking lazily. Returns null if the value is not materialized.
61   virtual Value *materialize(Value *V) = 0;
62 };
63 
64 /// These are flags that the value mapping APIs allow.
65 enum RemapFlags {
66   RF_None = 0,
67 
68   /// If this flag is set, the remapper knows that only local values within a
69   /// function (such as an instruction or argument) are mapped, not global
70   /// values like functions and global metadata.
71   RF_NoModuleLevelChanges = 1,
72 
73   /// If this flag is set, the remapper ignores missing function-local entries
74   /// (Argument, Instruction, BasicBlock) that are not in the value map.  If it
75   /// is unset, it aborts if an operand is asked to be remapped which doesn't
76   /// exist in the mapping.
77   ///
78   /// There are no such assertions in MapValue(), whose results are almost
79   /// unchanged by this flag.  This flag mainly changes the assertion behaviour
80   /// in RemapInstruction().
81   ///
82   /// Since an Instruction's metadata operands (even that point to SSA values)
83   /// aren't guaranteed to be dominated by their definitions, MapMetadata will
84   /// return "!{}" instead of "null" for \a LocalAsMetadata instances whose SSA
85   /// values are unmapped when this flag is set.  Otherwise, \a MapValue()
86   /// completely ignores this flag.
87   ///
88   /// \a MapMetadata() always ignores this flag.
89   RF_IgnoreMissingLocals = 2,
90 
91   /// Instruct the remapper to reuse and mutate distinct metadata (remapping
92   /// them in place) instead of cloning remapped copies. This flag has no
93   /// effect when when RF_NoModuleLevelChanges, since that implies an identity
94   /// mapping.
95   RF_ReuseAndMutateDistinctMDs = 4,
96 
97   /// Any global values not in value map are mapped to null instead of mapping
98   /// to self.  Illegal if RF_IgnoreMissingLocals is also set.
99   RF_NullMapMissingGlobalValues = 8,
100 };
101 
102 inline RemapFlags operator|(RemapFlags LHS, RemapFlags RHS) {
103   return RemapFlags(unsigned(LHS) | unsigned(RHS));
104 }
105 
106 /// Context for (re-)mapping values (and metadata).
107 ///
108 /// A shared context used for mapping and remapping of Value and Metadata
109 /// instances using \a ValueToValueMapTy, \a RemapFlags, \a
110 /// ValueMapTypeRemapper, and \a ValueMaterializer.
111 ///
112 /// There are a number of top-level entry points:
113 /// - \a mapValue() (and \a mapConstant());
114 /// - \a mapMetadata() (and \a mapMDNode());
115 /// - \a remapInstruction();
116 /// - \a remapFunction(); and
117 /// - \a remapGlobalObjectMetadata().
118 ///
119 /// The \a ValueMaterializer can be used as a callback, but cannot invoke any
120 /// of these top-level functions recursively.  Instead, callbacks should use
121 /// one of the following to schedule work lazily in the \a ValueMapper
122 /// instance:
123 /// - \a scheduleMapGlobalInitializer()
124 /// - \a scheduleMapAppendingVariable()
125 /// - \a scheduleMapGlobalAlias()
126 /// - \a scheduleMapGlobalIFunc()
127 /// - \a scheduleRemapFunction()
128 ///
129 /// Sometimes a callback needs a different mapping context.  Such a context can
130 /// be registered using \a registerAlternateMappingContext(), which takes an
131 /// alternate \a ValueToValueMapTy and \a ValueMaterializer and returns a ID to
132 /// pass into the schedule*() functions.
133 ///
134 /// TODO: lib/Linker really doesn't need the \a ValueHandle in the \a
135 /// ValueToValueMapTy.  We should template \a ValueMapper (and its
136 /// implementation classes), and explicitly instantiate on two concrete
137 /// instances of \a ValueMap (one as \a ValueToValueMap, and one with raw \a
138 /// Value pointers).  It may be viable to do away with \a TrackingMDRef in the
139 /// \a Metadata side map for the lib/Linker case as well, in which case we'll
140 /// need a new template parameter on \a ValueMap.
141 ///
142 /// TODO: Update callers of \a RemapInstruction() and \a MapValue() (etc.) to
143 /// use \a ValueMapper directly.
144 class ValueMapper {
145   void *pImpl;
146 
147 public:
148   ValueMapper(ValueToValueMapTy &VM, RemapFlags Flags = RF_None,
149               ValueMapTypeRemapper *TypeMapper = nullptr,
150               ValueMaterializer *Materializer = nullptr);
151   ValueMapper(ValueMapper &&) = delete;
152   ValueMapper(const ValueMapper &) = delete;
153   ValueMapper &operator=(ValueMapper &&) = delete;
154   ValueMapper &operator=(const ValueMapper &) = delete;
155   ~ValueMapper();
156 
157   /// Register an alternate mapping context.
158   ///
159   /// Returns a MappingContextID that can be used with the various schedule*()
160   /// API to switch in a different value map on-the-fly.
161   unsigned
162   registerAlternateMappingContext(ValueToValueMapTy &VM,
163                                   ValueMaterializer *Materializer = nullptr);
164 
165   /// Add to the current \a RemapFlags.
166   ///
167   /// \note Like the top-level mapping functions, \a addFlags() must be called
168   /// at the top level, not during a callback in a \a ValueMaterializer.
169   void addFlags(RemapFlags Flags);
170 
171   Metadata *mapMetadata(const Metadata &MD);
172   MDNode *mapMDNode(const MDNode &N);
173 
174   Value *mapValue(const Value &V);
175   Constant *mapConstant(const Constant &C);
176 
177   void remapInstruction(Instruction &I);
178   void remapFunction(Function &F);
179   void remapGlobalObjectMetadata(GlobalObject &GO);
180 
181   void scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init,
182                                     unsigned MappingContextID = 0);
183   void scheduleMapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
184                                     bool IsOldCtorDtor,
185                                     ArrayRef<Constant *> NewMembers,
186                                     unsigned MappingContextID = 0);
187   void scheduleMapGlobalAlias(GlobalAlias &GA, Constant &Aliasee,
188                               unsigned MappingContextID = 0);
189   void scheduleMapGlobalIFunc(GlobalIFunc &GI, Constant &Resolver,
190                               unsigned MappingContextID = 0);
191   void scheduleRemapFunction(Function &F, unsigned MappingContextID = 0);
192 };
193 
194 /// Look up or compute a value in the value map.
195 ///
196 /// Return a mapped value for a function-local value (Argument, Instruction,
197 /// BasicBlock), or compute and memoize a value for a Constant.
198 ///
199 ///  1. If \c V is in VM, return the result.
200 ///  2. Else if \c V can be materialized with \c Materializer, do so, memoize
201 ///     it in \c VM, and return it.
202 ///  3. Else if \c V is a function-local value, return nullptr.
203 ///  4. Else if \c V is a \a GlobalValue, return \c nullptr or \c V depending
204 ///     on \a RF_NullMapMissingGlobalValues.
205 ///  5. Else if \c V is a \a MetadataAsValue wrapping a LocalAsMetadata,
206 ///     recurse on the local SSA value, and return nullptr or "metadata !{}" on
207 ///     missing depending on RF_IgnoreMissingValues.
208 ///  6. Else if \c V is a \a MetadataAsValue, rewrap the return of \a
209 ///     MapMetadata().
210 ///  7. Else, compute the equivalent constant, and return it.
211 inline Value *MapValue(const Value *V, ValueToValueMapTy &VM,
212                        RemapFlags Flags = RF_None,
213                        ValueMapTypeRemapper *TypeMapper = nullptr,
214                        ValueMaterializer *Materializer = nullptr) {
215   return ValueMapper(VM, Flags, TypeMapper, Materializer).mapValue(*V);
216 }
217 
218 /// Lookup or compute a mapping for a piece of metadata.
219 ///
220 /// Compute and memoize a mapping for \c MD.
221 ///
222 ///  1. If \c MD is mapped, return it.
223 ///  2. Else if \a RF_NoModuleLevelChanges or \c MD is an \a MDString, return
224 ///     \c MD.
225 ///  3. Else if \c MD is a \a ConstantAsMetadata, call \a MapValue() and
226 ///     re-wrap its return (returning nullptr on nullptr).
227 ///  4. Else, \c MD is an \a MDNode.  These are remapped, along with their
228 ///     transitive operands.  Distinct nodes are duplicated or moved depending
229 ///     on \a RF_MoveDistinctNodes.  Uniqued nodes are remapped like constants.
230 ///
231 /// \note \a LocalAsMetadata is completely unsupported by \a MapMetadata.
232 /// Instead, use \a MapValue() with its wrapping \a MetadataAsValue instance.
233 inline Metadata *MapMetadata(const Metadata *MD, ValueToValueMapTy &VM,
234                              RemapFlags Flags = RF_None,
235                              ValueMapTypeRemapper *TypeMapper = nullptr,
236                              ValueMaterializer *Materializer = nullptr) {
237   return ValueMapper(VM, Flags, TypeMapper, Materializer).mapMetadata(*MD);
238 }
239 
240 /// Version of MapMetadata with type safety for MDNode.
241 inline MDNode *MapMetadata(const MDNode *MD, ValueToValueMapTy &VM,
242                            RemapFlags Flags = RF_None,
243                            ValueMapTypeRemapper *TypeMapper = nullptr,
244                            ValueMaterializer *Materializer = nullptr) {
245   return ValueMapper(VM, Flags, TypeMapper, Materializer).mapMDNode(*MD);
246 }
247 
248 /// Convert the instruction operands from referencing the current values into
249 /// those specified by VM.
250 ///
251 /// If \a RF_IgnoreMissingLocals is set and an operand can't be found via \a
252 /// MapValue(), use the old value.  Otherwise assert that this doesn't happen.
253 ///
254 /// Note that \a MapValue() only returns \c nullptr for SSA values missing from
255 /// \c VM.
256 inline void RemapInstruction(Instruction *I, ValueToValueMapTy &VM,
257                              RemapFlags Flags = RF_None,
258                              ValueMapTypeRemapper *TypeMapper = nullptr,
259                              ValueMaterializer *Materializer = nullptr) {
260   ValueMapper(VM, Flags, TypeMapper, Materializer).remapInstruction(*I);
261 }
262 
263 /// Remap the operands, metadata, arguments, and instructions of a function.
264 ///
265 /// Calls \a MapValue() on prefix data, prologue data, and personality
266 /// function; calls \a MapMetadata() on each attached MDNode; remaps the
267 /// argument types using the provided \c TypeMapper; and calls \a
268 /// RemapInstruction() on every instruction.
269 inline void RemapFunction(Function &F, ValueToValueMapTy &VM,
270                           RemapFlags Flags = RF_None,
271                           ValueMapTypeRemapper *TypeMapper = nullptr,
272                           ValueMaterializer *Materializer = nullptr) {
273   ValueMapper(VM, Flags, TypeMapper, Materializer).remapFunction(F);
274 }
275 
276 /// Version of MapValue with type safety for Constant.
277 inline Constant *MapValue(const Constant *V, ValueToValueMapTy &VM,
278                           RemapFlags Flags = RF_None,
279                           ValueMapTypeRemapper *TypeMapper = nullptr,
280                           ValueMaterializer *Materializer = nullptr) {
281   return ValueMapper(VM, Flags, TypeMapper, Materializer).mapConstant(*V);
282 }
283 
284 } // end namespace llvm
285 
286 #endif // LLVM_TRANSFORMS_UTILS_VALUEMAPPER_H
287