ValueMapper.h 12 KB

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