Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:44:45

0001 //===- ValueMapper.h - Remapping for constants and metadata -----*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 // This file defines the MapValue interface which is used by various parts of
0010 // the Transforms/Utils library to implement cloning and linking facilities.
0011 //
0012 //===----------------------------------------------------------------------===//
0013 
0014 #ifndef LLVM_TRANSFORMS_UTILS_VALUEMAPPER_H
0015 #define LLVM_TRANSFORMS_UTILS_VALUEMAPPER_H
0016 
0017 #include "llvm/ADT/ArrayRef.h"
0018 #include "llvm/ADT/SmallPtrSet.h"
0019 #include "llvm/ADT/simple_ilist.h"
0020 #include "llvm/IR/ValueHandle.h"
0021 #include "llvm/IR/ValueMap.h"
0022 
0023 namespace llvm {
0024 
0025 class Constant;
0026 class DIBuilder;
0027 class DbgRecord;
0028 class Function;
0029 class GlobalVariable;
0030 class Instruction;
0031 class MDNode;
0032 class Metadata;
0033 class Module;
0034 class Type;
0035 class Value;
0036 
0037 using ValueToValueMapTy = ValueMap<const Value *, WeakTrackingVH>;
0038 using DbgRecordIterator = simple_ilist<DbgRecord>::iterator;
0039 using MetadataSetTy = SmallPtrSet<const Metadata *, 16>;
0040 
0041 /// This is a class that can be implemented by clients to remap types when
0042 /// cloning constants and instructions.
0043 class ValueMapTypeRemapper {
0044   virtual void anchor(); // Out of line method.
0045 
0046 public:
0047   virtual ~ValueMapTypeRemapper() = default;
0048 
0049   /// The client should implement this method if they want to remap types while
0050   /// mapping values.
0051   virtual Type *remapType(Type *SrcTy) = 0;
0052 };
0053 
0054 /// This is a class that can be implemented by clients to materialize Values on
0055 /// demand.
0056 class ValueMaterializer {
0057   virtual void anchor(); // Out of line method.
0058 
0059 protected:
0060   ValueMaterializer() = default;
0061   ValueMaterializer(const ValueMaterializer &) = default;
0062   ValueMaterializer &operator=(const ValueMaterializer &) = default;
0063   ~ValueMaterializer() = default;
0064 
0065 public:
0066   /// This method can be implemented to generate a mapped Value on demand. For
0067   /// example, if linking lazily. Returns null if the value is not materialized.
0068   virtual Value *materialize(Value *V) = 0;
0069 };
0070 
0071 /// These are flags that the value mapping APIs allow.
0072 enum RemapFlags {
0073   RF_None = 0,
0074 
0075   /// If this flag is set, the remapper knows that only local values within a
0076   /// function (such as an instruction or argument) are mapped, not global
0077   /// values like functions and global metadata.
0078   RF_NoModuleLevelChanges = 1,
0079 
0080   /// If this flag is set, the remapper ignores missing function-local entries
0081   /// (Argument, Instruction, BasicBlock) that are not in the value map.  If it
0082   /// is unset, it aborts if an operand is asked to be remapped which doesn't
0083   /// exist in the mapping.
0084   ///
0085   /// There are no such assertions in MapValue(), whose results are almost
0086   /// unchanged by this flag.  This flag mainly changes the assertion behaviour
0087   /// in RemapInstruction().
0088   ///
0089   /// Since an Instruction's metadata operands (even that point to SSA values)
0090   /// aren't guaranteed to be dominated by their definitions, MapMetadata will
0091   /// return "!{}" instead of "null" for \a LocalAsMetadata instances whose SSA
0092   /// values are unmapped when this flag is set.  Otherwise, \a MapValue()
0093   /// completely ignores this flag.
0094   ///
0095   /// \a MapMetadata() always ignores this flag.
0096   RF_IgnoreMissingLocals = 2,
0097 
0098   /// Instruct the remapper to reuse and mutate distinct metadata (remapping
0099   /// them in place) instead of cloning remapped copies. This flag has no
0100   /// effect when RF_NoModuleLevelChanges, since that implies an identity
0101   /// mapping.
0102   RF_ReuseAndMutateDistinctMDs = 4,
0103 
0104   /// Any global values not in value map are mapped to null instead of mapping
0105   /// to self.  Illegal if RF_IgnoreMissingLocals is also set.
0106   RF_NullMapMissingGlobalValues = 8,
0107 };
0108 
0109 inline RemapFlags operator|(RemapFlags LHS, RemapFlags RHS) {
0110   return RemapFlags(unsigned(LHS) | unsigned(RHS));
0111 }
0112 
0113 /// Context for (re-)mapping values (and metadata).
0114 ///
0115 /// A shared context used for mapping and remapping of Value and Metadata
0116 /// instances using \a ValueToValueMapTy, \a RemapFlags, \a
0117 /// ValueMapTypeRemapper, \a ValueMaterializer, and \a IdentityMD.
0118 ///
0119 /// There are a number of top-level entry points:
0120 /// - \a mapValue() (and \a mapConstant());
0121 /// - \a mapMetadata() (and \a mapMDNode());
0122 /// - \a remapInstruction();
0123 /// - \a remapFunction(); and
0124 /// - \a remapGlobalObjectMetadata().
0125 ///
0126 /// The \a ValueMaterializer can be used as a callback, but cannot invoke any
0127 /// of these top-level functions recursively.  Instead, callbacks should use
0128 /// one of the following to schedule work lazily in the \a ValueMapper
0129 /// instance:
0130 /// - \a scheduleMapGlobalInitializer()
0131 /// - \a scheduleMapAppendingVariable()
0132 /// - \a scheduleMapGlobalAlias()
0133 /// - \a scheduleMapGlobalIFunc()
0134 /// - \a scheduleRemapFunction()
0135 ///
0136 /// Sometimes a callback needs a different mapping context.  Such a context can
0137 /// be registered using \a registerAlternateMappingContext(), which takes an
0138 /// alternate \a ValueToValueMapTy and \a ValueMaterializer and returns a ID to
0139 /// pass into the schedule*() functions.
0140 ///
0141 /// If an \a IdentityMD set is optionally provided, \a Metadata inside this set
0142 /// will be mapped onto itself in \a VM on first use.
0143 ///
0144 /// TODO: lib/Linker really doesn't need the \a ValueHandle in the \a
0145 /// ValueToValueMapTy.  We should template \a ValueMapper (and its
0146 /// implementation classes), and explicitly instantiate on two concrete
0147 /// instances of \a ValueMap (one as \a ValueToValueMap, and one with raw \a
0148 /// Value pointers).  It may be viable to do away with \a TrackingMDRef in the
0149 /// \a Metadata side map for the lib/Linker case as well, in which case we'll
0150 /// need a new template parameter on \a ValueMap.
0151 ///
0152 /// TODO: Update callers of \a RemapInstruction() and \a MapValue() (etc.) to
0153 /// use \a ValueMapper directly.
0154 class ValueMapper {
0155   void *pImpl;
0156 
0157 public:
0158   ValueMapper(ValueToValueMapTy &VM, RemapFlags Flags = RF_None,
0159               ValueMapTypeRemapper *TypeMapper = nullptr,
0160               ValueMaterializer *Materializer = nullptr,
0161               const MetadataSetTy *IdentityMD = nullptr);
0162   ValueMapper(ValueMapper &&) = delete;
0163   ValueMapper(const ValueMapper &) = delete;
0164   ValueMapper &operator=(ValueMapper &&) = delete;
0165   ValueMapper &operator=(const ValueMapper &) = delete;
0166   ~ValueMapper();
0167 
0168   /// Register an alternate mapping context.
0169   ///
0170   /// Returns a MappingContextID that can be used with the various schedule*()
0171   /// API to switch in a different value map on-the-fly.
0172   unsigned
0173   registerAlternateMappingContext(ValueToValueMapTy &VM,
0174                                   ValueMaterializer *Materializer = nullptr);
0175 
0176   /// Add to the current \a RemapFlags.
0177   ///
0178   /// \note Like the top-level mapping functions, \a addFlags() must be called
0179   /// at the top level, not during a callback in a \a ValueMaterializer.
0180   void addFlags(RemapFlags Flags);
0181 
0182   Metadata *mapMetadata(const Metadata &MD);
0183   MDNode *mapMDNode(const MDNode &N);
0184 
0185   Value *mapValue(const Value &V);
0186   Constant *mapConstant(const Constant &C);
0187 
0188   void remapInstruction(Instruction &I);
0189   void remapDbgRecord(Module *M, DbgRecord &V);
0190   void remapDbgRecordRange(Module *M, iterator_range<DbgRecordIterator> Range);
0191   void remapFunction(Function &F);
0192   void remapGlobalObjectMetadata(GlobalObject &GO);
0193 
0194   void scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init,
0195                                     unsigned MappingContextID = 0);
0196   void scheduleMapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
0197                                     bool IsOldCtorDtor,
0198                                     ArrayRef<Constant *> NewMembers,
0199                                     unsigned MappingContextID = 0);
0200   void scheduleMapGlobalAlias(GlobalAlias &GA, Constant &Aliasee,
0201                               unsigned MappingContextID = 0);
0202   void scheduleMapGlobalIFunc(GlobalIFunc &GI, Constant &Resolver,
0203                               unsigned MappingContextID = 0);
0204   void scheduleRemapFunction(Function &F, unsigned MappingContextID = 0);
0205 };
0206 
0207 /// Look up or compute a value in the value map.
0208 ///
0209 /// Return a mapped value for a function-local value (Argument, Instruction,
0210 /// BasicBlock), or compute and memoize a value for a Constant.
0211 ///
0212 ///  1. If \c V is in VM, return the result.
0213 ///  2. Else if \c V can be materialized with \c Materializer, do so, memoize
0214 ///     it in \c VM, and return it.
0215 ///  3. Else if \c V is a function-local value, return nullptr.
0216 ///  4. Else if \c V is a \a GlobalValue, return \c nullptr or \c V depending
0217 ///     on \a RF_NullMapMissingGlobalValues.
0218 ///  5. Else if \c V is a \a MetadataAsValue wrapping a LocalAsMetadata,
0219 ///     recurse on the local SSA value, and return nullptr or "metadata !{}" on
0220 ///     missing depending on RF_IgnoreMissingValues.
0221 ///  6. Else if \c V is a \a MetadataAsValue, rewrap the return of \a
0222 ///     MapMetadata().
0223 ///  7. Else, compute the equivalent constant, and return it.
0224 inline Value *MapValue(const Value *V, ValueToValueMapTy &VM,
0225                        RemapFlags Flags = RF_None,
0226                        ValueMapTypeRemapper *TypeMapper = nullptr,
0227                        ValueMaterializer *Materializer = nullptr,
0228                        const MetadataSetTy *IdentityMD = nullptr) {
0229   return ValueMapper(VM, Flags, TypeMapper, Materializer, IdentityMD)
0230       .mapValue(*V);
0231 }
0232 
0233 /// Lookup or compute a mapping for a piece of metadata.
0234 ///
0235 /// Compute and memoize a mapping for \c MD.
0236 ///
0237 ///  1. If \c MD is mapped, return it.
0238 ///  2. Else if \a RF_NoModuleLevelChanges or \c MD is an \a MDString, return
0239 ///     \c MD.
0240 ///  3. Else if \c MD is a \a ConstantAsMetadata, call \a MapValue() and
0241 ///     re-wrap its return (returning nullptr on nullptr).
0242 ///  4. Else if \c MD is in \c IdentityMD then add an identity mapping for it
0243 ///     and return it.
0244 ///  5. Else, \c MD is an \a MDNode.  These are remapped, along with their
0245 ///     transitive operands.  Distinct nodes are duplicated or moved depending
0246 ///     on \a RF_MoveDistinctNodes.  Uniqued nodes are remapped like constants.
0247 ///
0248 /// \note \a LocalAsMetadata is completely unsupported by \a MapMetadata.
0249 /// Instead, use \a MapValue() with its wrapping \a MetadataAsValue instance.
0250 inline Metadata *MapMetadata(const Metadata *MD, ValueToValueMapTy &VM,
0251                              RemapFlags Flags = RF_None,
0252                              ValueMapTypeRemapper *TypeMapper = nullptr,
0253                              ValueMaterializer *Materializer = nullptr,
0254                              const MetadataSetTy *IdentityMD = nullptr) {
0255   return ValueMapper(VM, Flags, TypeMapper, Materializer, IdentityMD)
0256       .mapMetadata(*MD);
0257 }
0258 
0259 /// Version of MapMetadata with type safety for MDNode.
0260 inline MDNode *MapMetadata(const MDNode *MD, ValueToValueMapTy &VM,
0261                            RemapFlags Flags = RF_None,
0262                            ValueMapTypeRemapper *TypeMapper = nullptr,
0263                            ValueMaterializer *Materializer = nullptr,
0264                            const MetadataSetTy *IdentityMD = nullptr) {
0265   return ValueMapper(VM, Flags, TypeMapper, Materializer, IdentityMD)
0266       .mapMDNode(*MD);
0267 }
0268 
0269 /// Convert the instruction operands from referencing the current values into
0270 /// those specified by VM.
0271 ///
0272 /// If \a RF_IgnoreMissingLocals is set and an operand can't be found via \a
0273 /// MapValue(), use the old value.  Otherwise assert that this doesn't happen.
0274 ///
0275 /// Note that \a MapValue() only returns \c nullptr for SSA values missing from
0276 /// \c VM.
0277 inline void RemapInstruction(Instruction *I, ValueToValueMapTy &VM,
0278                              RemapFlags Flags = RF_None,
0279                              ValueMapTypeRemapper *TypeMapper = nullptr,
0280                              ValueMaterializer *Materializer = nullptr,
0281                              const MetadataSetTy *IdentityMD = nullptr) {
0282   ValueMapper(VM, Flags, TypeMapper, Materializer, IdentityMD)
0283       .remapInstruction(*I);
0284 }
0285 
0286 /// Remap the Values used in the DbgRecord \a DR using the value map \a
0287 /// VM.
0288 inline void RemapDbgRecord(Module *M, DbgRecord *DR, ValueToValueMapTy &VM,
0289                            RemapFlags Flags = RF_None,
0290                            ValueMapTypeRemapper *TypeMapper = nullptr,
0291                            ValueMaterializer *Materializer = nullptr,
0292                            const MetadataSetTy *IdentityMD = nullptr) {
0293   ValueMapper(VM, Flags, TypeMapper, Materializer, IdentityMD)
0294       .remapDbgRecord(M, *DR);
0295 }
0296 
0297 /// Remap the Values used in the DbgRecords \a Range using the value map \a
0298 /// VM.
0299 inline void RemapDbgRecordRange(Module *M,
0300                                 iterator_range<DbgRecordIterator> Range,
0301                                 ValueToValueMapTy &VM,
0302                                 RemapFlags Flags = RF_None,
0303                                 ValueMapTypeRemapper *TypeMapper = nullptr,
0304                                 ValueMaterializer *Materializer = nullptr,
0305                                 const MetadataSetTy *IdentityMD = nullptr) {
0306   ValueMapper(VM, Flags, TypeMapper, Materializer, IdentityMD)
0307       .remapDbgRecordRange(M, Range);
0308 }
0309 
0310 /// Remap the operands, metadata, arguments, and instructions of a function.
0311 ///
0312 /// Calls \a MapValue() on prefix data, prologue data, and personality
0313 /// function; calls \a MapMetadata() on each attached MDNode; remaps the
0314 /// argument types using the provided \c TypeMapper; and calls \a
0315 /// RemapInstruction() on every instruction.
0316 inline void RemapFunction(Function &F, ValueToValueMapTy &VM,
0317                           RemapFlags Flags = RF_None,
0318                           ValueMapTypeRemapper *TypeMapper = nullptr,
0319                           ValueMaterializer *Materializer = nullptr,
0320                           const MetadataSetTy *IdentityMD = nullptr) {
0321   ValueMapper(VM, Flags, TypeMapper, Materializer, IdentityMD).remapFunction(F);
0322 }
0323 
0324 /// Version of MapValue with type safety for Constant.
0325 inline Constant *MapValue(const Constant *V, ValueToValueMapTy &VM,
0326                           RemapFlags Flags = RF_None,
0327                           ValueMapTypeRemapper *TypeMapper = nullptr,
0328                           ValueMaterializer *Materializer = nullptr,
0329                           const MetadataSetTy *IdentityMD = nullptr) {
0330   return ValueMapper(VM, Flags, TypeMapper, Materializer, IdentityMD)
0331       .mapConstant(*V);
0332 }
0333 
0334 } // end namespace llvm
0335 
0336 #endif // LLVM_TRANSFORMS_UTILS_VALUEMAPPER_H