blob: ae839bd3a3d365416b5d9b4242647fa33412babe [file] [log] [blame]
Chris Lattner1c733cb2002-11-20 20:47:41 +00001//===- ValueMapper.cpp - Interface shared by lib/Transforms/Utils ---------===//
Misha Brukman263a6ea2005-04-21 23:48:37 +00002//
Chandler Carruthca6d7192019-01-19 08:50:56 +00003// 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
Misha Brukman263a6ea2005-04-21 23:48:37 +00006//
John Criswell287baed2003-10-20 19:43:21 +00007//===----------------------------------------------------------------------===//
Chris Lattner1c733cb2002-11-20 20:47:41 +00008//
9// This file defines the MapValue function, which is shared by various parts of
10// the lib/Transforms/Utils library.
11//
12//===----------------------------------------------------------------------===//
13
Dan Gohman0adabad2010-08-24 18:50:07 +000014#include "llvm/Transforms/Utils/ValueMapper.h"
Eugene Zelenkobd1fb282017-10-26 00:55:39 +000015#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/DenseMap.h"
Duncan P. N. Exon Smithc26c0122016-04-17 19:40:20 +000017#include "llvm/ADT/DenseSet.h"
Eugene Zelenkobd1fb282017-10-26 00:55:39 +000018#include "llvm/ADT/None.h"
19#include "llvm/ADT/Optional.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/IR/Argument.h"
23#include "llvm/IR/BasicBlock.h"
Eugene Zelenkobd1fb282017-10-26 00:55:39 +000024#include "llvm/IR/Constant.h"
Chandler Carruth1d569b62013-01-02 11:36:10 +000025#include "llvm/IR/Constants.h"
Teresa Johnson88e10352018-01-30 20:16:32 +000026#include "llvm/IR/DebugInfoMetadata.h"
Eugene Zelenkobd1fb282017-10-26 00:55:39 +000027#include "llvm/IR/DerivedTypes.h"
Chandler Carruth1d569b62013-01-02 11:36:10 +000028#include "llvm/IR/Function.h"
Peter Collingbourne00e6c2f2019-08-08 22:09:18 +000029#include "llvm/IR/GlobalIndirectSymbol.h"
Ruiling Songae556892021-02-01 17:24:12 +080030#include "llvm/IR/GlobalObject.h"
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +000031#include "llvm/IR/GlobalVariable.h"
Chandler Carruth1d569b62013-01-02 11:36:10 +000032#include "llvm/IR/InlineAsm.h"
Eugene Zelenkobd1fb282017-10-26 00:55:39 +000033#include "llvm/IR/Instruction.h"
Chandler Carruth1d569b62013-01-02 11:36:10 +000034#include "llvm/IR/Instructions.h"
35#include "llvm/IR/Metadata.h"
David Blaikieeb1e1dd2015-08-21 20:16:51 +000036#include "llvm/IR/Operator.h"
Eugene Zelenkobd1fb282017-10-26 00:55:39 +000037#include "llvm/IR/Type.h"
38#include "llvm/IR/Value.h"
39#include "llvm/Support/Casting.h"
Ruiling Songae556892021-02-01 17:24:12 +080040#include "llvm/Support/Debug.h"
Eugene Zelenkobd1fb282017-10-26 00:55:39 +000041#include <cassert>
42#include <limits>
43#include <memory>
44#include <utility>
45
Chris Lattner48f332a2004-01-09 06:12:26 +000046using namespace llvm;
Chris Lattner1c733cb2002-11-20 20:47:41 +000047
Ruiling Songae556892021-02-01 17:24:12 +080048#define DEBUG_TYPE "value-mapper"
49
Chris Lattner212157c2011-07-09 17:41:24 +000050// Out of line method to get vtable etc for class.
Craig Topperff452ce2012-09-26 06:36:36 +000051void ValueMapTypeRemapper::anchor() {}
James Molloy0aec9ae2013-05-28 15:17:05 +000052void ValueMaterializer::anchor() {}
Chris Lattner212157c2011-07-09 17:41:24 +000053
Duncan P. N. Exon Smith0a73e9e2016-04-03 19:06:24 +000054namespace {
55
Duncan P. N. Exon Smith1c1f1172016-04-03 20:17:45 +000056/// A basic block used in a BlockAddress whose function body is not yet
57/// materialized.
58struct DelayedBasicBlock {
59 BasicBlock *OldBB;
60 std::unique_ptr<BasicBlock> TempBB;
Duncan P. N. Exon Smith9ed2c6c2016-04-03 20:42:21 +000061
Duncan P. N. Exon Smith1c1f1172016-04-03 20:17:45 +000062 DelayedBasicBlock(const BlockAddress &Old)
63 : OldBB(Old.getBasicBlock()),
64 TempBB(BasicBlock::Create(Old.getContext())) {}
65};
66
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +000067struct WorklistEntry {
68 enum EntryKind {
69 MapGlobalInit,
70 MapAppendingVar,
Peter Collingbourne00e6c2f2019-08-08 22:09:18 +000071 MapGlobalIndirectSymbol,
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +000072 RemapFunction
73 };
74 struct GVInitTy {
75 GlobalVariable *GV;
76 Constant *Init;
77 };
78 struct AppendingGVTy {
79 GlobalVariable *GV;
80 Constant *InitPrefix;
81 };
Peter Collingbourne00e6c2f2019-08-08 22:09:18 +000082 struct GlobalIndirectSymbolTy {
83 GlobalIndirectSymbol *GIS;
84 Constant *Target;
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +000085 };
86
87 unsigned Kind : 2;
88 unsigned MCID : 29;
89 unsigned AppendingGVIsOldCtorDtor : 1;
90 unsigned AppendingGVNumNewMembers;
91 union {
92 GVInitTy GVInit;
93 AppendingGVTy AppendingGV;
Peter Collingbourne00e6c2f2019-08-08 22:09:18 +000094 GlobalIndirectSymbolTy GlobalIndirectSymbol;
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +000095 Function *RemapF;
96 } Data;
97};
98
99struct MappingContext {
100 ValueToValueMapTy *VM;
101 ValueMaterializer *Materializer = nullptr;
102
103 /// Construct a MappingContext with a value map and materializer.
104 explicit MappingContext(ValueToValueMapTy &VM,
105 ValueMaterializer *Materializer = nullptr)
106 : VM(&VM), Materializer(Materializer) {}
107};
108
Duncan P. N. Exon Smith0a73e9e2016-04-03 19:06:24 +0000109class Mapper {
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000110 friend class MDNodeMapper;
111
Duncan P. N. Exon Smithc26c0122016-04-17 19:40:20 +0000112#ifndef NDEBUG
113 DenseSet<GlobalValue *> AlreadyScheduled;
114#endif
115
Duncan P. N. Exon Smith0a73e9e2016-04-03 19:06:24 +0000116 RemapFlags Flags;
117 ValueMapTypeRemapper *TypeMapper;
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +0000118 unsigned CurrentMCID = 0;
119 SmallVector<MappingContext, 2> MCs;
120 SmallVector<WorklistEntry, 4> Worklist;
Duncan P. N. Exon Smith1c1f1172016-04-03 20:17:45 +0000121 SmallVector<DelayedBasicBlock, 1> DelayedBBs;
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +0000122 SmallVector<Constant *, 16> AppendingInits;
Duncan P. N. Exon Smith0a73e9e2016-04-03 19:06:24 +0000123
124public:
125 Mapper(ValueToValueMapTy &VM, RemapFlags Flags,
126 ValueMapTypeRemapper *TypeMapper, ValueMaterializer *Materializer)
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +0000127 : Flags(Flags), TypeMapper(TypeMapper),
128 MCs(1, MappingContext(VM, Materializer)) {}
Duncan P. N. Exon Smith0a73e9e2016-04-03 19:06:24 +0000129
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +0000130 /// ValueMapper should explicitly call \a flush() before destruction.
131 ~Mapper() { assert(!hasWorkToDo() && "Expected to be flushed"); }
132
133 bool hasWorkToDo() const { return !Worklist.empty(); }
134
135 unsigned
136 registerAlternateMappingContext(ValueToValueMapTy &VM,
137 ValueMaterializer *Materializer = nullptr) {
138 MCs.push_back(MappingContext(VM, Materializer));
139 return MCs.size() - 1;
140 }
141
142 void addFlags(RemapFlags Flags);
Duncan P. N. Exon Smith0a73e9e2016-04-03 19:06:24 +0000143
Evgeniy Stepanov31818532017-05-04 23:29:39 +0000144 void remapGlobalObjectMetadata(GlobalObject &GO);
145
Duncan P. N. Exon Smith0a73e9e2016-04-03 19:06:24 +0000146 Value *mapValue(const Value *V);
Duncan P. N. Exon Smithba441152016-04-08 19:09:34 +0000147 void remapInstruction(Instruction *I);
Duncan P. N. Exon Smith24a7e4e2016-04-08 19:26:32 +0000148 void remapFunction(Function &F);
Duncan P. N. Exon Smith0a73e9e2016-04-03 19:06:24 +0000149
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +0000150 Constant *mapConstant(const Constant *C) {
151 return cast_or_null<Constant>(mapValue(C));
152 }
153
Duncan P. N. Exon Smith0a73e9e2016-04-03 19:06:24 +0000154 /// Map metadata.
155 ///
156 /// Find the mapping for MD. Guarantees that the return will be resolved
157 /// (not an MDNode, or MDNode::isResolved() returns true).
158 Metadata *mapMetadata(const Metadata *MD);
159
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +0000160 void scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init,
161 unsigned MCID);
162 void scheduleMapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
163 bool IsOldCtorDtor,
164 ArrayRef<Constant *> NewMembers,
165 unsigned MCID);
Peter Collingbourne00e6c2f2019-08-08 22:09:18 +0000166 void scheduleMapGlobalIndirectSymbol(GlobalIndirectSymbol &GIS, Constant &Target,
167 unsigned MCID);
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +0000168 void scheduleRemapFunction(Function &F, unsigned MCID);
169
170 void flush();
171
Duncan P. N. Exon Smith0a73e9e2016-04-03 19:06:24 +0000172private:
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +0000173 void mapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
174 bool IsOldCtorDtor,
175 ArrayRef<Constant *> NewMembers);
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +0000176
177 ValueToValueMapTy &getVM() { return *MCs[CurrentMCID].VM; }
178 ValueMaterializer *getMaterializer() { return MCs[CurrentMCID].Materializer; }
Duncan P. N. Exon Smithbaaae782016-04-15 23:18:43 +0000179
Duncan P. N. Exon Smith1c1f1172016-04-03 20:17:45 +0000180 Value *mapBlockAddress(const BlockAddress &BA);
181
Duncan P. N. Exon Smithdf941122016-04-03 19:31:01 +0000182 /// Map metadata that doesn't require visiting operands.
183 Optional<Metadata *> mapSimpleMetadata(const Metadata *MD);
184
Duncan P. N. Exon Smith0a73e9e2016-04-03 19:06:24 +0000185 Metadata *mapToMetadata(const Metadata *Key, Metadata *Val);
186 Metadata *mapToSelf(const Metadata *MD);
187};
188
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000189class MDNodeMapper {
190 Mapper &M;
191
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000192 /// Data about a node in \a UniquedGraph.
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000193 struct Data {
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000194 bool HasChanged = false;
Eugene Zelenkobd1fb282017-10-26 00:55:39 +0000195 unsigned ID = std::numeric_limits<unsigned>::max();
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000196 TempMDNode Placeholder;
197 };
198
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000199 /// A graph of uniqued nodes.
200 struct UniquedGraph {
201 SmallDenseMap<const Metadata *, Data, 32> Info; // Node properties.
202 SmallVector<MDNode *, 16> POT; // Post-order traversal.
203
204 /// Propagate changed operands through the post-order traversal.
205 ///
206 /// Iteratively update \a Data::HasChanged for each node based on \a
207 /// Data::HasChanged of its operands, until fixed point.
208 void propagateChanges();
209
210 /// Get a forward reference to a node to use as an operand.
211 Metadata &getFwdReference(MDNode &Op);
212 };
213
214 /// Worklist of distinct nodes whose operands need to be remapped.
215 SmallVector<MDNode *, 16> DistinctWorklist;
216
217 // Storage for a UniquedGraph.
218 SmallDenseMap<const Metadata *, Data, 32> InfoStorage;
219 SmallVector<MDNode *, 16> POTStorage;
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000220
221public:
222 MDNodeMapper(Mapper &M) : M(M) {}
223
224 /// Map a metadata node (and its transitive operands).
225 ///
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000226 /// Map all the (unmapped) nodes in the subgraph under \c N. The iterative
227 /// algorithm handles distinct nodes and uniqued node subgraphs using
228 /// different strategies.
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000229 ///
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000230 /// Distinct nodes are immediately mapped and added to \a DistinctWorklist
231 /// using \a mapDistinctNode(). Their mapping can always be computed
232 /// immediately without visiting operands, even if their operands change.
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000233 ///
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000234 /// The mapping for uniqued nodes depends on whether their operands change.
235 /// \a mapTopLevelUniquedNode() traverses the transitive uniqued subgraph of
236 /// a node to calculate uniqued node mappings in bulk. Distinct leafs are
237 /// added to \a DistinctWorklist with \a mapDistinctNode().
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000238 ///
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000239 /// After mapping \c N itself, this function remaps the operands of the
240 /// distinct nodes in \a DistinctWorklist until the entire subgraph under \c
241 /// N has been mapped.
242 Metadata *map(const MDNode &N);
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000243
244private:
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000245 /// Map a top-level uniqued node and the uniqued subgraph underneath it.
246 ///
247 /// This builds up a post-order traversal of the (unmapped) uniqued subgraph
248 /// underneath \c FirstN and calculates the nodes' mapping. Each node uses
249 /// the identity mapping (\a Mapper::mapToSelf()) as long as all of its
250 /// operands uses the identity mapping.
251 ///
252 /// The algorithm works as follows:
253 ///
254 /// 1. \a createPOT(): traverse the uniqued subgraph under \c FirstN and
255 /// save the post-order traversal in the given \a UniquedGraph, tracking
256 /// nodes' operands change.
257 ///
258 /// 2. \a UniquedGraph::propagateChanges(): propagate changed operands
259 /// through the \a UniquedGraph until fixed point, following the rule
260 /// that if a node changes, any node that references must also change.
261 ///
262 /// 3. \a mapNodesInPOT(): map the uniqued nodes, creating new uniqued nodes
263 /// (referencing new operands) where necessary.
264 Metadata *mapTopLevelUniquedNode(const MDNode &FirstN);
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000265
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000266 /// Try to map the operand of an \a MDNode.
267 ///
268 /// If \c Op is already mapped, return the mapping. If it's not an \a
269 /// MDNode, compute and return the mapping. If it's a distinct \a MDNode,
270 /// return the result of \a mapDistinctNode().
271 ///
272 /// \return None if \c Op is an unmapped uniqued \a MDNode.
273 /// \post getMappedOp(Op) only returns None if this returns None.
274 Optional<Metadata *> tryToMapOperand(const Metadata *Op);
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000275
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000276 /// Map a distinct node.
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000277 ///
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000278 /// Return the mapping for the distinct node \c N, saving the result in \a
279 /// DistinctWorklist for later remapping.
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000280 ///
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000281 /// \pre \c N is not yet mapped.
282 /// \pre \c N.isDistinct().
283 MDNode *mapDistinctNode(const MDNode &N);
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000284
285 /// Get a previously mapped node.
286 Optional<Metadata *> getMappedOp(const Metadata *Op) const;
287
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000288 /// Create a post-order traversal of an unmapped uniqued node subgraph.
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000289 ///
290 /// This traverses the metadata graph deeply enough to map \c FirstN. It
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000291 /// uses \a tryToMapOperand() (via \a Mapper::mapSimplifiedNode()), so any
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000292 /// metadata that has already been mapped will not be part of the POT.
293 ///
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000294 /// Each node that has a changed operand from outside the graph (e.g., a
295 /// distinct node, an already-mapped uniqued node, or \a ConstantAsMetadata)
296 /// is marked with \a Data::HasChanged.
297 ///
298 /// \return \c true if any nodes in \c G have \a Data::HasChanged.
299 /// \post \c G.POT is a post-order traversal ending with \c FirstN.
300 /// \post \a Data::hasChanged in \c G.Info indicates whether any node needs
301 /// to change because of operands outside the graph.
302 bool createPOT(UniquedGraph &G, const MDNode &FirstN);
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000303
Duncan P. N. Exon Smithf6a0a402016-04-22 02:33:06 +0000304 /// Visit the operands of a uniqued node in the POT.
Duncan P. N. Exon Smithfec75e12016-04-21 02:34:36 +0000305 ///
Duncan P. N. Exon Smithf6a0a402016-04-22 02:33:06 +0000306 /// Visit the operands in the range from \c I to \c E, returning the first
307 /// uniqued node we find that isn't yet in \c G. \c I is always advanced to
308 /// where to continue the loop through the operands.
309 ///
310 /// This sets \c HasChanged if any of the visited operands change.
311 MDNode *visitOperands(UniquedGraph &G, MDNode::op_iterator &I,
312 MDNode::op_iterator E, bool &HasChanged);
Duncan P. N. Exon Smithfec75e12016-04-21 02:34:36 +0000313
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000314 /// Map all the nodes in the given uniqued graph.
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000315 ///
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000316 /// This visits all the nodes in \c G in post-order, using the identity
317 /// mapping or creating a new node depending on \a Data::HasChanged.
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000318 ///
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000319 /// \pre \a getMappedOp() returns None for nodes in \c G, but not for any of
320 /// their operands outside of \c G.
321 /// \pre \a Data::HasChanged is true for a node in \c G iff any of its
322 /// operands have changed.
323 /// \post \a getMappedOp() returns the mapped node for every node in \c G.
324 void mapNodesInPOT(UniquedGraph &G);
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000325
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000326 /// Remap a node's operands using the given functor.
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000327 ///
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000328 /// Iterate through the operands of \c N and update them in place using \c
329 /// mapOperand.
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000330 ///
331 /// \pre N.isDistinct() or N.isTemporary().
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000332 template <class OperandMapper>
333 void remapOperands(MDNode &N, OperandMapper mapOperand);
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000334};
335
Eugene Zelenkobd1fb282017-10-26 00:55:39 +0000336} // end anonymous namespace
Duncan P. N. Exon Smith0a73e9e2016-04-03 19:06:24 +0000337
Duncan P. N. Exon Smith0a73e9e2016-04-03 19:06:24 +0000338Value *Mapper::mapValue(const Value *V) {
Duncan P. N. Exon Smithbaaae782016-04-15 23:18:43 +0000339 ValueToValueMapTy::iterator I = getVM().find(V);
340
Chris Lattnerb76d75c2011-01-08 08:15:20 +0000341 // If the value already exists in the map, use it.
Duncan P. N. Exon Smith17a6eb32016-04-17 18:53:24 +0000342 if (I != getVM().end()) {
343 assert(I->second && "Unexpected null mapping");
Duncan P. N. Exon Smithbaaae782016-04-15 23:18:43 +0000344 return I->second;
Duncan P. N. Exon Smith17a6eb32016-04-17 18:53:24 +0000345 }
Duncan P. N. Exon Smithbaaae782016-04-15 23:18:43 +0000346
James Molloy0aec9ae2013-05-28 15:17:05 +0000347 // If we have a materializer and it can materialize a value, use that.
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +0000348 if (auto *Materializer = getMaterializer()) {
Mehdi Amini33d8b9f2016-05-25 21:03:21 +0000349 if (Value *NewV = Materializer->materialize(const_cast<Value *>(V))) {
350 getVM()[V] = NewV;
351 return NewV;
Rafael Espindola5c624442015-11-27 20:28:19 +0000352 }
James Molloy0aec9ae2013-05-28 15:17:05 +0000353 }
354
Dan Gohmanf6c8a542010-08-26 15:41:53 +0000355 // Global values do not need to be seeded into the VM if they
356 // are using the identity mapping.
Teresa Johnson39065092015-11-15 14:50:14 +0000357 if (isa<GlobalValue>(V)) {
Duncan P. N. Exon Smithbb8d88a2016-04-07 01:22:45 +0000358 if (Flags & RF_NullMapMissingGlobalValues)
Teresa Johnson39065092015-11-15 14:50:14 +0000359 return nullptr;
Duncan P. N. Exon Smithbaaae782016-04-15 23:18:43 +0000360 return getVM()[V] = const_cast<Value *>(V);
Teresa Johnson39065092015-11-15 14:50:14 +0000361 }
362
Chris Lattner9b3692c2011-07-15 23:18:40 +0000363 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
364 // Inline asm may need *type* remapping.
365 FunctionType *NewTy = IA->getFunctionType();
366 if (TypeMapper) {
367 NewTy = cast<FunctionType>(TypeMapper->remapType(NewTy));
368
369 if (NewTy != IA->getFunctionType())
370 V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),
Craig Topper3caba292020-05-17 14:57:04 -0700371 IA->hasSideEffects(), IA->isAlignStack(),
372 IA->getDialect());
Chris Lattner9b3692c2011-07-15 23:18:40 +0000373 }
Duncan P. N. Exon Smithbaaae782016-04-15 23:18:43 +0000374
375 return getVM()[V] = const_cast<Value *>(V);
Chris Lattner9b3692c2011-07-15 23:18:40 +0000376 }
Chris Lattner92711102003-10-06 15:23:43 +0000377
Duncan P. N. Exon Smith373db622014-12-09 18:38:53 +0000378 if (const auto *MDV = dyn_cast<MetadataAsValue>(V)) {
379 const Metadata *MD = MDV->getMetadata();
Duncan P. N. Exon Smitha27492c2016-04-08 03:13:22 +0000380
381 if (auto *LAM = dyn_cast<LocalAsMetadata>(MD)) {
382 // Look through to grab the local value.
383 if (Value *LV = mapValue(LAM->getValue())) {
384 if (V == LAM->getValue())
385 return const_cast<Value *>(V);
386 return MetadataAsValue::get(V->getContext(), ValueAsMetadata::get(LV));
387 }
388
389 // FIXME: always return nullptr once Verifier::verifyDominatesUse()
390 // ensures metadata operands only reference defined SSA values.
391 return (Flags & RF_IgnoreMissingLocals)
392 ? nullptr
393 : MetadataAsValue::get(V->getContext(),
394 MDTuple::get(V->getContext(), None));
395 }
gbtozersd1073d32020-09-30 16:29:53 +0100396 if (auto *AL = dyn_cast<DIArgList>(MD)) {
397 SmallVector<ValueAsMetadata *, 4> MappedArgs;
398 for (auto *VAM : AL->getArgs()) {
399 // Map both Local and Constant VAMs here; they will both ultimately
400 // be mapped via mapValue (apart from constants when we have no
401 // module level changes, which have an identity mapping).
402 if ((Flags & RF_NoModuleLevelChanges) && isa<ConstantAsMetadata>(VAM)) {
403 MappedArgs.push_back(VAM);
404 } else if (Value *LV = mapValue(VAM->getValue())) {
405 MappedArgs.push_back(
406 LV == VAM->getValue() ? VAM : ValueAsMetadata::get(LV));
407 } else {
408 // If we cannot map the value, set the argument as undef.
409 MappedArgs.push_back(ValueAsMetadata::get(
410 UndefValue::get(VAM->getValue()->getType())));
411 }
412 }
413 return MetadataAsValue::get(V->getContext(),
414 DIArgList::get(V->getContext(), MappedArgs));
415 }
Duncan P. N. Exon Smitha27492c2016-04-08 03:13:22 +0000416
Chris Lattnerb76d75c2011-01-08 08:15:20 +0000417 // If this is a module-level metadata and we know that nothing at the module
418 // level is changing, then use an identity mapping.
Duncan P. N. Exon Smitha27492c2016-04-08 03:13:22 +0000419 if (Flags & RF_NoModuleLevelChanges)
Duncan P. N. Exon Smithbaaae782016-04-15 23:18:43 +0000420 return getVM()[V] = const_cast<Value *>(V);
Dan Gohmanf6c8a542010-08-26 15:41:53 +0000421
Duncan P. N. Exon Smitha27492c2016-04-08 03:13:22 +0000422 // Map the metadata and turn it into a value.
Duncan P. N. Exon Smith0a73e9e2016-04-03 19:06:24 +0000423 auto *MappedMD = mapMetadata(MD);
Duncan P. N. Exon Smitha27492c2016-04-08 03:13:22 +0000424 if (MD == MappedMD)
Duncan P. N. Exon Smithbaaae782016-04-15 23:18:43 +0000425 return getVM()[V] = const_cast<Value *>(V);
426 return getVM()[V] = MetadataAsValue::get(V->getContext(), MappedMD);
Victor Hernandezecf675d2010-01-20 05:49:59 +0000427 }
428
Chris Lattnerb76d75c2011-01-08 08:15:20 +0000429 // Okay, this either must be a constant (which may or may not be mappable) or
430 // is something that is not in the mapping table.
Chris Lattnerdcf54652009-10-29 00:28:30 +0000431 Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
Craig Toppereb4c76a2014-04-25 05:29:35 +0000432 if (!C)
433 return nullptr;
Duncan P. N. Exon Smith1c1f1172016-04-03 20:17:45 +0000434
435 if (BlockAddress *BA = dyn_cast<BlockAddress>(C))
436 return mapBlockAddress(*BA);
437
Leonard Chan7c712b92021-03-05 16:11:01 -0800438 if (const auto *E = dyn_cast<DSOLocalEquivalent>(C)) {
439 auto *Val = mapValue(E->getGlobalValue());
440 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
441 if (GV)
442 return getVM()[E] = DSOLocalEquivalent::get(GV);
443
444 auto *Func = cast<Function>(Val->stripPointerCastsAndAliases());
445 Type *NewTy = E->getType();
446 if (TypeMapper)
447 NewTy = TypeMapper->remapType(NewTy);
448 return getVM()[E] = llvm::ConstantExpr::getBitCast(
449 DSOLocalEquivalent::get(Func), NewTy);
450 }
451
Mehdi Amini78fe0b72016-05-28 17:26:03 +0000452 auto mapValueOrNull = [this](Value *V) {
453 auto Mapped = mapValue(V);
454 assert((Mapped || (Flags & RF_NullMapMissingGlobalValues)) &&
455 "Unexpected null mapping for constant operand without "
456 "NullMapMissingGlobalValues flag");
457 return Mapped;
458 };
459
Chris Lattner212157c2011-07-09 17:41:24 +0000460 // Otherwise, we have some other constant to remap. Start by checking to see
461 // if all operands have an identity remapping.
462 unsigned OpNo = 0, NumOperands = C->getNumOperands();
Craig Toppereb4c76a2014-04-25 05:29:35 +0000463 Value *Mapped = nullptr;
Chris Lattner212157c2011-07-09 17:41:24 +0000464 for (; OpNo != NumOperands; ++OpNo) {
465 Value *Op = C->getOperand(OpNo);
Mehdi Amini78fe0b72016-05-28 17:26:03 +0000466 Mapped = mapValueOrNull(Op);
467 if (!Mapped)
468 return nullptr;
Mehdi Amini9f0c6ee2016-05-27 00:32:12 +0000469 if (Mapped != Op)
470 break;
Chris Lattnerdcf54652009-10-29 00:28:30 +0000471 }
Junmo Parkb683de82016-05-08 23:22:58 +0000472
Chris Lattner212157c2011-07-09 17:41:24 +0000473 // See if the type mapper wants to remap the type as well.
474 Type *NewTy = C->getType();
475 if (TypeMapper)
476 NewTy = TypeMapper->remapType(NewTy);
Chris Lattnerb76d75c2011-01-08 08:15:20 +0000477
Chris Lattner212157c2011-07-09 17:41:24 +0000478 // If the result type and all operands match up, then just insert an identity
479 // mapping.
480 if (OpNo == NumOperands && NewTy == C->getType())
Duncan P. N. Exon Smithbaaae782016-04-15 23:18:43 +0000481 return getVM()[V] = C;
482
Chris Lattner212157c2011-07-09 17:41:24 +0000483 // Okay, we need to create a new constant. We've already processed some or
484 // all of the operands, set them all up now.
485 SmallVector<Constant*, 8> Ops;
486 Ops.reserve(NumOperands);
487 for (unsigned j = 0; j != OpNo; ++j)
488 Ops.push_back(cast<Constant>(C->getOperand(j)));
Junmo Parkb683de82016-05-08 23:22:58 +0000489
Chris Lattner212157c2011-07-09 17:41:24 +0000490 // If one of the operands mismatch, push it and the other mapped operands.
491 if (OpNo != NumOperands) {
492 Ops.push_back(cast<Constant>(Mapped));
Junmo Parkb683de82016-05-08 23:22:58 +0000493
Chris Lattner212157c2011-07-09 17:41:24 +0000494 // Map the rest of the operands that aren't processed yet.
Mehdi Amini78fe0b72016-05-28 17:26:03 +0000495 for (++OpNo; OpNo != NumOperands; ++OpNo) {
496 Mapped = mapValueOrNull(C->getOperand(OpNo));
497 if (!Mapped)
498 return nullptr;
499 Ops.push_back(cast<Constant>(Mapped));
500 }
Chris Lattner212157c2011-07-09 17:41:24 +0000501 }
David Blaikieeb1e1dd2015-08-21 20:16:51 +0000502 Type *NewSrcTy = nullptr;
503 if (TypeMapper)
504 if (auto *GEPO = dyn_cast<GEPOperator>(C))
505 NewSrcTy = TypeMapper->remapType(GEPO->getSourceElementType());
506
Chris Lattner212157c2011-07-09 17:41:24 +0000507 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Duncan P. N. Exon Smithbaaae782016-04-15 23:18:43 +0000508 return getVM()[V] = CE->getWithOperands(Ops, NewTy, false, NewSrcTy);
Chris Lattner212157c2011-07-09 17:41:24 +0000509 if (isa<ConstantArray>(C))
Duncan P. N. Exon Smithbaaae782016-04-15 23:18:43 +0000510 return getVM()[V] = ConstantArray::get(cast<ArrayType>(NewTy), Ops);
Chris Lattner212157c2011-07-09 17:41:24 +0000511 if (isa<ConstantStruct>(C))
Duncan P. N. Exon Smithbaaae782016-04-15 23:18:43 +0000512 return getVM()[V] = ConstantStruct::get(cast<StructType>(NewTy), Ops);
Chris Lattner212157c2011-07-09 17:41:24 +0000513 if (isa<ConstantVector>(C))
Duncan P. N. Exon Smithbaaae782016-04-15 23:18:43 +0000514 return getVM()[V] = ConstantVector::get(Ops);
Chris Lattner212157c2011-07-09 17:41:24 +0000515 // If this is a no-operand constant, it must be because the type was remapped.
516 if (isa<UndefValue>(C))
Duncan P. N. Exon Smithbaaae782016-04-15 23:18:43 +0000517 return getVM()[V] = UndefValue::get(NewTy);
Chris Lattner212157c2011-07-09 17:41:24 +0000518 if (isa<ConstantAggregateZero>(C))
Duncan P. N. Exon Smithbaaae782016-04-15 23:18:43 +0000519 return getVM()[V] = ConstantAggregateZero::get(NewTy);
Chris Lattner212157c2011-07-09 17:41:24 +0000520 assert(isa<ConstantPointerNull>(C));
Duncan P. N. Exon Smithbaaae782016-04-15 23:18:43 +0000521 return getVM()[V] = ConstantPointerNull::get(cast<PointerType>(NewTy));
Chris Lattner1c733cb2002-11-20 20:47:41 +0000522}
Brian Gaeke355f9f62004-05-19 09:08:12 +0000523
Duncan P. N. Exon Smith1c1f1172016-04-03 20:17:45 +0000524Value *Mapper::mapBlockAddress(const BlockAddress &BA) {
525 Function *F = cast<Function>(mapValue(BA.getFunction()));
526
527 // F may not have materialized its initializer. In that case, create a
528 // dummy basic block for now, and replace it once we've materialized all
529 // the initializers.
530 BasicBlock *BB;
Duncan P. N. Exon Smith69f4d0d2016-04-06 02:25:12 +0000531 if (F->empty()) {
Duncan P. N. Exon Smith1c1f1172016-04-03 20:17:45 +0000532 DelayedBBs.push_back(DelayedBasicBlock(BA));
533 BB = DelayedBBs.back().TempBB.get();
Duncan P. N. Exon Smith69f4d0d2016-04-06 02:25:12 +0000534 } else {
535 BB = cast_or_null<BasicBlock>(mapValue(BA.getBasicBlock()));
Duncan P. N. Exon Smith1c1f1172016-04-03 20:17:45 +0000536 }
537
Duncan P. N. Exon Smithbaaae782016-04-15 23:18:43 +0000538 return getVM()[&BA] = BlockAddress::get(F, BB ? BB : BA.getBasicBlock());
Duncan P. N. Exon Smith1c1f1172016-04-03 20:17:45 +0000539}
540
Duncan P. N. Exon Smith0a73e9e2016-04-03 19:06:24 +0000541Metadata *Mapper::mapToMetadata(const Metadata *Key, Metadata *Val) {
Duncan P. N. Exon Smithbaaae782016-04-15 23:18:43 +0000542 getVM().MD()[Key].reset(Val);
Duncan P. N. Exon Smith373db622014-12-09 18:38:53 +0000543 return Val;
544}
545
Duncan P. N. Exon Smith0a73e9e2016-04-03 19:06:24 +0000546Metadata *Mapper::mapToSelf(const Metadata *MD) {
547 return mapToMetadata(MD, const_cast<Metadata *>(MD));
Duncan P. N. Exon Smith373db622014-12-09 18:38:53 +0000548}
549
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000550Optional<Metadata *> MDNodeMapper::tryToMapOperand(const Metadata *Op) {
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000551 if (!Op)
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000552 return nullptr;
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000553
554 if (Optional<Metadata *> MappedOp = M.mapSimpleMetadata(Op)) {
Simon Atanasyan8f02c382016-04-16 11:49:40 +0000555#ifndef NDEBUG
Duncan P. N. Exon Smith56ecf502016-04-16 03:39:44 +0000556 if (auto *CMD = dyn_cast<ConstantAsMetadata>(Op))
557 assert((!*MappedOp || M.getVM().count(CMD->getValue()) ||
558 M.getVM().getMappedMD(Op)) &&
559 "Expected Value to be memoized");
560 else
561 assert((isa<MDString>(Op) || M.getVM().getMappedMD(Op)) &&
562 "Expected result to be memoized");
Simon Atanasyan8f02c382016-04-16 11:49:40 +0000563#endif
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000564 return *MappedOp;
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000565 }
566
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000567 const MDNode &N = *cast<MDNode>(Op);
568 if (N.isDistinct())
569 return mapDistinctNode(N);
570 return None;
571}
572
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000573MDNode *MDNodeMapper::mapDistinctNode(const MDNode &N) {
574 assert(N.isDistinct() && "Expected a distinct node");
575 assert(!M.getVM().getMappedMD(&N) && "Expected an unmapped node");
Ruiling Songae556892021-02-01 17:24:12 +0800576 Metadata *NewM = nullptr;
577
578 if (M.Flags & RF_ReuseAndMutateDistinctMDs) {
579 NewM = M.mapToSelf(&N);
580 } else {
581 NewM = MDNode::replaceWithDistinct(N.clone());
582 LLVM_DEBUG(dbgs() << "\nMap " << N << "\n"
583 << "To " << *NewM << "\n\n");
584 M.mapToMetadata(&N, NewM);
585 }
586 DistinctWorklist.push_back(cast<MDNode>(NewM));
587
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000588 return DistinctWorklist.back();
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000589}
590
Duncan P. N. Exon Smith56ecf502016-04-16 03:39:44 +0000591static ConstantAsMetadata *wrapConstantAsMetadata(const ConstantAsMetadata &CMD,
592 Value *MappedV) {
593 if (CMD.getValue() == MappedV)
594 return const_cast<ConstantAsMetadata *>(&CMD);
595 return MappedV ? ConstantAsMetadata::getConstant(MappedV) : nullptr;
596}
597
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000598Optional<Metadata *> MDNodeMapper::getMappedOp(const Metadata *Op) const {
Duncan P. N. Exon Smithb1555032015-01-14 01:01:19 +0000599 if (!Op)
600 return nullptr;
Teresa Johnsonc8042552015-12-18 17:51:37 +0000601
Duncan P. N. Exon Smithbaaae782016-04-15 23:18:43 +0000602 if (Optional<Metadata *> MappedOp = M.getVM().getMappedMD(Op))
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000603 return *MappedOp;
Duncan P. N. Exon Smithb1555032015-01-14 01:01:19 +0000604
Duncan P. N. Exon Smithfef81a42016-04-08 18:47:02 +0000605 if (isa<MDString>(Op))
606 return const_cast<Metadata *>(Op);
607
Duncan P. N. Exon Smith56ecf502016-04-16 03:39:44 +0000608 if (auto *CMD = dyn_cast<ConstantAsMetadata>(Op))
609 return wrapConstantAsMetadata(*CMD, M.getVM().lookup(CMD->getValue()));
610
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000611 return None;
Duncan P. N. Exon Smithb1555032015-01-14 01:01:19 +0000612}
613
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000614Metadata &MDNodeMapper::UniquedGraph::getFwdReference(MDNode &Op) {
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000615 auto Where = Info.find(&Op);
616 assert(Where != Info.end() && "Expected a valid reference");
617
618 auto &OpD = Where->second;
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000619 if (!OpD.HasChanged)
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000620 return Op;
621
622 // Lazily construct a temporary node.
623 if (!OpD.Placeholder)
624 OpD.Placeholder = Op.clone();
625
626 return *OpD.Placeholder;
627}
628
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000629template <class OperandMapper>
630void MDNodeMapper::remapOperands(MDNode &N, OperandMapper mapOperand) {
631 assert(!N.isUniqued() && "Expected distinct or temporary nodes");
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000632 for (unsigned I = 0, E = N.getNumOperands(); I != E; ++I) {
633 Metadata *Old = N.getOperand(I);
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000634 Metadata *New = mapOperand(Old);
Ruiling Songae556892021-02-01 17:24:12 +0800635 if (Old != New)
636 LLVM_DEBUG(dbgs() << "Replacing Op " << Old << " with " << New << " in "
637 << N << "\n");
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000638
639 if (Old != New)
640 N.replaceOperandWith(I, New);
641 }
642}
643
Duncan P. N. Exon Smithf6a0a402016-04-22 02:33:06 +0000644namespace {
Eugene Zelenkobd1fb282017-10-26 00:55:39 +0000645
Duncan P. N. Exon Smithf6a0a402016-04-22 02:33:06 +0000646/// An entry in the worklist for the post-order traversal.
647struct POTWorklistEntry {
648 MDNode *N; ///< Current node.
649 MDNode::op_iterator Op; ///< Current operand of \c N.
650
651 /// Keep a flag of whether operands have changed in the worklist to avoid
652 /// hitting the map in \a UniquedGraph.
653 bool HasChanged = false;
654
655 POTWorklistEntry(MDNode &N) : N(&N), Op(N.op_begin()) {}
656};
Eugene Zelenkobd1fb282017-10-26 00:55:39 +0000657
658} // end anonymous namespace
Duncan P. N. Exon Smithf6a0a402016-04-22 02:33:06 +0000659
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000660bool MDNodeMapper::createPOT(UniquedGraph &G, const MDNode &FirstN) {
661 assert(G.Info.empty() && "Expected a fresh traversal");
662 assert(FirstN.isUniqued() && "Expected uniqued node in POT");
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000663
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000664 // Construct a post-order traversal of the uniqued subgraph under FirstN.
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000665 bool AnyChanges = false;
Duncan P. N. Exon Smithfec75e12016-04-21 02:34:36 +0000666 SmallVector<POTWorklistEntry, 16> Worklist;
667 Worklist.push_back(POTWorklistEntry(const_cast<MDNode &>(FirstN)));
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000668 (void)G.Info[&FirstN];
669 while (!Worklist.empty()) {
Duncan P. N. Exon Smithf6a0a402016-04-22 02:33:06 +0000670 // Start or continue the traversal through the this node's operands.
671 auto &WE = Worklist.back();
672 if (MDNode *N = visitOperands(G, WE.Op, WE.N->op_end(), WE.HasChanged)) {
673 // Push a new node to traverse first.
674 Worklist.push_back(POTWorklistEntry(*N));
Duncan P. N. Exon Smithfec75e12016-04-21 02:34:36 +0000675 continue;
Duncan P. N. Exon Smithf6a0a402016-04-22 02:33:06 +0000676 }
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000677
Duncan P. N. Exon Smithf6a0a402016-04-22 02:33:06 +0000678 // Push the node onto the POT.
679 assert(WE.N->isUniqued() && "Expected only uniqued nodes");
680 assert(WE.Op == WE.N->op_end() && "Expected to visit all operands");
681 auto &D = G.Info[WE.N];
682 AnyChanges |= D.HasChanged = WE.HasChanged;
Duncan P. N. Exon Smithfec75e12016-04-21 02:34:36 +0000683 D.ID = G.POT.size();
Duncan P. N. Exon Smithf6a0a402016-04-22 02:33:06 +0000684 G.POT.push_back(WE.N);
685
686 // Pop the node off the worklist.
687 Worklist.pop_back();
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000688 }
689 return AnyChanges;
690}
691
Duncan P. N. Exon Smithf6a0a402016-04-22 02:33:06 +0000692MDNode *MDNodeMapper::visitOperands(UniquedGraph &G, MDNode::op_iterator &I,
693 MDNode::op_iterator E, bool &HasChanged) {
694 while (I != E) {
695 Metadata *Op = *I++; // Increment even on early return.
696 if (Optional<Metadata *> MappedOp = tryToMapOperand(Op)) {
697 // Check if the operand changes.
698 HasChanged |= Op != *MappedOp;
699 continue;
700 }
701
702 // A uniqued metadata node.
703 MDNode &OpN = *cast<MDNode>(Op);
704 assert(OpN.isUniqued() &&
705 "Only uniqued operands cannot be mapped immediately");
706 if (G.Info.insert(std::make_pair(&OpN, Data())).second)
707 return &OpN; // This is a new one. Return it.
Duncan P. N. Exon Smithfec75e12016-04-21 02:34:36 +0000708 }
Duncan P. N. Exon Smithf6a0a402016-04-22 02:33:06 +0000709 return nullptr;
Duncan P. N. Exon Smithfec75e12016-04-21 02:34:36 +0000710}
711
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000712void MDNodeMapper::UniquedGraph::propagateChanges() {
713 bool AnyChanges;
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000714 do {
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000715 AnyChanges = false;
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000716 for (MDNode *N : POT) {
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000717 auto &D = Info[N];
718 if (D.HasChanged)
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000719 continue;
720
Eugene Zelenkobd1fb282017-10-26 00:55:39 +0000721 if (llvm::none_of(N->operands(), [&](const Metadata *Op) {
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000722 auto Where = Info.find(Op);
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000723 return Where != Info.end() && Where->second.HasChanged;
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000724 }))
725 continue;
726
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000727 AnyChanges = D.HasChanged = true;
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000728 }
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000729 } while (AnyChanges);
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000730}
731
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000732void MDNodeMapper::mapNodesInPOT(UniquedGraph &G) {
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000733 // Construct uniqued nodes, building forward references as necessary.
Duncan P. N. Exon Smith0f74a3c2016-04-13 22:54:01 +0000734 SmallVector<MDNode *, 16> CyclicNodes;
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000735 for (auto *N : G.POT) {
736 auto &D = G.Info[N];
737 if (!D.HasChanged) {
738 // The node hasn't changed.
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000739 M.mapToSelf(N);
740 continue;
741 }
742
Duncan P. N. Exon Smith39703442016-04-16 21:09:53 +0000743 // Remember whether this node had a placeholder.
744 bool HadPlaceholder(D.Placeholder);
745
746 // Clone the uniqued node and remap the operands.
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000747 TempMDNode ClonedN = D.Placeholder ? std::move(D.Placeholder) : N->clone();
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000748 remapOperands(*ClonedN, [this, &D, &G](Metadata *Old) {
749 if (Optional<Metadata *> MappedOp = getMappedOp(Old))
750 return *MappedOp;
David L. Jones1c840602017-01-13 21:02:41 +0000751 (void)D;
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000752 assert(G.Info[Old].ID > D.ID && "Expected a forward reference");
753 return &G.getFwdReference(*cast<MDNode>(Old));
754 });
755
Duncan P. N. Exon Smith39703442016-04-16 21:09:53 +0000756 auto *NewN = MDNode::replaceWithUniqued(std::move(ClonedN));
Ruiling Songae556892021-02-01 17:24:12 +0800757 if (N && NewN && N != NewN) {
758 LLVM_DEBUG(dbgs() << "\nMap " << *N << "\n"
759 << "To " << *NewN << "\n\n");
760 }
761
Duncan P. N. Exon Smith39703442016-04-16 21:09:53 +0000762 M.mapToMetadata(N, NewN);
763
764 // Nodes that were referenced out of order in the POT are involved in a
765 // uniquing cycle.
766 if (HadPlaceholder)
767 CyclicNodes.push_back(NewN);
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000768 }
769
770 // Resolve cycles.
Duncan P. N. Exon Smith0f74a3c2016-04-13 22:54:01 +0000771 for (auto *N : CyclicNodes)
Teresa Johnson89cdaf52016-03-29 18:24:19 +0000772 if (!N->isResolved())
773 N->resolveCycles();
Duncan P. N. Exon Smith5d6b9602015-08-07 00:39:26 +0000774}
775
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000776Metadata *MDNodeMapper::map(const MDNode &N) {
777 assert(DistinctWorklist.empty() && "MDNodeMapper::map is not recursive");
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000778 assert(!(M.Flags & RF_NoModuleLevelChanges) &&
779 "MDNodeMapper::map assumes module-level changes");
Duncan P. N. Exon Smithe609e8862015-01-14 01:03:05 +0000780
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000781 // Require resolved nodes whenever metadata might be remapped.
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000782 assert(N.isResolved() && "Unexpected unresolved node");
Duncan P. N. Exon Smith39bc2872015-02-04 19:44:34 +0000783
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000784 Metadata *MappedN =
785 N.isUniqued() ? mapTopLevelUniquedNode(N) : mapDistinctNode(N);
786 while (!DistinctWorklist.empty())
787 remapOperands(*DistinctWorklist.pop_back_val(), [this](Metadata *Old) {
788 if (Optional<Metadata *> MappedOp = tryToMapOperand(Old))
789 return *MappedOp;
790 return mapTopLevelUniquedNode(*cast<MDNode>(Old));
791 });
792 return MappedN;
793}
794
795Metadata *MDNodeMapper::mapTopLevelUniquedNode(const MDNode &FirstN) {
796 assert(FirstN.isUniqued() && "Expected uniqued node");
797
798 // Create a post-order traversal of uniqued nodes under FirstN.
799 UniquedGraph G;
800 if (!createPOT(G, FirstN)) {
801 // Return early if no nodes have changed.
802 for (const MDNode *N : G.POT)
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000803 M.mapToSelf(N);
804 return &const_cast<MDNode &>(FirstN);
Duncan P. N. Exon Smithfc1953f2015-08-04 06:42:31 +0000805 }
Duncan P. N. Exon Smith4e79d702015-01-19 22:39:07 +0000806
Duncan P. N. Exon Smitha15f1ad2016-04-16 21:44:08 +0000807 // Update graph with all nodes that have changed.
808 G.propagateChanges();
809
810 // Map all the nodes in the graph.
811 mapNodesInPOT(G);
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000812
813 // Return the original node, remapped.
814 return *getMappedOp(&FirstN);
Duncan P. N. Exon Smithd40001b2015-01-14 01:06:21 +0000815}
816
Duncan P. N. Exon Smithdf941122016-04-03 19:31:01 +0000817Optional<Metadata *> Mapper::mapSimpleMetadata(const Metadata *MD) {
Duncan P. N. Exon Smith373db622014-12-09 18:38:53 +0000818 // If the value already exists in the map, use it.
Duncan P. N. Exon Smithbaaae782016-04-15 23:18:43 +0000819 if (Optional<Metadata *> NewMD = getVM().getMappedMD(MD))
Duncan P. N. Exon Smithbafa3dc2016-04-02 17:04:38 +0000820 return *NewMD;
Duncan P. N. Exon Smith373db622014-12-09 18:38:53 +0000821
822 if (isa<MDString>(MD))
Duncan P. N. Exon Smithfef81a42016-04-08 18:47:02 +0000823 return const_cast<Metadata *>(MD);
Duncan P. N. Exon Smith373db622014-12-09 18:38:53 +0000824
Duncan P. N. Exon Smitha27492c2016-04-08 03:13:22 +0000825 // This is a module-level metadata. If nothing at the module level is
826 // changing, use an identity mapping.
827 if ((Flags & RF_NoModuleLevelChanges))
Duncan P. N. Exon Smithff3a91f2016-04-08 18:49:36 +0000828 return const_cast<Metadata *>(MD);
Duncan P. N. Exon Smith373db622014-12-09 18:38:53 +0000829
Duncan P. N. Exon Smitha27492c2016-04-08 03:13:22 +0000830 if (auto *CMD = dyn_cast<ConstantAsMetadata>(MD)) {
Duncan P. N. Exon Smith56ecf502016-04-16 03:39:44 +0000831 // Don't memoize ConstantAsMetadata. Instead of lasting until the
832 // LLVMContext is destroyed, they can be deleted when the GlobalValue they
833 // reference is destructed. These aren't super common, so the extra
834 // indirection isn't that expensive.
835 return wrapConstantAsMetadata(*CMD, mapValue(CMD->getValue()));
Duncan P. N. Exon Smith373db622014-12-09 18:38:53 +0000836 }
837
Duncan P. N. Exon Smithdf941122016-04-03 19:31:01 +0000838 assert(isa<MDNode>(MD) && "Expected a metadata node");
Duncan P. N. Exon Smith373db622014-12-09 18:38:53 +0000839
Duncan P. N. Exon Smithdf941122016-04-03 19:31:01 +0000840 return None;
841}
842
Duncan P. N. Exon Smith0a73e9e2016-04-03 19:06:24 +0000843Metadata *Mapper::mapMetadata(const Metadata *MD) {
Duncan P. N. Exon Smitha27492c2016-04-08 03:13:22 +0000844 assert(MD && "Expected valid metadata");
845 assert(!isa<LocalAsMetadata>(MD) && "Unexpected local metadata");
846
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000847 if (Optional<Metadata *> NewMD = mapSimpleMetadata(MD))
848 return *NewMD;
Duncan P. N. Exon Smith39bc2872015-02-04 19:44:34 +0000849
Duncan P. N. Exon Smith36242fd2016-04-05 20:23:21 +0000850 return MDNodeMapper(*this).map(*cast<MDNode>(MD));
Duncan P. N. Exon Smith373db622014-12-09 18:38:53 +0000851}
852
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +0000853void Mapper::flush() {
854 // Flush out the worklist of global values.
855 while (!Worklist.empty()) {
856 WorklistEntry E = Worklist.pop_back_val();
857 CurrentMCID = E.MCID;
858 switch (E.Kind) {
859 case WorklistEntry::MapGlobalInit:
860 E.Data.GVInit.GV->setInitializer(mapConstant(E.Data.GVInit.Init));
Evgeniy Stepanov31818532017-05-04 23:29:39 +0000861 remapGlobalObjectMetadata(*E.Data.GVInit.GV);
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +0000862 break;
863 case WorklistEntry::MapAppendingVar: {
864 unsigned PrefixSize = AppendingInits.size() - E.AppendingGVNumNewMembers;
Sergey Dmitriev006eb092021-01-25 18:07:23 -0800865 // mapAppendingVariable call can change AppendingInits if initalizer for
866 // the variable depends on another appending global, because of that inits
867 // need to be extracted and updated before the call.
868 SmallVector<Constant *, 8> NewInits(
869 drop_begin(AppendingInits, PrefixSize));
870 AppendingInits.resize(PrefixSize);
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +0000871 mapAppendingVariable(*E.Data.AppendingGV.GV,
872 E.Data.AppendingGV.InitPrefix,
Sergey Dmitriev006eb092021-01-25 18:07:23 -0800873 E.AppendingGVIsOldCtorDtor, makeArrayRef(NewInits));
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +0000874 break;
875 }
Peter Collingbourne00e6c2f2019-08-08 22:09:18 +0000876 case WorklistEntry::MapGlobalIndirectSymbol:
877 E.Data.GlobalIndirectSymbol.GIS->setIndirectSymbol(
878 mapConstant(E.Data.GlobalIndirectSymbol.Target));
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +0000879 break;
880 case WorklistEntry::RemapFunction:
881 remapFunction(*E.Data.RemapF);
882 break;
883 }
Duncan P. N. Exon Smith1c1f1172016-04-03 20:17:45 +0000884 }
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +0000885 CurrentMCID = 0;
Duncan P. N. Exon Smith1c1f1172016-04-03 20:17:45 +0000886
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +0000887 // Finish logic for block addresses now that all global values have been
888 // handled.
Duncan P. N. Exon Smith1c1f1172016-04-03 20:17:45 +0000889 while (!DelayedBBs.empty()) {
890 DelayedBasicBlock DBB = DelayedBBs.pop_back_val();
891 BasicBlock *BB = cast_or_null<BasicBlock>(mapValue(DBB.OldBB));
892 DBB.TempBB->replaceAllUsesWith(BB ? BB : DBB.OldBB);
893 }
Duncan P. N. Exon Smithba441152016-04-08 19:09:34 +0000894}
895
896void Mapper::remapInstruction(Instruction *I) {
Dan Gohmanf6c8a542010-08-26 15:41:53 +0000897 // Remap operands.
Davide Italiano81610cc2016-04-14 18:07:32 +0000898 for (Use &Op : I->operands()) {
899 Value *V = mapValue(Op);
Chris Lattnerb76d75c2011-01-08 08:15:20 +0000900 // If we aren't ignoring missing entries, assert that something happened.
Craig Toppereb4c76a2014-04-25 05:29:35 +0000901 if (V)
Davide Italiano81610cc2016-04-14 18:07:32 +0000902 Op = V;
Chris Lattnerb76d75c2011-01-08 08:15:20 +0000903 else
Duncan P. N. Exon Smith16898092016-04-07 00:26:43 +0000904 assert((Flags & RF_IgnoreMissingLocals) &&
Chris Lattnerb76d75c2011-01-08 08:15:20 +0000905 "Referenced value not in value map!");
Brian Gaeke355f9f62004-05-19 09:08:12 +0000906 }
Daniel Dunbarf6e4e9e2010-08-26 03:48:08 +0000907
Jay Foad33f3f4e2011-06-23 09:09:15 +0000908 // Remap phi nodes' incoming blocks.
909 if (PHINode *PN = dyn_cast<PHINode>(I)) {
910 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Duncan P. N. Exon Smith24a96e72016-04-08 19:17:13 +0000911 Value *V = mapValue(PN->getIncomingBlock(i));
Jay Foad33f3f4e2011-06-23 09:09:15 +0000912 // If we aren't ignoring missing entries, assert that something happened.
Craig Toppereb4c76a2014-04-25 05:29:35 +0000913 if (V)
Jay Foad33f3f4e2011-06-23 09:09:15 +0000914 PN->setIncomingBlock(i, cast<BasicBlock>(V));
915 else
Duncan P. N. Exon Smith16898092016-04-07 00:26:43 +0000916 assert((Flags & RF_IgnoreMissingLocals) &&
Jay Foad33f3f4e2011-06-23 09:09:15 +0000917 "Referenced block not in value map!");
918 }
919 }
920
Devang Pateleb3e2422011-08-04 20:02:18 +0000921 // Remap attached metadata.
Duncan P. N. Exon Smith1bd16232014-11-11 21:30:22 +0000922 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
Devang Pateleb3e2422011-08-04 20:02:18 +0000923 I->getAllMetadata(MDs);
Duncan P. N. Exon Smith62b649f2015-08-03 03:27:12 +0000924 for (const auto &MI : MDs) {
925 MDNode *Old = MI.second;
Duncan P. N. Exon Smithba441152016-04-08 19:09:34 +0000926 MDNode *New = cast_or_null<MDNode>(mapMetadata(Old));
Dan Gohmanf6c8a542010-08-26 15:41:53 +0000927 if (New != Old)
Duncan P. N. Exon Smith62b649f2015-08-03 03:27:12 +0000928 I->setMetadata(MI.first, New);
Dan Gohmanf6c8a542010-08-26 15:41:53 +0000929 }
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +0000930
David Blaikied567f2f2015-04-23 21:36:23 +0000931 if (!TypeMapper)
932 return;
933
Chris Lattner212157c2011-07-09 17:41:24 +0000934 // If the instruction's type is being remapped, do so now.
Mircea Trofin9500e4e2020-04-15 16:50:57 -0700935 if (auto *CB = dyn_cast<CallBase>(I)) {
David Blaikied567f2f2015-04-23 21:36:23 +0000936 SmallVector<Type *, 3> Tys;
Mircea Trofin9500e4e2020-04-15 16:50:57 -0700937 FunctionType *FTy = CB->getFunctionType();
David Blaikied567f2f2015-04-23 21:36:23 +0000938 Tys.reserve(FTy->getNumParams());
939 for (Type *Ty : FTy->params())
940 Tys.push_back(TypeMapper->remapType(Ty));
Mircea Trofin9500e4e2020-04-15 16:50:57 -0700941 CB->mutateFunctionType(FunctionType::get(
David Blaikied567f2f2015-04-23 21:36:23 +0000942 TypeMapper->remapType(I->getType()), Tys, FTy->isVarArg()));
Tim Northover8eadeda2019-05-30 18:48:23 +0000943
Mircea Trofin9500e4e2020-04-15 16:50:57 -0700944 LLVMContext &C = CB->getContext();
945 AttributeList Attrs = CB->getAttributes();
Tim Northover8eadeda2019-05-30 18:48:23 +0000946 for (unsigned i = 0; i < Attrs.getNumAttrSets(); ++i) {
Matt Arsenaulta4985e72020-09-29 09:33:55 -0400947 for (Attribute::AttrKind TypedAttr :
Nico Weber01c9b9c2021-03-28 13:02:52 -0400948 {Attribute::ByVal, Attribute::StructRet, Attribute::ByRef}) {
Matt Arsenaulta4985e72020-09-29 09:33:55 -0400949 if (Type *Ty = Attrs.getAttribute(i, TypedAttr).getValueAsType()) {
950 Attrs = Attrs.replaceAttributeType(C, i, TypedAttr,
951 TypeMapper->remapType(Ty));
952 break;
953 }
Tim Northover8eadeda2019-05-30 18:48:23 +0000954 }
955 }
Mircea Trofin9500e4e2020-04-15 16:50:57 -0700956 CB->setAttributes(Attrs);
David Blaikie93e09f02015-04-29 23:00:35 +0000957 return;
958 }
959 if (auto *AI = dyn_cast<AllocaInst>(I))
960 AI->setAllocatedType(TypeMapper->remapType(AI->getAllocatedType()));
David Blaikie5ccf06f2015-06-01 03:09:34 +0000961 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
David Blaikie2d9b98b2015-05-05 18:03:48 +0000962 GEP->setSourceElementType(
963 TypeMapper->remapType(GEP->getSourceElementType()));
David Blaikie5ccf06f2015-06-01 03:09:34 +0000964 GEP->setResultElementType(
965 TypeMapper->remapType(GEP->getResultElementType()));
966 }
David Blaikie93e09f02015-04-29 23:00:35 +0000967 I->mutateType(TypeMapper->remapType(I->getType()));
Dan Gohmanf6c8a542010-08-26 15:41:53 +0000968}
Duncan P. N. Exon Smith24a7e4e2016-04-08 19:26:32 +0000969
Evgeniy Stepanov31818532017-05-04 23:29:39 +0000970void Mapper::remapGlobalObjectMetadata(GlobalObject &GO) {
971 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
972 GO.getAllMetadata(MDs);
973 GO.clearMetadata();
974 for (const auto &I : MDs)
975 GO.addMetadata(I.first, *cast<MDNode>(mapMetadata(I.second)));
976}
977
Duncan P. N. Exon Smith24a7e4e2016-04-08 19:26:32 +0000978void Mapper::remapFunction(Function &F) {
979 // Remap the operands.
980 for (Use &Op : F.operands())
981 if (Op)
982 Op = mapValue(Op);
983
984 // Remap the metadata attachments.
Evgeniy Stepanov31818532017-05-04 23:29:39 +0000985 remapGlobalObjectMetadata(F);
Duncan P. N. Exon Smith24a7e4e2016-04-08 19:26:32 +0000986
987 // Remap the argument types.
988 if (TypeMapper)
989 for (Argument &A : F.args())
990 A.mutateType(TypeMapper->remapType(A.getType()));
991
992 // Remap the instructions.
993 for (BasicBlock &BB : F)
994 for (Instruction &I : BB)
995 remapInstruction(&I);
996}
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +0000997
998void Mapper::mapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
999 bool IsOldCtorDtor,
1000 ArrayRef<Constant *> NewMembers) {
1001 SmallVector<Constant *, 16> Elements;
1002 if (InitPrefix) {
1003 unsigned NumElements =
1004 cast<ArrayType>(InitPrefix->getType())->getNumElements();
1005 for (unsigned I = 0; I != NumElements; ++I)
1006 Elements.push_back(InitPrefix->getAggregateElement(I));
1007 }
1008
1009 PointerType *VoidPtrTy;
1010 Type *EltTy;
1011 if (IsOldCtorDtor) {
1012 // FIXME: This upgrade is done during linking to support the C API. See
1013 // also IRLinker::linkAppendingVarProto() in IRMover.cpp.
1014 VoidPtrTy = Type::getInt8Ty(GV.getContext())->getPointerTo();
1015 auto &ST = *cast<StructType>(NewMembers.front()->getType());
1016 Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
1017 EltTy = StructType::get(GV.getContext(), Tys, false);
1018 }
1019
1020 for (auto *V : NewMembers) {
1021 Constant *NewV;
1022 if (IsOldCtorDtor) {
1023 auto *S = cast<ConstantStruct>(V);
Serge Guelton6b335552017-05-09 19:31:13 +00001024 auto *E1 = cast<Constant>(mapValue(S->getOperand(0)));
1025 auto *E2 = cast<Constant>(mapValue(S->getOperand(1)));
1026 Constant *Null = Constant::getNullValue(VoidPtrTy);
1027 NewV = ConstantStruct::get(cast<StructType>(EltTy), E1, E2, Null);
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +00001028 } else {
1029 NewV = cast_or_null<Constant>(mapValue(V));
1030 }
1031 Elements.push_back(NewV);
1032 }
1033
1034 GV.setInitializer(ConstantArray::get(
1035 cast<ArrayType>(GV.getType()->getElementType()), Elements));
1036}
1037
1038void Mapper::scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init,
1039 unsigned MCID) {
Duncan P. N. Exon Smithc26c0122016-04-17 19:40:20 +00001040 assert(AlreadyScheduled.insert(&GV).second && "Should not reschedule");
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +00001041 assert(MCID < MCs.size() && "Invalid mapping context");
1042
1043 WorklistEntry WE;
1044 WE.Kind = WorklistEntry::MapGlobalInit;
1045 WE.MCID = MCID;
1046 WE.Data.GVInit.GV = &GV;
1047 WE.Data.GVInit.Init = &Init;
1048 Worklist.push_back(WE);
1049}
1050
1051void Mapper::scheduleMapAppendingVariable(GlobalVariable &GV,
1052 Constant *InitPrefix,
1053 bool IsOldCtorDtor,
1054 ArrayRef<Constant *> NewMembers,
1055 unsigned MCID) {
Duncan P. N. Exon Smithc26c0122016-04-17 19:40:20 +00001056 assert(AlreadyScheduled.insert(&GV).second && "Should not reschedule");
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +00001057 assert(MCID < MCs.size() && "Invalid mapping context");
1058
1059 WorklistEntry WE;
1060 WE.Kind = WorklistEntry::MapAppendingVar;
1061 WE.MCID = MCID;
1062 WE.Data.AppendingGV.GV = &GV;
1063 WE.Data.AppendingGV.InitPrefix = InitPrefix;
1064 WE.AppendingGVIsOldCtorDtor = IsOldCtorDtor;
1065 WE.AppendingGVNumNewMembers = NewMembers.size();
1066 Worklist.push_back(WE);
1067 AppendingInits.append(NewMembers.begin(), NewMembers.end());
1068}
1069
Peter Collingbourne00e6c2f2019-08-08 22:09:18 +00001070void Mapper::scheduleMapGlobalIndirectSymbol(GlobalIndirectSymbol &GIS,
1071 Constant &Target, unsigned MCID) {
1072 assert(AlreadyScheduled.insert(&GIS).second && "Should not reschedule");
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +00001073 assert(MCID < MCs.size() && "Invalid mapping context");
1074
1075 WorklistEntry WE;
Peter Collingbourne00e6c2f2019-08-08 22:09:18 +00001076 WE.Kind = WorklistEntry::MapGlobalIndirectSymbol;
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +00001077 WE.MCID = MCID;
Peter Collingbourne00e6c2f2019-08-08 22:09:18 +00001078 WE.Data.GlobalIndirectSymbol.GIS = &GIS;
1079 WE.Data.GlobalIndirectSymbol.Target = &Target;
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +00001080 Worklist.push_back(WE);
1081}
1082
1083void Mapper::scheduleRemapFunction(Function &F, unsigned MCID) {
Duncan P. N. Exon Smithc26c0122016-04-17 19:40:20 +00001084 assert(AlreadyScheduled.insert(&F).second && "Should not reschedule");
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +00001085 assert(MCID < MCs.size() && "Invalid mapping context");
1086
1087 WorklistEntry WE;
1088 WE.Kind = WorklistEntry::RemapFunction;
1089 WE.MCID = MCID;
1090 WE.Data.RemapF = &F;
1091 Worklist.push_back(WE);
1092}
1093
1094void Mapper::addFlags(RemapFlags Flags) {
1095 assert(!hasWorkToDo() && "Expected to have flushed the worklist");
1096 this->Flags = this->Flags | Flags;
1097}
1098
1099static Mapper *getAsMapper(void *pImpl) {
1100 return reinterpret_cast<Mapper *>(pImpl);
1101}
1102
1103namespace {
1104
1105class FlushingMapper {
1106 Mapper &M;
1107
1108public:
1109 explicit FlushingMapper(void *pImpl) : M(*getAsMapper(pImpl)) {
1110 assert(!M.hasWorkToDo() && "Expected to be flushed");
1111 }
Eugene Zelenkobd1fb282017-10-26 00:55:39 +00001112
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +00001113 ~FlushingMapper() { M.flush(); }
Eugene Zelenkobd1fb282017-10-26 00:55:39 +00001114
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +00001115 Mapper *operator->() const { return &M; }
1116};
1117
Eugene Zelenkobd1fb282017-10-26 00:55:39 +00001118} // end anonymous namespace
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +00001119
1120ValueMapper::ValueMapper(ValueToValueMapTy &VM, RemapFlags Flags,
1121 ValueMapTypeRemapper *TypeMapper,
1122 ValueMaterializer *Materializer)
1123 : pImpl(new Mapper(VM, Flags, TypeMapper, Materializer)) {}
1124
1125ValueMapper::~ValueMapper() { delete getAsMapper(pImpl); }
1126
1127unsigned
1128ValueMapper::registerAlternateMappingContext(ValueToValueMapTy &VM,
1129 ValueMaterializer *Materializer) {
1130 return getAsMapper(pImpl)->registerAlternateMappingContext(VM, Materializer);
1131}
1132
1133void ValueMapper::addFlags(RemapFlags Flags) {
1134 FlushingMapper(pImpl)->addFlags(Flags);
1135}
1136
1137Value *ValueMapper::mapValue(const Value &V) {
1138 return FlushingMapper(pImpl)->mapValue(&V);
1139}
1140
1141Constant *ValueMapper::mapConstant(const Constant &C) {
1142 return cast_or_null<Constant>(mapValue(C));
1143}
1144
1145Metadata *ValueMapper::mapMetadata(const Metadata &MD) {
1146 return FlushingMapper(pImpl)->mapMetadata(&MD);
1147}
1148
1149MDNode *ValueMapper::mapMDNode(const MDNode &N) {
1150 return cast_or_null<MDNode>(mapMetadata(N));
1151}
1152
1153void ValueMapper::remapInstruction(Instruction &I) {
1154 FlushingMapper(pImpl)->remapInstruction(&I);
1155}
1156
1157void ValueMapper::remapFunction(Function &F) {
1158 FlushingMapper(pImpl)->remapFunction(F);
1159}
1160
1161void ValueMapper::scheduleMapGlobalInitializer(GlobalVariable &GV,
1162 Constant &Init,
1163 unsigned MCID) {
1164 getAsMapper(pImpl)->scheduleMapGlobalInitializer(GV, Init, MCID);
1165}
1166
1167void ValueMapper::scheduleMapAppendingVariable(GlobalVariable &GV,
1168 Constant *InitPrefix,
1169 bool IsOldCtorDtor,
1170 ArrayRef<Constant *> NewMembers,
1171 unsigned MCID) {
1172 getAsMapper(pImpl)->scheduleMapAppendingVariable(
1173 GV, InitPrefix, IsOldCtorDtor, NewMembers, MCID);
1174}
1175
Peter Collingbourne00e6c2f2019-08-08 22:09:18 +00001176void ValueMapper::scheduleMapGlobalIndirectSymbol(GlobalIndirectSymbol &GIS,
1177 Constant &Target,
1178 unsigned MCID) {
1179 getAsMapper(pImpl)->scheduleMapGlobalIndirectSymbol(GIS, Target, MCID);
Duncan P. N. Exon Smithbd718a32016-04-16 02:29:55 +00001180}
1181
1182void ValueMapper::scheduleRemapFunction(Function &F, unsigned MCID) {
1183 getAsMapper(pImpl)->scheduleRemapFunction(F, MCID);
1184}