blob: f8fa61329e202cf0b5f6f751b79581d7bf3e36b1 [file] [log] [blame]
Chris Lattnere4dbb1a2002-11-20 20:47:41 +00001//===- ValueMapper.cpp - Interface shared by lib/Transforms/Utils ---------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnere4dbb1a2002-11-20 20:47:41 +00009//
10// This file defines the MapValue function, which is shared by various parts of
11// the lib/Transforms/Utils library.
12//
13//===----------------------------------------------------------------------===//
14
Dan Gohmana2095032010-08-24 18:50:07 +000015#include "llvm/Transforms/Utils/ValueMapper.h"
David Blaikie348de692015-04-23 21:36:23 +000016#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +000018#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000019#include "llvm/IR/Function.h"
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +000020#include "llvm/IR/GlobalAlias.h"
21#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/InlineAsm.h"
23#include "llvm/IR/Instructions.h"
24#include "llvm/IR/Metadata.h"
David Blaikie88208842015-08-21 20:16:51 +000025#include "llvm/IR/Operator.h"
Chris Lattnerdf3c3422004-01-09 06:12:26 +000026using namespace llvm;
Chris Lattnere4dbb1a2002-11-20 20:47:41 +000027
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000028// Out of line method to get vtable etc for class.
Craig Topper2a6a08b2012-09-26 06:36:36 +000029void ValueMapTypeRemapper::anchor() {}
James Molloyf6f121e2013-05-28 15:17:05 +000030void ValueMaterializer::anchor() {}
Rafael Espindola19b52382015-11-27 20:28:19 +000031void ValueMaterializer::materializeInitFor(GlobalValue *New, GlobalValue *Old) {
32}
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000033
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +000034namespace {
35
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +000036/// A basic block used in a BlockAddress whose function body is not yet
37/// materialized.
38struct DelayedBasicBlock {
39 BasicBlock *OldBB;
40 std::unique_ptr<BasicBlock> TempBB;
Duncan P. N. Exon Smitha9978562016-04-03 20:42:21 +000041
42 // Explicit move for MSVC.
43 DelayedBasicBlock(DelayedBasicBlock &&X)
44 : OldBB(std::move(X.OldBB)), TempBB(std::move(X.TempBB)) {}
45 DelayedBasicBlock &operator=(DelayedBasicBlock &&X) {
46 OldBB = std::move(X.OldBB);
47 TempBB = std::move(X.TempBB);
48 return *this;
49 }
50
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +000051 DelayedBasicBlock(const BlockAddress &Old)
52 : OldBB(Old.getBasicBlock()),
53 TempBB(BasicBlock::Create(Old.getContext())) {}
54};
55
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +000056struct WorklistEntry {
57 enum EntryKind {
58 MapGlobalInit,
59 MapAppendingVar,
60 MapGlobalAliasee,
61 RemapFunction
62 };
63 struct GVInitTy {
64 GlobalVariable *GV;
65 Constant *Init;
66 };
67 struct AppendingGVTy {
68 GlobalVariable *GV;
69 Constant *InitPrefix;
70 };
71 struct GlobalAliaseeTy {
72 GlobalAlias *GA;
73 Constant *Aliasee;
74 };
75
76 unsigned Kind : 2;
77 unsigned MCID : 29;
78 unsigned AppendingGVIsOldCtorDtor : 1;
79 unsigned AppendingGVNumNewMembers;
80 union {
81 GVInitTy GVInit;
82 AppendingGVTy AppendingGV;
83 GlobalAliaseeTy GlobalAliasee;
84 Function *RemapF;
85 } Data;
86};
87
88struct MappingContext {
89 ValueToValueMapTy *VM;
90 ValueMaterializer *Materializer = nullptr;
91
92 /// Construct a MappingContext with a value map and materializer.
93 explicit MappingContext(ValueToValueMapTy &VM,
94 ValueMaterializer *Materializer = nullptr)
95 : VM(&VM), Materializer(Materializer) {}
96};
97
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +000098class MDNodeMapper;
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +000099class Mapper {
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000100 friend class MDNodeMapper;
101
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000102 RemapFlags Flags;
103 ValueMapTypeRemapper *TypeMapper;
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000104 unsigned CurrentMCID = 0;
105 SmallVector<MappingContext, 2> MCs;
106 SmallVector<WorklistEntry, 4> Worklist;
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000107 SmallVector<DelayedBasicBlock, 1> DelayedBBs;
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000108 SmallVector<Constant *, 16> AppendingInits;
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000109
110public:
111 Mapper(ValueToValueMapTy &VM, RemapFlags Flags,
112 ValueMapTypeRemapper *TypeMapper, ValueMaterializer *Materializer)
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000113 : Flags(Flags), TypeMapper(TypeMapper),
114 MCs(1, MappingContext(VM, Materializer)) {}
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000115
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000116 /// ValueMapper should explicitly call \a flush() before destruction.
117 ~Mapper() { assert(!hasWorkToDo() && "Expected to be flushed"); }
118
119 bool hasWorkToDo() const { return !Worklist.empty(); }
120
121 unsigned
122 registerAlternateMappingContext(ValueToValueMapTy &VM,
123 ValueMaterializer *Materializer = nullptr) {
124 MCs.push_back(MappingContext(VM, Materializer));
125 return MCs.size() - 1;
126 }
127
128 void addFlags(RemapFlags Flags);
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000129
130 Value *mapValue(const Value *V);
Duncan P. N. Exon Smitha574e7a2016-04-08 19:09:34 +0000131 void remapInstruction(Instruction *I);
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000132 void remapFunction(Function &F);
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000133
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000134 Constant *mapConstant(const Constant *C) {
135 return cast_or_null<Constant>(mapValue(C));
136 }
137
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000138 /// Map metadata.
139 ///
140 /// Find the mapping for MD. Guarantees that the return will be resolved
141 /// (not an MDNode, or MDNode::isResolved() returns true).
142 Metadata *mapMetadata(const Metadata *MD);
143
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000144 // Map LocalAsMetadata, which never gets memoized.
145 //
146 // If the referenced local is not mapped, the principled return is nullptr.
147 // However, optimization passes sometimes move metadata operands *before* the
148 // SSA values they reference. To prevent crashes in \a RemapInstruction(),
149 // return "!{}" when RF_IgnoreMissingLocals is not set.
150 //
151 // \note Adding a mapping for LocalAsMetadata is unsupported. Add a mapping
152 // to the value map for the SSA value in question instead.
153 //
154 // FIXME: Once we have a verifier check for forward references to SSA values
155 // through metadata operands, always return nullptr on unmapped locals.
156 Metadata *mapLocalAsMetadata(const LocalAsMetadata &LAM);
157
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000158 void scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init,
159 unsigned MCID);
160 void scheduleMapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
161 bool IsOldCtorDtor,
162 ArrayRef<Constant *> NewMembers,
163 unsigned MCID);
164 void scheduleMapGlobalAliasee(GlobalAlias &GA, Constant &Aliasee,
165 unsigned MCID);
166 void scheduleRemapFunction(Function &F, unsigned MCID);
167
168 void flush();
169
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000170private:
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000171 void mapGlobalInitializer(GlobalVariable &GV, Constant &Init);
172 void mapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
173 bool IsOldCtorDtor,
174 ArrayRef<Constant *> NewMembers);
175 void mapGlobalAliasee(GlobalAlias &GA, Constant &Aliasee);
176 void remapFunction(Function &F, ValueToValueMapTy &VM);
177
178 ValueToValueMapTy &getVM() { return *MCs[CurrentMCID].VM; }
179 ValueMaterializer *getMaterializer() { return MCs[CurrentMCID].Materializer; }
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000180
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000181 Value *mapBlockAddress(const BlockAddress &BA);
182
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +0000183 /// Map metadata that doesn't require visiting operands.
184 Optional<Metadata *> mapSimpleMetadata(const Metadata *MD);
185
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000186 Metadata *mapToMetadata(const Metadata *Key, Metadata *Val);
187 Metadata *mapToSelf(const Metadata *MD);
188};
189
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000190class MDNodeMapper {
191 Mapper &M;
192
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000193 /// Data about a node in \a UniquedGraph.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000194 struct Data {
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000195 bool HasChanged = false;
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000196 unsigned ID = ~0u;
197 TempMDNode Placeholder;
Duncan P. N. Exon Smithf880d352016-04-05 21:07:01 +0000198
Duncan P. N. Exon Smith818e5f32016-04-05 21:25:33 +0000199 Data() {}
200 Data(Data &&X)
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000201 : HasChanged(std::move(X.HasChanged)), ID(std::move(X.ID)),
202 Placeholder(std::move(X.Placeholder)) {}
Duncan P. N. Exon Smith818e5f32016-04-05 21:25:33 +0000203 Data &operator=(Data &&X) {
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000204 HasChanged = std::move(X.HasChanged);
Duncan P. N. Exon Smith818e5f32016-04-05 21:25:33 +0000205 ID = std::move(X.ID);
206 Placeholder = std::move(X.Placeholder);
207 return *this;
208 }
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000209 };
210
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000211 /// A graph of uniqued nodes.
212 struct UniquedGraph {
213 SmallDenseMap<const Metadata *, Data, 32> Info; // Node properties.
214 SmallVector<MDNode *, 16> POT; // Post-order traversal.
215
216 /// Propagate changed operands through the post-order traversal.
217 ///
218 /// Iteratively update \a Data::HasChanged for each node based on \a
219 /// Data::HasChanged of its operands, until fixed point.
220 void propagateChanges();
221
222 /// Get a forward reference to a node to use as an operand.
223 Metadata &getFwdReference(MDNode &Op);
224 };
225
226 /// Worklist of distinct nodes whose operands need to be remapped.
227 SmallVector<MDNode *, 16> DistinctWorklist;
228
229 // Storage for a UniquedGraph.
230 SmallDenseMap<const Metadata *, Data, 32> InfoStorage;
231 SmallVector<MDNode *, 16> POTStorage;
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000232
233public:
234 MDNodeMapper(Mapper &M) : M(M) {}
235
236 /// Map a metadata node (and its transitive operands).
237 ///
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000238 /// Map all the (unmapped) nodes in the subgraph under \c N. The iterative
239 /// algorithm handles distinct nodes and uniqued node subgraphs using
240 /// different strategies.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000241 ///
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000242 /// Distinct nodes are immediately mapped and added to \a DistinctWorklist
243 /// using \a mapDistinctNode(). Their mapping can always be computed
244 /// immediately without visiting operands, even if their operands change.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000245 ///
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000246 /// The mapping for uniqued nodes depends on whether their operands change.
247 /// \a mapTopLevelUniquedNode() traverses the transitive uniqued subgraph of
248 /// a node to calculate uniqued node mappings in bulk. Distinct leafs are
249 /// added to \a DistinctWorklist with \a mapDistinctNode().
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000250 ///
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000251 /// After mapping \c N itself, this function remaps the operands of the
252 /// distinct nodes in \a DistinctWorklist until the entire subgraph under \c
253 /// N has been mapped.
254 Metadata *map(const MDNode &N);
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000255
256private:
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000257 /// Map a top-level uniqued node and the uniqued subgraph underneath it.
258 ///
259 /// This builds up a post-order traversal of the (unmapped) uniqued subgraph
260 /// underneath \c FirstN and calculates the nodes' mapping. Each node uses
261 /// the identity mapping (\a Mapper::mapToSelf()) as long as all of its
262 /// operands uses the identity mapping.
263 ///
264 /// The algorithm works as follows:
265 ///
266 /// 1. \a createPOT(): traverse the uniqued subgraph under \c FirstN and
267 /// save the post-order traversal in the given \a UniquedGraph, tracking
268 /// nodes' operands change.
269 ///
270 /// 2. \a UniquedGraph::propagateChanges(): propagate changed operands
271 /// through the \a UniquedGraph until fixed point, following the rule
272 /// that if a node changes, any node that references must also change.
273 ///
274 /// 3. \a mapNodesInPOT(): map the uniqued nodes, creating new uniqued nodes
275 /// (referencing new operands) where necessary.
276 Metadata *mapTopLevelUniquedNode(const MDNode &FirstN);
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000277
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000278 /// Try to map the operand of an \a MDNode.
279 ///
280 /// If \c Op is already mapped, return the mapping. If it's not an \a
281 /// MDNode, compute and return the mapping. If it's a distinct \a MDNode,
282 /// return the result of \a mapDistinctNode().
283 ///
284 /// \return None if \c Op is an unmapped uniqued \a MDNode.
285 /// \post getMappedOp(Op) only returns None if this returns None.
286 Optional<Metadata *> tryToMapOperand(const Metadata *Op);
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000287
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000288 /// Map a distinct node.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000289 ///
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000290 /// Return the mapping for the distinct node \c N, saving the result in \a
291 /// DistinctWorklist for later remapping.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000292 ///
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000293 /// \pre \c N is not yet mapped.
294 /// \pre \c N.isDistinct().
295 MDNode *mapDistinctNode(const MDNode &N);
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000296
297 /// Get a previously mapped node.
298 Optional<Metadata *> getMappedOp(const Metadata *Op) const;
299
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000300 /// Create a post-order traversal of an unmapped uniqued node subgraph.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000301 ///
302 /// This traverses the metadata graph deeply enough to map \c FirstN. It
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000303 /// uses \a tryToMapOperand() (via \a Mapper::mapSimplifiedNode()), so any
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000304 /// metadata that has already been mapped will not be part of the POT.
305 ///
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000306 /// Each node that has a changed operand from outside the graph (e.g., a
307 /// distinct node, an already-mapped uniqued node, or \a ConstantAsMetadata)
308 /// is marked with \a Data::HasChanged.
309 ///
310 /// \return \c true if any nodes in \c G have \a Data::HasChanged.
311 /// \post \c G.POT is a post-order traversal ending with \c FirstN.
312 /// \post \a Data::hasChanged in \c G.Info indicates whether any node needs
313 /// to change because of operands outside the graph.
314 bool createPOT(UniquedGraph &G, const MDNode &FirstN);
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000315
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000316 /// Map all the nodes in the given uniqued graph.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000317 ///
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000318 /// This visits all the nodes in \c G in post-order, using the identity
319 /// mapping or creating a new node depending on \a Data::HasChanged.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000320 ///
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000321 /// \pre \a getMappedOp() returns None for nodes in \c G, but not for any of
322 /// their operands outside of \c G.
323 /// \pre \a Data::HasChanged is true for a node in \c G iff any of its
324 /// operands have changed.
325 /// \post \a getMappedOp() returns the mapped node for every node in \c G.
326 void mapNodesInPOT(UniquedGraph &G);
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000327
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000328 /// Remap a node's operands using the given functor.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000329 ///
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000330 /// Iterate through the operands of \c N and update them in place using \c
331 /// mapOperand.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000332 ///
333 /// \pre N.isDistinct() or N.isTemporary().
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000334 template <class OperandMapper>
335 void remapOperands(MDNode &N, OperandMapper mapOperand);
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000336};
337
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000338} // end namespace
339
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000340Value *Mapper::mapValue(const Value *V) {
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000341 ValueToValueMapTy::iterator I = getVM().find(V);
342
Chris Lattner43f8d162011-01-08 08:15:20 +0000343 // If the value already exists in the map, use it.
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000344 if (I != getVM().end() && I->second)
345 return I->second;
346
James Molloyf6f121e2013-05-28 15:17:05 +0000347 // If we have a materializer and it can materialize a value, use that.
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000348 if (auto *Materializer = getMaterializer()) {
Rafael Espindola19b52382015-11-27 20:28:19 +0000349 if (Value *NewV =
350 Materializer->materializeDeclFor(const_cast<Value *>(V))) {
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000351 getVM()[V] = NewV;
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000352 if (auto *NewGV = dyn_cast<GlobalValue>(NewV))
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000353 Materializer->materializeInitFor(
354 NewGV, cast<GlobalValue>(const_cast<Value *>(V)));
Rafael Espindola19b52382015-11-27 20:28:19 +0000355 return NewV;
356 }
James Molloyf6f121e2013-05-28 15:17:05 +0000357 }
358
Dan Gohmanca26f792010-08-26 15:41:53 +0000359 // Global values do not need to be seeded into the VM if they
360 // are using the identity mapping.
Teresa Johnson83d03dd2015-11-15 14:50:14 +0000361 if (isa<GlobalValue>(V)) {
Duncan P. N. Exon Smithfdccad92016-04-07 01:22:45 +0000362 if (Flags & RF_NullMapMissingGlobalValues)
Teresa Johnson83d03dd2015-11-15 14:50:14 +0000363 return nullptr;
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000364 return getVM()[V] = const_cast<Value *>(V);
Teresa Johnson83d03dd2015-11-15 14:50:14 +0000365 }
366
Chris Lattner8b4cf5e2011-07-15 23:18:40 +0000367 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
368 // Inline asm may need *type* remapping.
369 FunctionType *NewTy = IA->getFunctionType();
370 if (TypeMapper) {
371 NewTy = cast<FunctionType>(TypeMapper->remapType(NewTy));
372
373 if (NewTy != IA->getFunctionType())
374 V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),
375 IA->hasSideEffects(), IA->isAlignStack());
376 }
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000377
378 return getVM()[V] = const_cast<Value *>(V);
Chris Lattner8b4cf5e2011-07-15 23:18:40 +0000379 }
Chris Lattner6aa34b02003-10-06 15:23:43 +0000380
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000381 if (const auto *MDV = dyn_cast<MetadataAsValue>(V)) {
382 const Metadata *MD = MDV->getMetadata();
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000383
384 if (auto *LAM = dyn_cast<LocalAsMetadata>(MD)) {
385 // Look through to grab the local value.
386 if (Value *LV = mapValue(LAM->getValue())) {
387 if (V == LAM->getValue())
388 return const_cast<Value *>(V);
389 return MetadataAsValue::get(V->getContext(), ValueAsMetadata::get(LV));
390 }
391
392 // FIXME: always return nullptr once Verifier::verifyDominatesUse()
393 // ensures metadata operands only reference defined SSA values.
394 return (Flags & RF_IgnoreMissingLocals)
395 ? nullptr
396 : MetadataAsValue::get(V->getContext(),
397 MDTuple::get(V->getContext(), None));
398 }
399
Chris Lattner43f8d162011-01-08 08:15:20 +0000400 // If this is a module-level metadata and we know that nothing at the module
401 // level is changing, then use an identity mapping.
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000402 if (Flags & RF_NoModuleLevelChanges)
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000403 return getVM()[V] = const_cast<Value *>(V);
Dan Gohmanca26f792010-08-26 15:41:53 +0000404
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000405 // Map the metadata and turn it into a value.
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000406 auto *MappedMD = mapMetadata(MD);
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000407 if (MD == MappedMD)
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000408 return getVM()[V] = const_cast<Value *>(V);
409 return getVM()[V] = MetadataAsValue::get(V->getContext(), MappedMD);
Victor Hernandez5fa88d42010-01-20 05:49:59 +0000410 }
411
Chris Lattner43f8d162011-01-08 08:15:20 +0000412 // Okay, this either must be a constant (which may or may not be mappable) or
413 // is something that is not in the mapping table.
Chris Lattnercf5a47d2009-10-29 00:28:30 +0000414 Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
Craig Topperf40110f2014-04-25 05:29:35 +0000415 if (!C)
416 return nullptr;
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000417
418 if (BlockAddress *BA = dyn_cast<BlockAddress>(C))
419 return mapBlockAddress(*BA);
420
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000421 // Otherwise, we have some other constant to remap. Start by checking to see
422 // if all operands have an identity remapping.
423 unsigned OpNo = 0, NumOperands = C->getNumOperands();
Craig Topperf40110f2014-04-25 05:29:35 +0000424 Value *Mapped = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000425 for (; OpNo != NumOperands; ++OpNo) {
426 Value *Op = C->getOperand(OpNo);
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000427 Mapped = mapValue(Op);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000428 if (Mapped != C) break;
Chris Lattnercf5a47d2009-10-29 00:28:30 +0000429 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000430
431 // See if the type mapper wants to remap the type as well.
432 Type *NewTy = C->getType();
433 if (TypeMapper)
434 NewTy = TypeMapper->remapType(NewTy);
Chris Lattner43f8d162011-01-08 08:15:20 +0000435
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000436 // If the result type and all operands match up, then just insert an identity
437 // mapping.
438 if (OpNo == NumOperands && NewTy == C->getType())
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000439 return getVM()[V] = C;
440
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000441 // Okay, we need to create a new constant. We've already processed some or
442 // all of the operands, set them all up now.
443 SmallVector<Constant*, 8> Ops;
444 Ops.reserve(NumOperands);
445 for (unsigned j = 0; j != OpNo; ++j)
446 Ops.push_back(cast<Constant>(C->getOperand(j)));
447
448 // If one of the operands mismatch, push it and the other mapped operands.
449 if (OpNo != NumOperands) {
450 Ops.push_back(cast<Constant>(Mapped));
451
452 // Map the rest of the operands that aren't processed yet.
453 for (++OpNo; OpNo != NumOperands; ++OpNo)
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000454 Ops.push_back(cast<Constant>(mapValue(C->getOperand(OpNo))));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000455 }
David Blaikie88208842015-08-21 20:16:51 +0000456 Type *NewSrcTy = nullptr;
457 if (TypeMapper)
458 if (auto *GEPO = dyn_cast<GEPOperator>(C))
459 NewSrcTy = TypeMapper->remapType(GEPO->getSourceElementType());
460
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000461 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000462 return getVM()[V] = CE->getWithOperands(Ops, NewTy, false, NewSrcTy);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000463 if (isa<ConstantArray>(C))
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000464 return getVM()[V] = ConstantArray::get(cast<ArrayType>(NewTy), Ops);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000465 if (isa<ConstantStruct>(C))
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000466 return getVM()[V] = ConstantStruct::get(cast<StructType>(NewTy), Ops);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000467 if (isa<ConstantVector>(C))
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000468 return getVM()[V] = ConstantVector::get(Ops);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000469 // If this is a no-operand constant, it must be because the type was remapped.
470 if (isa<UndefValue>(C))
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000471 return getVM()[V] = UndefValue::get(NewTy);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000472 if (isa<ConstantAggregateZero>(C))
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000473 return getVM()[V] = ConstantAggregateZero::get(NewTy);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000474 assert(isa<ConstantPointerNull>(C));
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000475 return getVM()[V] = ConstantPointerNull::get(cast<PointerType>(NewTy));
Chris Lattnere4dbb1a2002-11-20 20:47:41 +0000476}
Brian Gaeke6182acf2004-05-19 09:08:12 +0000477
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000478Value *Mapper::mapBlockAddress(const BlockAddress &BA) {
479 Function *F = cast<Function>(mapValue(BA.getFunction()));
480
481 // F may not have materialized its initializer. In that case, create a
482 // dummy basic block for now, and replace it once we've materialized all
483 // the initializers.
484 BasicBlock *BB;
Duncan P. N. Exon Smith6f2e3742016-04-06 02:25:12 +0000485 if (F->empty()) {
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000486 DelayedBBs.push_back(DelayedBasicBlock(BA));
487 BB = DelayedBBs.back().TempBB.get();
Duncan P. N. Exon Smith6f2e3742016-04-06 02:25:12 +0000488 } else {
489 BB = cast_or_null<BasicBlock>(mapValue(BA.getBasicBlock()));
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000490 }
491
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000492 return getVM()[&BA] = BlockAddress::get(F, BB ? BB : BA.getBasicBlock());
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000493}
494
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000495Metadata *Mapper::mapToMetadata(const Metadata *Key, Metadata *Val) {
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000496 getVM().MD()[Key].reset(Val);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000497 return Val;
498}
499
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000500Metadata *Mapper::mapToSelf(const Metadata *MD) {
501 return mapToMetadata(MD, const_cast<Metadata *>(MD));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000502}
503
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000504Optional<Metadata *> MDNodeMapper::tryToMapOperand(const Metadata *Op) {
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000505 if (!Op)
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000506 return nullptr;
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000507
508 if (Optional<Metadata *> MappedOp = M.mapSimpleMetadata(Op)) {
Simon Atanasyane12bef72016-04-16 11:49:40 +0000509#ifndef NDEBUG
Duncan P. N. Exon Smitha77d0732016-04-16 03:39:44 +0000510 if (auto *CMD = dyn_cast<ConstantAsMetadata>(Op))
511 assert((!*MappedOp || M.getVM().count(CMD->getValue()) ||
512 M.getVM().getMappedMD(Op)) &&
513 "Expected Value to be memoized");
514 else
515 assert((isa<MDString>(Op) || M.getVM().getMappedMD(Op)) &&
516 "Expected result to be memoized");
Simon Atanasyane12bef72016-04-16 11:49:40 +0000517#endif
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000518 return *MappedOp;
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000519 }
520
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000521 const MDNode &N = *cast<MDNode>(Op);
522 if (N.isDistinct())
523 return mapDistinctNode(N);
524 return None;
525}
526
527MDNode *MDNodeMapper::mapDistinctNode(const MDNode &N) {
528 assert(N.isDistinct() && "Expected a distinct node");
529 assert(!M.getVM().getMappedMD(&N) && "Expected an unmapped node");
530 DistinctWorklist.push_back(cast<MDNode>(
531 (M.Flags & RF_MoveDistinctMDs)
532 ? M.mapToSelf(&N)
533 : M.mapToMetadata(&N, MDNode::replaceWithDistinct(N.clone()))));
534 return DistinctWorklist.back();
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000535}
536
Duncan P. N. Exon Smitha77d0732016-04-16 03:39:44 +0000537static ConstantAsMetadata *wrapConstantAsMetadata(const ConstantAsMetadata &CMD,
538 Value *MappedV) {
539 if (CMD.getValue() == MappedV)
540 return const_cast<ConstantAsMetadata *>(&CMD);
541 return MappedV ? ConstantAsMetadata::getConstant(MappedV) : nullptr;
542}
543
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000544Optional<Metadata *> MDNodeMapper::getMappedOp(const Metadata *Op) const {
Duncan P. N. Exon Smith077affd2015-01-14 01:01:19 +0000545 if (!Op)
546 return nullptr;
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000547
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000548 if (Optional<Metadata *> MappedOp = M.getVM().getMappedMD(Op))
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000549 return *MappedOp;
Duncan P. N. Exon Smith077affd2015-01-14 01:01:19 +0000550
Duncan P. N. Exon Smithe05ff7c2016-04-08 18:47:02 +0000551 if (isa<MDString>(Op))
552 return const_cast<Metadata *>(Op);
553
Duncan P. N. Exon Smitha77d0732016-04-16 03:39:44 +0000554 if (auto *CMD = dyn_cast<ConstantAsMetadata>(Op))
555 return wrapConstantAsMetadata(*CMD, M.getVM().lookup(CMD->getValue()));
556
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000557 return None;
Duncan P. N. Exon Smith077affd2015-01-14 01:01:19 +0000558}
559
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000560Metadata &MDNodeMapper::UniquedGraph::getFwdReference(MDNode &Op) {
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000561 auto Where = Info.find(&Op);
562 assert(Where != Info.end() && "Expected a valid reference");
563
564 auto &OpD = Where->second;
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000565 if (!OpD.HasChanged)
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000566 return Op;
567
568 // Lazily construct a temporary node.
569 if (!OpD.Placeholder)
570 OpD.Placeholder = Op.clone();
571
572 return *OpD.Placeholder;
573}
574
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000575template <class OperandMapper>
576void MDNodeMapper::remapOperands(MDNode &N, OperandMapper mapOperand) {
577 assert(!N.isUniqued() && "Expected distinct or temporary nodes");
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000578 for (unsigned I = 0, E = N.getNumOperands(); I != E; ++I) {
579 Metadata *Old = N.getOperand(I);
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000580 Metadata *New = mapOperand(Old);
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000581
582 if (Old != New)
583 N.replaceOperandWith(I, New);
584 }
585}
586
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000587bool MDNodeMapper::createPOT(UniquedGraph &G, const MDNode &FirstN) {
588 assert(G.Info.empty() && "Expected a fresh traversal");
589 assert(FirstN.isUniqued() && "Expected uniqued node in POT");
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000590
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000591 // Construct a post-order traversal of the uniqued subgraph under FirstN.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000592 bool AnyChanges = false;
593
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000594 // The flag on the worklist indicates whether this is the first or second
595 // visit of a node. The first visit looks through the operands; the second
596 // visit adds the node to POT.
597 SmallVector<std::pair<MDNode *, bool>, 16> Worklist;
598 Worklist.push_back(std::make_pair(&const_cast<MDNode &>(FirstN), false));
599 (void)G.Info[&FirstN];
600 while (!Worklist.empty()) {
601 MDNode &N = *Worklist.back().first;
602 if (Worklist.back().second) {
603 // We've already visited operands. Add this to POT.
604 Worklist.pop_back();
605 G.Info[&N].ID = G.POT.size();
606 G.POT.push_back(&N);
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000607 continue;
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000608 }
609 Worklist.back().second = true;
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000610
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000611 // Look through the operands for changes, pushing unmapped uniqued nodes
612 // onto to the worklist.
613 assert(N.isUniqued() && "Expected only uniqued nodes in POT");
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000614 bool LocalChanges = false;
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000615 for (Metadata *Op : N.operands()) {
616 assert(Op != &N && "Uniqued nodes cannot have self-references");
617 if (Optional<Metadata *> MappedOp = tryToMapOperand(Op)) {
618 AnyChanges |= LocalChanges |= Op != *MappedOp;
619 continue;
620 }
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000621
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000622 MDNode &OpN = *cast<MDNode>(Op);
623 assert(OpN.isUniqued() &&
624 "Only uniqued operands cannot be mapped immediately");
625 if (G.Info.insert(std::make_pair(&OpN, Data())).second)
626 Worklist.push_back(std::make_pair(&OpN, false));
627 }
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000628
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000629 if (LocalChanges)
630 G.Info[&N].HasChanged = true;
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000631 }
632 return AnyChanges;
633}
634
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000635void MDNodeMapper::UniquedGraph::propagateChanges() {
636 bool AnyChanges;
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000637 do {
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000638 AnyChanges = false;
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000639 for (MDNode *N : POT) {
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000640 auto &D = Info[N];
641 if (D.HasChanged)
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000642 continue;
643
644 if (!llvm::any_of(N->operands(), [&](const Metadata *Op) {
645 auto Where = Info.find(Op);
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000646 return Where != Info.end() && Where->second.HasChanged;
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000647 }))
648 continue;
649
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000650 AnyChanges = D.HasChanged = true;
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000651 }
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000652 } while (AnyChanges);
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000653}
654
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000655void MDNodeMapper::mapNodesInPOT(UniquedGraph &G) {
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000656 // Construct uniqued nodes, building forward references as necessary.
Duncan P. N. Exon Smith11f60fd2016-04-13 22:54:01 +0000657 SmallVector<MDNode *, 16> CyclicNodes;
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000658 for (auto *N : G.POT) {
659 auto &D = G.Info[N];
660 if (!D.HasChanged) {
661 // The node hasn't changed.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000662 M.mapToSelf(N);
663 continue;
664 }
665
Duncan P. N. Exon Smith0cb5c342016-04-16 21:09:53 +0000666 // Remember whether this node had a placeholder.
667 bool HadPlaceholder(D.Placeholder);
668
669 // Clone the uniqued node and remap the operands.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000670 TempMDNode ClonedN = D.Placeholder ? std::move(D.Placeholder) : N->clone();
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000671 remapOperands(*ClonedN, [this, &D, &G](Metadata *Old) {
672 if (Optional<Metadata *> MappedOp = getMappedOp(Old))
673 return *MappedOp;
674 assert(G.Info[Old].ID > D.ID && "Expected a forward reference");
675 return &G.getFwdReference(*cast<MDNode>(Old));
676 });
677
Duncan P. N. Exon Smith0cb5c342016-04-16 21:09:53 +0000678 auto *NewN = MDNode::replaceWithUniqued(std::move(ClonedN));
679 M.mapToMetadata(N, NewN);
680
681 // Nodes that were referenced out of order in the POT are involved in a
682 // uniquing cycle.
683 if (HadPlaceholder)
684 CyclicNodes.push_back(NewN);
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000685 }
686
687 // Resolve cycles.
Duncan P. N. Exon Smith11f60fd2016-04-13 22:54:01 +0000688 for (auto *N : CyclicNodes)
Teresa Johnsonb703c772016-03-29 18:24:19 +0000689 if (!N->isResolved())
690 N->resolveCycles();
Duncan P. N. Exon Smithc9fdbdb2015-08-07 00:39:26 +0000691}
692
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000693Metadata *MDNodeMapper::map(const MDNode &N) {
694 assert(DistinctWorklist.empty() && "MDNodeMapper::map is not recursive");
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000695 assert(!(M.Flags & RF_NoModuleLevelChanges) &&
696 "MDNodeMapper::map assumes module-level changes");
Duncan P. N. Exon Smith14cc94c2015-01-14 01:03:05 +0000697
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000698 // Require resolved nodes whenever metadata might be remapped.
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000699 assert(N.isResolved() && "Unexpected unresolved node");
Duncan P. N. Exon Smith920df5c2015-02-04 19:44:34 +0000700
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000701 Metadata *MappedN =
702 N.isUniqued() ? mapTopLevelUniquedNode(N) : mapDistinctNode(N);
703 while (!DistinctWorklist.empty())
704 remapOperands(*DistinctWorklist.pop_back_val(), [this](Metadata *Old) {
705 if (Optional<Metadata *> MappedOp = tryToMapOperand(Old))
706 return *MappedOp;
707 return mapTopLevelUniquedNode(*cast<MDNode>(Old));
708 });
709 return MappedN;
710}
711
712Metadata *MDNodeMapper::mapTopLevelUniquedNode(const MDNode &FirstN) {
713 assert(FirstN.isUniqued() && "Expected uniqued node");
714
715 // Create a post-order traversal of uniqued nodes under FirstN.
716 UniquedGraph G;
717 if (!createPOT(G, FirstN)) {
718 // Return early if no nodes have changed.
719 for (const MDNode *N : G.POT)
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000720 M.mapToSelf(N);
721 return &const_cast<MDNode &>(FirstN);
Duncan P. N. Exon Smith706f37e2015-08-04 06:42:31 +0000722 }
Duncan P. N. Exon Smith0dcffe22015-01-19 22:39:07 +0000723
Duncan P. N. Exon Smith694ab4e2016-04-16 21:44:08 +0000724 // Update graph with all nodes that have changed.
725 G.propagateChanges();
726
727 // Map all the nodes in the graph.
728 mapNodesInPOT(G);
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000729
730 // Return the original node, remapped.
731 return *getMappedOp(&FirstN);
Duncan P. N. Exon Smithb5579892015-01-14 01:06:21 +0000732}
733
Duncan P. N. Exon Smitha77d0732016-04-16 03:39:44 +0000734namespace {
735
736struct MapMetadataDisabler {
737 ValueToValueMapTy &VM;
738
739 MapMetadataDisabler(ValueToValueMapTy &VM) : VM(VM) {
740 VM.disableMapMetadata();
741 }
742 ~MapMetadataDisabler() { VM.enableMapMetadata(); }
743};
744
745} // end namespace
746
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +0000747Optional<Metadata *> Mapper::mapSimpleMetadata(const Metadata *MD) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000748 // If the value already exists in the map, use it.
Duncan P. N. Exon Smithdb6861e2016-04-15 23:18:43 +0000749 if (Optional<Metadata *> NewMD = getVM().getMappedMD(MD))
Duncan P. N. Exon Smithda4a56d2016-04-02 17:04:38 +0000750 return *NewMD;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000751
752 if (isa<MDString>(MD))
Duncan P. N. Exon Smithe05ff7c2016-04-08 18:47:02 +0000753 return const_cast<Metadata *>(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000754
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000755 // This is a module-level metadata. If nothing at the module level is
756 // changing, use an identity mapping.
757 if ((Flags & RF_NoModuleLevelChanges))
Duncan P. N. Exon Smith69341e62016-04-08 18:49:36 +0000758 return const_cast<Metadata *>(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000759
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000760 if (auto *CMD = dyn_cast<ConstantAsMetadata>(MD)) {
Duncan P. N. Exon Smith756e1c32016-04-03 20:54:51 +0000761 // Disallow recursion into metadata mapping through mapValue.
Duncan P. N. Exon Smitha77d0732016-04-16 03:39:44 +0000762 MapMetadataDisabler MMD(getVM());
Duncan P. N. Exon Smith756e1c32016-04-03 20:54:51 +0000763
Duncan P. N. Exon Smitha77d0732016-04-16 03:39:44 +0000764 // Don't memoize ConstantAsMetadata. Instead of lasting until the
765 // LLVMContext is destroyed, they can be deleted when the GlobalValue they
766 // reference is destructed. These aren't super common, so the extra
767 // indirection isn't that expensive.
768 return wrapConstantAsMetadata(*CMD, mapValue(CMD->getValue()));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000769 }
770
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +0000771 assert(isa<MDNode>(MD) && "Expected a metadata node");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000772
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +0000773 return None;
774}
775
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000776Metadata *Mapper::mapLocalAsMetadata(const LocalAsMetadata &LAM) {
777 // Lookup the mapping for the value itself, and return the appropriate
778 // metadata.
779 if (Value *V = mapValue(LAM.getValue())) {
780 if (V == LAM.getValue())
781 return const_cast<LocalAsMetadata *>(&LAM);
782 return ValueAsMetadata::get(V);
783 }
784
785 // FIXME: always return nullptr once Verifier::verifyDominatesUse() ensures
786 // metadata operands only reference defined SSA values.
787 return (Flags & RF_IgnoreMissingLocals)
788 ? nullptr
789 : MDTuple::get(LAM.getContext(), None);
790}
791
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000792Metadata *Mapper::mapMetadata(const Metadata *MD) {
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000793 assert(MD && "Expected valid metadata");
794 assert(!isa<LocalAsMetadata>(MD) && "Unexpected local metadata");
795
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000796 if (Optional<Metadata *> NewMD = mapSimpleMetadata(MD))
797 return *NewMD;
Duncan P. N. Exon Smith920df5c2015-02-04 19:44:34 +0000798
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000799 return MDNodeMapper(*this).map(*cast<MDNode>(MD));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000800}
801
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000802void Mapper::flush() {
803 // Flush out the worklist of global values.
804 while (!Worklist.empty()) {
805 WorklistEntry E = Worklist.pop_back_val();
806 CurrentMCID = E.MCID;
807 switch (E.Kind) {
808 case WorklistEntry::MapGlobalInit:
809 E.Data.GVInit.GV->setInitializer(mapConstant(E.Data.GVInit.Init));
810 break;
811 case WorklistEntry::MapAppendingVar: {
812 unsigned PrefixSize = AppendingInits.size() - E.AppendingGVNumNewMembers;
813 mapAppendingVariable(*E.Data.AppendingGV.GV,
814 E.Data.AppendingGV.InitPrefix,
815 E.AppendingGVIsOldCtorDtor,
816 makeArrayRef(AppendingInits).slice(PrefixSize));
817 AppendingInits.resize(PrefixSize);
818 break;
819 }
820 case WorklistEntry::MapGlobalAliasee:
821 E.Data.GlobalAliasee.GA->setAliasee(
822 mapConstant(E.Data.GlobalAliasee.Aliasee));
823 break;
824 case WorklistEntry::RemapFunction:
825 remapFunction(*E.Data.RemapF);
826 break;
827 }
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000828 }
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000829 CurrentMCID = 0;
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000830
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000831 // Finish logic for block addresses now that all global values have been
832 // handled.
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000833 while (!DelayedBBs.empty()) {
834 DelayedBasicBlock DBB = DelayedBBs.pop_back_val();
835 BasicBlock *BB = cast_or_null<BasicBlock>(mapValue(DBB.OldBB));
836 DBB.TempBB->replaceAllUsesWith(BB ? BB : DBB.OldBB);
837 }
Duncan P. N. Exon Smitha574e7a2016-04-08 19:09:34 +0000838}
839
840void Mapper::remapInstruction(Instruction *I) {
Dan Gohmanca26f792010-08-26 15:41:53 +0000841 // Remap operands.
Davide Italiano96d2a1c2016-04-14 18:07:32 +0000842 for (Use &Op : I->operands()) {
843 Value *V = mapValue(Op);
Chris Lattner43f8d162011-01-08 08:15:20 +0000844 // If we aren't ignoring missing entries, assert that something happened.
Craig Topperf40110f2014-04-25 05:29:35 +0000845 if (V)
Davide Italiano96d2a1c2016-04-14 18:07:32 +0000846 Op = V;
Chris Lattner43f8d162011-01-08 08:15:20 +0000847 else
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000848 assert((Flags & RF_IgnoreMissingLocals) &&
Chris Lattner43f8d162011-01-08 08:15:20 +0000849 "Referenced value not in value map!");
Brian Gaeke6182acf2004-05-19 09:08:12 +0000850 }
Daniel Dunbar95fe13c2010-08-26 03:48:08 +0000851
Jay Foad61ea0e42011-06-23 09:09:15 +0000852 // Remap phi nodes' incoming blocks.
853 if (PHINode *PN = dyn_cast<PHINode>(I)) {
854 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Duncan P. N. Exon Smithadcebdf2016-04-08 19:17:13 +0000855 Value *V = mapValue(PN->getIncomingBlock(i));
Jay Foad61ea0e42011-06-23 09:09:15 +0000856 // If we aren't ignoring missing entries, assert that something happened.
Craig Topperf40110f2014-04-25 05:29:35 +0000857 if (V)
Jay Foad61ea0e42011-06-23 09:09:15 +0000858 PN->setIncomingBlock(i, cast<BasicBlock>(V));
859 else
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000860 assert((Flags & RF_IgnoreMissingLocals) &&
Jay Foad61ea0e42011-06-23 09:09:15 +0000861 "Referenced block not in value map!");
862 }
863 }
864
Devang Patelc0174042011-08-04 20:02:18 +0000865 // Remap attached metadata.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000866 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
Devang Patelc0174042011-08-04 20:02:18 +0000867 I->getAllMetadata(MDs);
Duncan P. N. Exon Smithe08bcbf2015-08-03 03:27:12 +0000868 for (const auto &MI : MDs) {
869 MDNode *Old = MI.second;
Duncan P. N. Exon Smitha574e7a2016-04-08 19:09:34 +0000870 MDNode *New = cast_or_null<MDNode>(mapMetadata(Old));
Dan Gohmanca26f792010-08-26 15:41:53 +0000871 if (New != Old)
Duncan P. N. Exon Smithe08bcbf2015-08-03 03:27:12 +0000872 I->setMetadata(MI.first, New);
Dan Gohmanca26f792010-08-26 15:41:53 +0000873 }
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000874
David Blaikie348de692015-04-23 21:36:23 +0000875 if (!TypeMapper)
876 return;
877
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000878 // If the instruction's type is being remapped, do so now.
David Blaikie348de692015-04-23 21:36:23 +0000879 if (auto CS = CallSite(I)) {
880 SmallVector<Type *, 3> Tys;
881 FunctionType *FTy = CS.getFunctionType();
882 Tys.reserve(FTy->getNumParams());
883 for (Type *Ty : FTy->params())
884 Tys.push_back(TypeMapper->remapType(Ty));
885 CS.mutateFunctionType(FunctionType::get(
886 TypeMapper->remapType(I->getType()), Tys, FTy->isVarArg()));
David Blaikiebf0a42a2015-04-29 23:00:35 +0000887 return;
888 }
889 if (auto *AI = dyn_cast<AllocaInst>(I))
890 AI->setAllocatedType(TypeMapper->remapType(AI->getAllocatedType()));
David Blaikief5147ef2015-06-01 03:09:34 +0000891 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
David Blaikie73cf8722015-05-05 18:03:48 +0000892 GEP->setSourceElementType(
893 TypeMapper->remapType(GEP->getSourceElementType()));
David Blaikief5147ef2015-06-01 03:09:34 +0000894 GEP->setResultElementType(
895 TypeMapper->remapType(GEP->getResultElementType()));
896 }
David Blaikiebf0a42a2015-04-29 23:00:35 +0000897 I->mutateType(TypeMapper->remapType(I->getType()));
Dan Gohmanca26f792010-08-26 15:41:53 +0000898}
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000899
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000900void Mapper::remapFunction(Function &F) {
901 // Remap the operands.
902 for (Use &Op : F.operands())
903 if (Op)
904 Op = mapValue(Op);
905
906 // Remap the metadata attachments.
907 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
908 F.getAllMetadata(MDs);
909 for (const auto &I : MDs)
910 F.setMetadata(I.first, cast_or_null<MDNode>(mapMetadata(I.second)));
911
912 // Remap the argument types.
913 if (TypeMapper)
914 for (Argument &A : F.args())
915 A.mutateType(TypeMapper->remapType(A.getType()));
916
917 // Remap the instructions.
918 for (BasicBlock &BB : F)
919 for (Instruction &I : BB)
920 remapInstruction(&I);
921}
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000922
923void Mapper::mapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
924 bool IsOldCtorDtor,
925 ArrayRef<Constant *> NewMembers) {
926 SmallVector<Constant *, 16> Elements;
927 if (InitPrefix) {
928 unsigned NumElements =
929 cast<ArrayType>(InitPrefix->getType())->getNumElements();
930 for (unsigned I = 0; I != NumElements; ++I)
931 Elements.push_back(InitPrefix->getAggregateElement(I));
932 }
933
934 PointerType *VoidPtrTy;
935 Type *EltTy;
936 if (IsOldCtorDtor) {
937 // FIXME: This upgrade is done during linking to support the C API. See
938 // also IRLinker::linkAppendingVarProto() in IRMover.cpp.
939 VoidPtrTy = Type::getInt8Ty(GV.getContext())->getPointerTo();
940 auto &ST = *cast<StructType>(NewMembers.front()->getType());
941 Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
942 EltTy = StructType::get(GV.getContext(), Tys, false);
943 }
944
945 for (auto *V : NewMembers) {
946 Constant *NewV;
947 if (IsOldCtorDtor) {
948 auto *S = cast<ConstantStruct>(V);
949 auto *E1 = mapValue(S->getOperand(0));
950 auto *E2 = mapValue(S->getOperand(1));
951 Value *Null = Constant::getNullValue(VoidPtrTy);
952 NewV =
953 ConstantStruct::get(cast<StructType>(EltTy), E1, E2, Null, nullptr);
954 } else {
955 NewV = cast_or_null<Constant>(mapValue(V));
956 }
957 Elements.push_back(NewV);
958 }
959
960 GV.setInitializer(ConstantArray::get(
961 cast<ArrayType>(GV.getType()->getElementType()), Elements));
962}
963
964void Mapper::scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init,
965 unsigned MCID) {
966 assert(MCID < MCs.size() && "Invalid mapping context");
967
968 WorklistEntry WE;
969 WE.Kind = WorklistEntry::MapGlobalInit;
970 WE.MCID = MCID;
971 WE.Data.GVInit.GV = &GV;
972 WE.Data.GVInit.Init = &Init;
973 Worklist.push_back(WE);
974}
975
976void Mapper::scheduleMapAppendingVariable(GlobalVariable &GV,
977 Constant *InitPrefix,
978 bool IsOldCtorDtor,
979 ArrayRef<Constant *> NewMembers,
980 unsigned MCID) {
981 assert(MCID < MCs.size() && "Invalid mapping context");
982
983 WorklistEntry WE;
984 WE.Kind = WorklistEntry::MapAppendingVar;
985 WE.MCID = MCID;
986 WE.Data.AppendingGV.GV = &GV;
987 WE.Data.AppendingGV.InitPrefix = InitPrefix;
988 WE.AppendingGVIsOldCtorDtor = IsOldCtorDtor;
989 WE.AppendingGVNumNewMembers = NewMembers.size();
990 Worklist.push_back(WE);
991 AppendingInits.append(NewMembers.begin(), NewMembers.end());
992}
993
994void Mapper::scheduleMapGlobalAliasee(GlobalAlias &GA, Constant &Aliasee,
995 unsigned MCID) {
996 assert(MCID < MCs.size() && "Invalid mapping context");
997
998 WorklistEntry WE;
999 WE.Kind = WorklistEntry::MapGlobalAliasee;
1000 WE.MCID = MCID;
1001 WE.Data.GlobalAliasee.GA = &GA;
1002 WE.Data.GlobalAliasee.Aliasee = &Aliasee;
1003 Worklist.push_back(WE);
1004}
1005
1006void Mapper::scheduleRemapFunction(Function &F, unsigned MCID) {
1007 assert(MCID < MCs.size() && "Invalid mapping context");
1008
1009 WorklistEntry WE;
1010 WE.Kind = WorklistEntry::RemapFunction;
1011 WE.MCID = MCID;
1012 WE.Data.RemapF = &F;
1013 Worklist.push_back(WE);
1014}
1015
1016void Mapper::addFlags(RemapFlags Flags) {
1017 assert(!hasWorkToDo() && "Expected to have flushed the worklist");
1018 this->Flags = this->Flags | Flags;
1019}
1020
1021static Mapper *getAsMapper(void *pImpl) {
1022 return reinterpret_cast<Mapper *>(pImpl);
1023}
1024
1025namespace {
1026
1027class FlushingMapper {
1028 Mapper &M;
1029
1030public:
1031 explicit FlushingMapper(void *pImpl) : M(*getAsMapper(pImpl)) {
1032 assert(!M.hasWorkToDo() && "Expected to be flushed");
1033 }
1034 ~FlushingMapper() { M.flush(); }
1035 Mapper *operator->() const { return &M; }
1036};
1037
1038} // end namespace
1039
1040ValueMapper::ValueMapper(ValueToValueMapTy &VM, RemapFlags Flags,
1041 ValueMapTypeRemapper *TypeMapper,
1042 ValueMaterializer *Materializer)
1043 : pImpl(new Mapper(VM, Flags, TypeMapper, Materializer)) {}
1044
1045ValueMapper::~ValueMapper() { delete getAsMapper(pImpl); }
1046
1047unsigned
1048ValueMapper::registerAlternateMappingContext(ValueToValueMapTy &VM,
1049 ValueMaterializer *Materializer) {
1050 return getAsMapper(pImpl)->registerAlternateMappingContext(VM, Materializer);
1051}
1052
1053void ValueMapper::addFlags(RemapFlags Flags) {
1054 FlushingMapper(pImpl)->addFlags(Flags);
1055}
1056
1057Value *ValueMapper::mapValue(const Value &V) {
1058 return FlushingMapper(pImpl)->mapValue(&V);
1059}
1060
1061Constant *ValueMapper::mapConstant(const Constant &C) {
1062 return cast_or_null<Constant>(mapValue(C));
1063}
1064
1065Metadata *ValueMapper::mapMetadata(const Metadata &MD) {
1066 return FlushingMapper(pImpl)->mapMetadata(&MD);
1067}
1068
1069MDNode *ValueMapper::mapMDNode(const MDNode &N) {
1070 return cast_or_null<MDNode>(mapMetadata(N));
1071}
1072
1073void ValueMapper::remapInstruction(Instruction &I) {
1074 FlushingMapper(pImpl)->remapInstruction(&I);
1075}
1076
1077void ValueMapper::remapFunction(Function &F) {
1078 FlushingMapper(pImpl)->remapFunction(F);
1079}
1080
1081void ValueMapper::scheduleMapGlobalInitializer(GlobalVariable &GV,
1082 Constant &Init,
1083 unsigned MCID) {
1084 getAsMapper(pImpl)->scheduleMapGlobalInitializer(GV, Init, MCID);
1085}
1086
1087void ValueMapper::scheduleMapAppendingVariable(GlobalVariable &GV,
1088 Constant *InitPrefix,
1089 bool IsOldCtorDtor,
1090 ArrayRef<Constant *> NewMembers,
1091 unsigned MCID) {
1092 getAsMapper(pImpl)->scheduleMapAppendingVariable(
1093 GV, InitPrefix, IsOldCtorDtor, NewMembers, MCID);
1094}
1095
1096void ValueMapper::scheduleMapGlobalAliasee(GlobalAlias &GA, Constant &Aliasee,
1097 unsigned MCID) {
1098 getAsMapper(pImpl)->scheduleMapGlobalAliasee(GA, Aliasee, MCID);
1099}
1100
1101void ValueMapper::scheduleRemapFunction(Function &F, unsigned MCID) {
1102 getAsMapper(pImpl)->scheduleRemapFunction(F, MCID);
1103}