blob: 25c90b17d6689177582e8cd22c804a07d586fe35 [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"
18#include "llvm/IR/Function.h"
19#include "llvm/IR/InlineAsm.h"
20#include "llvm/IR/Instructions.h"
21#include "llvm/IR/Metadata.h"
David Blaikie88208842015-08-21 20:16:51 +000022#include "llvm/IR/Operator.h"
Chris Lattnerdf3c3422004-01-09 06:12:26 +000023using namespace llvm;
Chris Lattnere4dbb1a2002-11-20 20:47:41 +000024
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000025// Out of line method to get vtable etc for class.
Craig Topper2a6a08b2012-09-26 06:36:36 +000026void ValueMapTypeRemapper::anchor() {}
James Molloyf6f121e2013-05-28 15:17:05 +000027void ValueMaterializer::anchor() {}
Rafael Espindola19b52382015-11-27 20:28:19 +000028void ValueMaterializer::materializeInitFor(GlobalValue *New, GlobalValue *Old) {
29}
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000030
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +000031namespace {
32
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +000033/// A GlobalValue whose initializer needs to be materialized.
34struct DelayedGlobalValueInit {
35 GlobalValue *Old;
36 GlobalValue *New;
37 DelayedGlobalValueInit(const GlobalValue *Old, GlobalValue *New)
38 : Old(const_cast<GlobalValue *>(Old)), New(New) {}
39};
40
41/// A basic block used in a BlockAddress whose function body is not yet
42/// materialized.
43struct DelayedBasicBlock {
44 BasicBlock *OldBB;
45 std::unique_ptr<BasicBlock> TempBB;
Duncan P. N. Exon Smitha9978562016-04-03 20:42:21 +000046
47 // Explicit move for MSVC.
48 DelayedBasicBlock(DelayedBasicBlock &&X)
49 : OldBB(std::move(X.OldBB)), TempBB(std::move(X.TempBB)) {}
50 DelayedBasicBlock &operator=(DelayedBasicBlock &&X) {
51 OldBB = std::move(X.OldBB);
52 TempBB = std::move(X.TempBB);
53 return *this;
54 }
55
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +000056 DelayedBasicBlock(const BlockAddress &Old)
57 : OldBB(Old.getBasicBlock()),
58 TempBB(BasicBlock::Create(Old.getContext())) {}
59};
60
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +000061class MDNodeMapper;
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +000062class Mapper {
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +000063 friend class MDNodeMapper;
64
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +000065 ValueToValueMapTy &VM;
66 RemapFlags Flags;
67 ValueMapTypeRemapper *TypeMapper;
68 ValueMaterializer *Materializer;
69
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +000070 SmallVector<DelayedGlobalValueInit, 8> DelayedInits;
71 SmallVector<DelayedBasicBlock, 1> DelayedBBs;
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +000072
73public:
74 Mapper(ValueToValueMapTy &VM, RemapFlags Flags,
75 ValueMapTypeRemapper *TypeMapper, ValueMaterializer *Materializer)
76 : VM(VM), Flags(Flags), TypeMapper(TypeMapper),
77 Materializer(Materializer) {}
78
79 ~Mapper();
80
81 Value *mapValue(const Value *V);
82
83 /// Map metadata.
84 ///
85 /// Find the mapping for MD. Guarantees that the return will be resolved
86 /// (not an MDNode, or MDNode::isResolved() returns true).
87 Metadata *mapMetadata(const Metadata *MD);
88
89private:
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +000090 Value *mapBlockAddress(const BlockAddress &BA);
91
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +000092 /// Map metadata that doesn't require visiting operands.
93 Optional<Metadata *> mapSimpleMetadata(const Metadata *MD);
94
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +000095 Metadata *mapToMetadata(const Metadata *Key, Metadata *Val);
96 Metadata *mapToSelf(const Metadata *MD);
97};
98
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +000099class MDNodeMapper {
100 Mapper &M;
101
102 struct Data {
103 bool HasChangedOps = false;
104 bool HasChangedAddress = false;
105 unsigned ID = ~0u;
106 TempMDNode Placeholder;
Duncan P. N. Exon Smithf880d352016-04-05 21:07:01 +0000107
Duncan P. N. Exon Smith818e5f32016-04-05 21:25:33 +0000108 Data() {}
109 Data(Data &&X)
110 : HasChangedOps(std::move(X.HasChangedOps)),
111 HasChangedAddress(std::move(X.HasChangedAddress)),
112 ID(std::move(X.ID)), Placeholder(std::move(X.Placeholder)) {}
113 Data &operator=(Data &&X) {
114 HasChangedOps = std::move(X.HasChangedOps);
115 HasChangedAddress = std::move(X.HasChangedAddress);
116 ID = std::move(X.ID);
117 Placeholder = std::move(X.Placeholder);
118 return *this;
119 }
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000120 };
121
122 SmallDenseMap<const Metadata *, Data, 32> Info;
123 SmallVector<std::pair<MDNode *, bool>, 16> Worklist;
124 SmallVector<MDNode *, 16> POT;
125
126public:
127 MDNodeMapper(Mapper &M) : M(M) {}
128
129 /// Map a metadata node (and its transitive operands).
130 ///
131 /// This is the only entry point into MDNodeMapper. It works as follows:
132 ///
133 /// 1. \a createPOT(): use a worklist to perform a post-order traversal of
134 /// the transitively referenced unmapped nodes.
135 ///
136 /// 2. \a propagateChangedOperands(): track which nodes will change
137 /// operands, and which will have new addresses in the mapped scheme.
138 /// Propagate the changes through the POT until fixed point, to pick up
139 /// uniquing cycles that need to change.
140 ///
141 /// 3. \a mapDistinctNodes(): map all the distinct nodes without touching
142 /// their operands. If RF_MoveDistinctMetadata, they get mapped to
143 /// themselves; otherwise, they get mapped to clones.
144 ///
145 /// 4. \a mapUniquedNodes(): map the uniqued nodes (bottom-up), lazily
146 /// creating temporaries for forward references as needed.
147 ///
148 /// 5. \a remapDistinctOperands(): remap the operands of the distinct nodes.
149 Metadata *map(const MDNode &FirstN);
150
151private:
152 /// Return \c true as long as there's work to do.
153 bool hasWork() const { return !Worklist.empty(); }
154
155 /// Get the current node in the worklist.
156 MDNode &getCurrentNode() const { return *Worklist.back().first; }
157
158 /// Push a node onto the worklist.
159 ///
160 /// Adds \c N to \a Worklist and \a Info, unless it's already inserted. If
161 /// \c N.isDistinct(), \a Data::HasChangedAddress will be set based on \a
162 /// RF_MoveDistinctMDs.
163 ///
164 /// Returns the data for the node.
165 ///
166 /// \post Data::HasChangedAddress iff !RF_MoveDistinctMDs && N.isDistinct().
167 /// \post Worklist.back().first == &N.
168 /// \post Worklist.back().second == false.
169 Data &push(const MDNode &N);
170
171 /// Map a node operand, and return true if it changes.
172 ///
173 /// \post getMappedOp(Op) does not return None.
174 bool mapOperand(const Metadata *Op);
175
176 /// Get a previously mapped node.
177 Optional<Metadata *> getMappedOp(const Metadata *Op) const;
178
179 /// Try to pop a node off the worklist and store it in POT.
180 ///
181 /// Returns \c true if it popped; \c false if its operands need to be
182 /// visited.
183 ///
184 /// \post If Worklist.back().second == false: Worklist.back().second == true.
185 /// \post Else: Worklist.back() has been popped off and added to \a POT.
186 bool tryToPop();
187
188 /// Get a forward reference to a node to use as an operand.
189 ///
190 /// Returns \c Op if it's not changing; otherwise, lazily creates a temporary
191 /// node and returns it.
192 Metadata &getFwdReference(const Data &D, MDNode &Op);
193
194 /// Create a post-order traversal from the given node.
195 ///
196 /// This traverses the metadata graph deeply enough to map \c FirstN. It
197 /// uses \a mapOperand() (indirectly, \a Mapper::mapSimplifiedNode()), so any
198 /// metadata that has already been mapped will not be part of the POT.
199 ///
200 /// \post \a POT is a post-order traversal ending with \c FirstN.
201 bool createPOT(const MDNode &FirstN);
202
203 /// Propagate changed operands through post-order traversal.
204 ///
205 /// Until fixed point, iteratively update:
206 ///
207 /// - \a Data::HasChangedOps based on \a Data::HasChangedAddress of operands;
208 /// - \a Data::HasChangedAddress based on Data::HasChangedOps.
209 ///
210 /// This algorithm never changes \a Data::HasChangedAddress for distinct
211 /// nodes.
212 ///
213 /// \post \a POT is a post-order traversal ending with \c FirstN.
214 void propagateChangedOperands();
215
216 /// Map all distinct nodes in POT.
217 ///
218 /// \post \a getMappedOp() returns the correct node for every distinct node.
219 void mapDistinctNodes();
220
221 /// Map all uniqued nodes in POT with the correct operands.
222 ///
223 /// \pre Distinct nodes are mapped (\a mapDistinctNodes() has been called).
224 /// \post \a getMappedOp() returns the correct node for every node.
225 /// \post \a MDNode::operands() is correct for every uniqued node.
226 /// \post \a MDNode::isResolved() returns true for every node.
227 void mapUniquedNodes();
228
229 /// Re-map the operands for distinct nodes in POT.
230 ///
231 /// \pre Distinct nodes are mapped (\a mapDistinctNodes() has been called).
232 /// \pre Uniqued nodes are mapped (\a mapUniquedNodes() has been called).
233 /// \post \a MDNode::operands() is correct for every distinct node.
234 void remapDistinctOperands();
235
236 /// Remap a node's operands.
237 ///
238 /// Iterate through operands and update them in place using \a getMappedOp()
239 /// and \a getFwdReference().
240 ///
241 /// \pre N.isDistinct() or N.isTemporary().
242 /// \pre Distinct nodes are mapped (\a mapDistinctNodes() has been called).
243 /// \pre If \c N is distinct, all uniqued nodes are already mapped.
244 void remapOperands(const Data &D, MDNode &N);
245};
246
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000247} // end namespace
248
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000249Value *llvm::MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags,
James Molloyf6f121e2013-05-28 15:17:05 +0000250 ValueMapTypeRemapper *TypeMapper,
251 ValueMaterializer *Materializer) {
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000252 return Mapper(VM, Flags, TypeMapper, Materializer).mapValue(V);
253}
254
255Value *Mapper::mapValue(const Value *V) {
Chris Lattner43f8d162011-01-08 08:15:20 +0000256 ValueToValueMapTy::iterator I = VM.find(V);
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000257
Chris Lattner43f8d162011-01-08 08:15:20 +0000258 // If the value already exists in the map, use it.
259 if (I != VM.end() && I->second) return I->second;
260
James Molloyf6f121e2013-05-28 15:17:05 +0000261 // If we have a materializer and it can materialize a value, use that.
262 if (Materializer) {
Rafael Espindola19b52382015-11-27 20:28:19 +0000263 if (Value *NewV =
264 Materializer->materializeDeclFor(const_cast<Value *>(V))) {
265 VM[V] = NewV;
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000266 if (auto *NewGV = dyn_cast<GlobalValue>(NewV))
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000267 DelayedInits.push_back(
268 DelayedGlobalValueInit(cast<GlobalValue>(V), NewGV));
Rafael Espindola19b52382015-11-27 20:28:19 +0000269 return NewV;
270 }
James Molloyf6f121e2013-05-28 15:17:05 +0000271 }
272
Dan Gohmanca26f792010-08-26 15:41:53 +0000273 // Global values do not need to be seeded into the VM if they
274 // are using the identity mapping.
Teresa Johnson83d03dd2015-11-15 14:50:14 +0000275 if (isa<GlobalValue>(V)) {
276 if (Flags & RF_NullMapMissingGlobalValues) {
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000277 // FIXME: Remove this assertion. RF_IgnoreMissingLocals is unrelated to
278 // RF_NullMapMissingGlobalValues.
279 assert(!(Flags & RF_IgnoreMissingLocals) &&
Teresa Johnson83d03dd2015-11-15 14:50:14 +0000280 "Illegal to specify both RF_NullMapMissingGlobalValues and "
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000281 "RF_IgnoreMissingLocals");
Teresa Johnson83d03dd2015-11-15 14:50:14 +0000282 return nullptr;
283 }
Chris Lattner43f8d162011-01-08 08:15:20 +0000284 return VM[V] = const_cast<Value*>(V);
Teresa Johnson83d03dd2015-11-15 14:50:14 +0000285 }
286
Chris Lattner8b4cf5e2011-07-15 23:18:40 +0000287 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
288 // Inline asm may need *type* remapping.
289 FunctionType *NewTy = IA->getFunctionType();
290 if (TypeMapper) {
291 NewTy = cast<FunctionType>(TypeMapper->remapType(NewTy));
292
293 if (NewTy != IA->getFunctionType())
294 V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),
295 IA->hasSideEffects(), IA->isAlignStack());
296 }
297
298 return VM[V] = const_cast<Value*>(V);
299 }
Chris Lattner6aa34b02003-10-06 15:23:43 +0000300
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000301 if (const auto *MDV = dyn_cast<MetadataAsValue>(V)) {
302 const Metadata *MD = MDV->getMetadata();
Chris Lattner43f8d162011-01-08 08:15:20 +0000303 // If this is a module-level metadata and we know that nothing at the module
304 // level is changing, then use an identity mapping.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000305 if (!isa<LocalAsMetadata>(MD) && (Flags & RF_NoModuleLevelChanges))
306 return VM[V] = const_cast<Value *>(V);
Dan Gohmanca26f792010-08-26 15:41:53 +0000307
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000308 // FIXME: be consistent with function-local values for LocalAsMetadata by
309 // returning nullptr when LocalAsMetadata is missing. Adding a mapping is
310 // expensive.
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000311 auto *MappedMD = mapMetadata(MD);
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000312 if (MD == MappedMD || (!MappedMD && (Flags & RF_IgnoreMissingLocals)))
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000313 return VM[V] = const_cast<Value *>(V);
Dan Gohmanca26f792010-08-26 15:41:53 +0000314
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000315 return VM[V] = MetadataAsValue::get(V->getContext(), MappedMD);
Victor Hernandez5fa88d42010-01-20 05:49:59 +0000316 }
317
Chris Lattner43f8d162011-01-08 08:15:20 +0000318 // Okay, this either must be a constant (which may or may not be mappable) or
319 // is something that is not in the mapping table.
Chris Lattnercf5a47d2009-10-29 00:28:30 +0000320 Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
Craig Topperf40110f2014-04-25 05:29:35 +0000321 if (!C)
322 return nullptr;
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000323
324 if (BlockAddress *BA = dyn_cast<BlockAddress>(C))
325 return mapBlockAddress(*BA);
326
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000327 // Otherwise, we have some other constant to remap. Start by checking to see
328 // if all operands have an identity remapping.
329 unsigned OpNo = 0, NumOperands = C->getNumOperands();
Craig Topperf40110f2014-04-25 05:29:35 +0000330 Value *Mapped = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000331 for (; OpNo != NumOperands; ++OpNo) {
332 Value *Op = C->getOperand(OpNo);
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000333 Mapped = mapValue(Op);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000334 if (Mapped != C) break;
Chris Lattnercf5a47d2009-10-29 00:28:30 +0000335 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000336
337 // See if the type mapper wants to remap the type as well.
338 Type *NewTy = C->getType();
339 if (TypeMapper)
340 NewTy = TypeMapper->remapType(NewTy);
Chris Lattner43f8d162011-01-08 08:15:20 +0000341
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000342 // If the result type and all operands match up, then just insert an identity
343 // mapping.
344 if (OpNo == NumOperands && NewTy == C->getType())
345 return VM[V] = C;
346
347 // Okay, we need to create a new constant. We've already processed some or
348 // all of the operands, set them all up now.
349 SmallVector<Constant*, 8> Ops;
350 Ops.reserve(NumOperands);
351 for (unsigned j = 0; j != OpNo; ++j)
352 Ops.push_back(cast<Constant>(C->getOperand(j)));
353
354 // If one of the operands mismatch, push it and the other mapped operands.
355 if (OpNo != NumOperands) {
356 Ops.push_back(cast<Constant>(Mapped));
357
358 // Map the rest of the operands that aren't processed yet.
359 for (++OpNo; OpNo != NumOperands; ++OpNo)
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000360 Ops.push_back(cast<Constant>(mapValue(C->getOperand(OpNo))));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000361 }
David Blaikie88208842015-08-21 20:16:51 +0000362 Type *NewSrcTy = nullptr;
363 if (TypeMapper)
364 if (auto *GEPO = dyn_cast<GEPOperator>(C))
365 NewSrcTy = TypeMapper->remapType(GEPO->getSourceElementType());
366
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000367 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
David Blaikie88208842015-08-21 20:16:51 +0000368 return VM[V] = CE->getWithOperands(Ops, NewTy, false, NewSrcTy);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000369 if (isa<ConstantArray>(C))
370 return VM[V] = ConstantArray::get(cast<ArrayType>(NewTy), Ops);
371 if (isa<ConstantStruct>(C))
372 return VM[V] = ConstantStruct::get(cast<StructType>(NewTy), Ops);
373 if (isa<ConstantVector>(C))
374 return VM[V] = ConstantVector::get(Ops);
375 // If this is a no-operand constant, it must be because the type was remapped.
376 if (isa<UndefValue>(C))
377 return VM[V] = UndefValue::get(NewTy);
378 if (isa<ConstantAggregateZero>(C))
379 return VM[V] = ConstantAggregateZero::get(NewTy);
380 assert(isa<ConstantPointerNull>(C));
381 return VM[V] = ConstantPointerNull::get(cast<PointerType>(NewTy));
Chris Lattnere4dbb1a2002-11-20 20:47:41 +0000382}
Brian Gaeke6182acf2004-05-19 09:08:12 +0000383
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000384Value *Mapper::mapBlockAddress(const BlockAddress &BA) {
385 Function *F = cast<Function>(mapValue(BA.getFunction()));
386
387 // F may not have materialized its initializer. In that case, create a
388 // dummy basic block for now, and replace it once we've materialized all
389 // the initializers.
390 BasicBlock *BB;
Duncan P. N. Exon Smith6f2e3742016-04-06 02:25:12 +0000391 if (F->empty()) {
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000392 DelayedBBs.push_back(DelayedBasicBlock(BA));
393 BB = DelayedBBs.back().TempBB.get();
Duncan P. N. Exon Smith6f2e3742016-04-06 02:25:12 +0000394 } else {
395 BB = cast_or_null<BasicBlock>(mapValue(BA.getBasicBlock()));
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000396 }
397
398 return VM[&BA] = BlockAddress::get(F, BB ? BB : BA.getBasicBlock());
399}
400
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000401Metadata *Mapper::mapToMetadata(const Metadata *Key, Metadata *Val) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000402 VM.MD()[Key].reset(Val);
403 return Val;
404}
405
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000406Metadata *Mapper::mapToSelf(const Metadata *MD) {
407 return mapToMetadata(MD, const_cast<Metadata *>(MD));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000408}
409
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000410bool MDNodeMapper::mapOperand(const Metadata *Op) {
411 if (!Op)
412 return false;
413
414 if (Optional<Metadata *> MappedOp = M.mapSimpleMetadata(Op)) {
415 assert(M.VM.getMappedMD(Op) && "Expected result to be memoized");
416 return *MappedOp != Op;
417 }
418
419 return push(*cast<MDNode>(Op)).HasChangedAddress;
420}
421
422Optional<Metadata *> MDNodeMapper::getMappedOp(const Metadata *Op) const {
Duncan P. N. Exon Smith077affd2015-01-14 01:01:19 +0000423 if (!Op)
424 return nullptr;
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000425
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000426 if (Optional<Metadata *> MappedOp = M.VM.getMappedMD(Op))
427 return *MappedOp;
Duncan P. N. Exon Smith077affd2015-01-14 01:01:19 +0000428
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000429 return None;
Duncan P. N. Exon Smith077affd2015-01-14 01:01:19 +0000430}
431
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000432Metadata &MDNodeMapper::getFwdReference(const Data &D, MDNode &Op) {
433 auto Where = Info.find(&Op);
434 assert(Where != Info.end() && "Expected a valid reference");
435
436 auto &OpD = Where->second;
437 assert(OpD.ID > D.ID && "Expected a forward reference");
438
439 if (!OpD.HasChangedAddress)
440 return Op;
441
442 // Lazily construct a temporary node.
443 if (!OpD.Placeholder)
444 OpD.Placeholder = Op.clone();
445
446 return *OpD.Placeholder;
447}
448
449void MDNodeMapper::remapOperands(const Data &D, MDNode &N) {
450 for (unsigned I = 0, E = N.getNumOperands(); I != E; ++I) {
451 Metadata *Old = N.getOperand(I);
452 Metadata *New;
453 if (Optional<Metadata *> MappedOp = getMappedOp(Old)){
454 New = *MappedOp;
455 } else {
456 assert(!N.isDistinct() &&
457 "Expected all nodes to be pre-mapped for distinct operands");
458 MDNode &OldN = *cast<MDNode>(Old);
459 assert(!OldN.isDistinct() && "Expected distinct nodes to be pre-mapped");
460 New = &getFwdReference(D, OldN);
461 }
462
463 if (Old != New)
464 N.replaceOperandWith(I, New);
465 }
466}
467
468MDNodeMapper::Data &MDNodeMapper::push(const MDNode &N) {
469 auto Insertion = Info.insert(std::make_pair(&N, Data()));
470 auto &D = Insertion.first->second;
471 if (!Insertion.second)
472 return D;
473
474 // Add to the worklist; check for distinct nodes that are required to be
475 // copied.
476 Worklist.push_back(std::make_pair(&const_cast<MDNode &>(N), false));
477 D.HasChangedAddress = !(M.Flags & RF_MoveDistinctMDs) && N.isDistinct();
478 return D;
479}
480
481bool MDNodeMapper::tryToPop() {
482 if (!Worklist.back().second) {
483 Worklist.back().second = true;
484 return false;
485 }
486
487 MDNode *N = Worklist.pop_back_val().first;
488 Info[N].ID = POT.size();
489 POT.push_back(N);
490 return true;
491}
492
493bool MDNodeMapper::createPOT(const MDNode &FirstN) {
494 bool AnyChanges = false;
495
496 // Do a traversal of the unmapped subgraph, tracking whether operands change.
497 // In some cases, these changes will propagate naturally, but
498 // propagateChangedOperands() catches the general case.
499 AnyChanges |= push(FirstN).HasChangedAddress;
500 while (hasWork()) {
501 if (tryToPop())
502 continue;
503
504 MDNode &N = getCurrentNode();
505 bool LocalChanges = false;
506 for (const Metadata *Op : N.operands())
507 LocalChanges |= mapOperand(Op);
508
509 if (!LocalChanges)
510 continue;
511
512 AnyChanges = true;
513 auto &D = Info[&N];
514 D.HasChangedOps = true;
515
516 // Uniqued nodes change address when operands change.
517 if (!N.isDistinct())
518 D.HasChangedAddress = true;
519 }
520 return AnyChanges;
521}
522
523void MDNodeMapper::propagateChangedOperands() {
524 bool AnyChangedAddresses;
525 do {
526 AnyChangedAddresses = false;
527 for (MDNode *N : POT) {
528 auto &NI = Info[N];
529 if (NI.HasChangedOps)
530 continue;
531
532 if (!llvm::any_of(N->operands(), [&](const Metadata *Op) {
533 auto Where = Info.find(Op);
534 return Where != Info.end() && Where->second.HasChangedAddress;
535 }))
536 continue;
537
538 NI.HasChangedOps = true;
539 if (!N->isDistinct()) {
540 NI.HasChangedAddress = true;
541 AnyChangedAddresses = true;
542 }
543 }
544 } while (AnyChangedAddresses);
545}
546
547void MDNodeMapper::mapDistinctNodes() {
548 // Map all the distinct nodes in POT.
549 for (MDNode *N : POT) {
550 if (!N->isDistinct())
551 continue;
552
553 if (M.Flags & RF_MoveDistinctMDs)
554 M.mapToSelf(N);
555 else
556 M.mapToMetadata(N, MDNode::replaceWithDistinct(N->clone()));
557 }
558}
559
560void MDNodeMapper::mapUniquedNodes() {
561 // Construct uniqued nodes, building forward references as necessary.
562 for (auto *N : POT) {
563 if (N->isDistinct())
564 continue;
565
566 auto &D = Info[N];
567 assert(D.HasChangedAddress == D.HasChangedOps &&
568 "Uniqued nodes should change address iff ops change");
569 if (!D.HasChangedAddress) {
570 M.mapToSelf(N);
571 continue;
572 }
573
574 TempMDNode ClonedN = D.Placeholder ? std::move(D.Placeholder) : N->clone();
575 remapOperands(D, *ClonedN);
576 M.mapToMetadata(N, MDNode::replaceWithUniqued(std::move(ClonedN)));
577 }
578
579 // Resolve cycles.
580 for (auto *N : POT)
Teresa Johnsonb703c772016-03-29 18:24:19 +0000581 if (!N->isResolved())
582 N->resolveCycles();
Duncan P. N. Exon Smithc9fdbdb2015-08-07 00:39:26 +0000583}
584
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000585void MDNodeMapper::remapDistinctOperands() {
586 for (auto *N : POT) {
587 if (!N->isDistinct())
588 continue;
Duncan P. N. Exon Smith6dc22bf2015-01-19 22:44:32 +0000589
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000590 auto &D = Info[N];
591 if (!D.HasChangedOps)
592 continue;
Duncan P. N. Exon Smith8c9dcac2015-08-07 00:44:55 +0000593
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000594 assert(D.HasChangedAddress == !bool(M.Flags & RF_MoveDistinctMDs) &&
595 "Distinct nodes should change address iff they cannot be moved");
596 remapOperands(D, D.HasChangedAddress ? *cast<MDNode>(*getMappedOp(N)) : *N);
Duncan P. N. Exon Smith6dc22bf2015-01-19 22:44:32 +0000597 }
Duncan P. N. Exon Smith6dc22bf2015-01-19 22:44:32 +0000598}
599
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000600Metadata *MDNodeMapper::map(const MDNode &FirstN) {
601 assert(!(M.Flags & RF_NoModuleLevelChanges) &&
602 "MDNodeMapper::map assumes module-level changes");
603 assert(POT.empty() && "MDNodeMapper::map is not re-entrant");
Duncan P. N. Exon Smith14cc94c2015-01-14 01:03:05 +0000604
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000605 // Require resolved nodes whenever metadata might be remapped.
606 assert(FirstN.isResolved() && "Unexpected unresolved node");
Duncan P. N. Exon Smith920df5c2015-02-04 19:44:34 +0000607
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000608 // Return early if nothing at all changed.
609 if (!createPOT(FirstN)) {
610 for (const MDNode *N : POT)
611 M.mapToSelf(N);
612 return &const_cast<MDNode &>(FirstN);
Duncan P. N. Exon Smith706f37e2015-08-04 06:42:31 +0000613 }
Duncan P. N. Exon Smith0dcffe22015-01-19 22:39:07 +0000614
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000615 propagateChangedOperands();
616 mapDistinctNodes();
617 mapUniquedNodes();
618 remapDistinctOperands();
619
620 // Return the original node, remapped.
621 return *getMappedOp(&FirstN);
Duncan P. N. Exon Smithb5579892015-01-14 01:06:21 +0000622}
623
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +0000624Optional<Metadata *> Mapper::mapSimpleMetadata(const Metadata *MD) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000625 // If the value already exists in the map, use it.
Duncan P. N. Exon Smithda4a56d2016-04-02 17:04:38 +0000626 if (Optional<Metadata *> NewMD = VM.getMappedMD(MD))
627 return *NewMD;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000628
629 if (isa<MDString>(MD))
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000630 return mapToSelf(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000631
632 if (isa<ConstantAsMetadata>(MD))
633 if ((Flags & RF_NoModuleLevelChanges))
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000634 return mapToSelf(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000635
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000636 // FIXME: Assert that this is not LocalAsMetadata. It should be handled
637 // elsewhere.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000638 if (const auto *VMD = dyn_cast<ValueAsMetadata>(MD)) {
Duncan P. N. Exon Smith756e1c32016-04-03 20:54:51 +0000639 // Disallow recursion into metadata mapping through mapValue.
640 VM.disableMapMetadata();
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000641 Value *MappedV = mapValue(VMD->getValue());
Duncan P. N. Exon Smith756e1c32016-04-03 20:54:51 +0000642 VM.enableMapMetadata();
643
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000644 // FIXME: Always use "ignore" behaviour. There should only be globals here.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000645 if (VMD->getValue() == MappedV ||
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000646 (!MappedV && (Flags & RF_IgnoreMissingLocals)))
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000647 return mapToSelf(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000648
Duncan P. N. Exon Smith8e65f8d2016-04-04 04:59:56 +0000649 return mapToMetadata(MD, MappedV ? ValueAsMetadata::get(MappedV) : nullptr);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000650 }
651
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +0000652 assert(isa<MDNode>(MD) && "Expected a metadata node");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000653
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000654 // If this is a module-level metadata and we know that nothing at the
655 // module level is changing, then use an identity mapping.
656 if (Flags & RF_NoModuleLevelChanges)
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000657 return mapToSelf(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000658
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +0000659 return None;
660}
661
Duncan P. N. Exon Smith46d7af52014-12-19 06:06:18 +0000662Metadata *llvm::MapMetadata(const Metadata *MD, ValueToValueMapTy &VM,
663 RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
664 ValueMaterializer *Materializer) {
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000665 return Mapper(VM, Flags, TypeMapper, Materializer).mapMetadata(MD);
666}
667
668Metadata *Mapper::mapMetadata(const Metadata *MD) {
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000669 // FIXME: First check for and deal with LocalAsMetadata, so that
670 // mapSimpleMetadata() doesn't need to deal with it.
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000671 if (Optional<Metadata *> NewMD = mapSimpleMetadata(MD))
672 return *NewMD;
Duncan P. N. Exon Smith920df5c2015-02-04 19:44:34 +0000673
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000674 return MDNodeMapper(*this).map(*cast<MDNode>(MD));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000675}
676
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000677Mapper::~Mapper() {
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000678 // Materialize global initializers.
679 while (!DelayedInits.empty()) {
680 auto Init = DelayedInits.pop_back_val();
681 Materializer->materializeInitFor(Init.New, Init.Old);
682 }
683
684 // Process block addresses delayed until global inits.
685 while (!DelayedBBs.empty()) {
686 DelayedBasicBlock DBB = DelayedBBs.pop_back_val();
687 BasicBlock *BB = cast_or_null<BasicBlock>(mapValue(DBB.OldBB));
688 DBB.TempBB->replaceAllUsesWith(BB ? BB : DBB.OldBB);
689 }
690
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000691 // We don't expect these to grow after clearing.
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000692 assert(DelayedInits.empty());
693 assert(DelayedBBs.empty());
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000694}
695
Duncan P. N. Exon Smith46d7af52014-12-19 06:06:18 +0000696MDNode *llvm::MapMetadata(const MDNode *MD, ValueToValueMapTy &VM,
697 RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
698 ValueMaterializer *Materializer) {
Duncan P. N. Exon Smithda4a56d2016-04-02 17:04:38 +0000699 return cast_or_null<MDNode>(MapMetadata(static_cast<const Metadata *>(MD), VM,
700 Flags, TypeMapper, Materializer));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000701}
702
Brian Gaeke6182acf2004-05-19 09:08:12 +0000703/// RemapInstruction - Convert the instruction operands from referencing the
Devang Patelb8f11de2010-06-23 23:55:51 +0000704/// current values into those specified by VMap.
Brian Gaeke6182acf2004-05-19 09:08:12 +0000705///
Dan Gohmanca26f792010-08-26 15:41:53 +0000706void llvm::RemapInstruction(Instruction *I, ValueToValueMapTy &VMap,
James Molloyf6f121e2013-05-28 15:17:05 +0000707 RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
708 ValueMaterializer *Materializer){
Dan Gohmanca26f792010-08-26 15:41:53 +0000709 // Remap operands.
Gabor Greif5df43262008-05-30 21:24:22 +0000710 for (User::op_iterator op = I->op_begin(), E = I->op_end(); op != E; ++op) {
James Molloyf6f121e2013-05-28 15:17:05 +0000711 Value *V = MapValue(*op, VMap, Flags, TypeMapper, Materializer);
Chris Lattner43f8d162011-01-08 08:15:20 +0000712 // If we aren't ignoring missing entries, assert that something happened.
Craig Topperf40110f2014-04-25 05:29:35 +0000713 if (V)
Chris Lattner43f8d162011-01-08 08:15:20 +0000714 *op = V;
715 else
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000716 assert((Flags & RF_IgnoreMissingLocals) &&
Chris Lattner43f8d162011-01-08 08:15:20 +0000717 "Referenced value not in value map!");
Brian Gaeke6182acf2004-05-19 09:08:12 +0000718 }
Daniel Dunbar95fe13c2010-08-26 03:48:08 +0000719
Jay Foad61ea0e42011-06-23 09:09:15 +0000720 // Remap phi nodes' incoming blocks.
721 if (PHINode *PN = dyn_cast<PHINode>(I)) {
722 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
723 Value *V = MapValue(PN->getIncomingBlock(i), VMap, Flags);
724 // If we aren't ignoring missing entries, assert that something happened.
Craig Topperf40110f2014-04-25 05:29:35 +0000725 if (V)
Jay Foad61ea0e42011-06-23 09:09:15 +0000726 PN->setIncomingBlock(i, cast<BasicBlock>(V));
727 else
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000728 assert((Flags & RF_IgnoreMissingLocals) &&
Jay Foad61ea0e42011-06-23 09:09:15 +0000729 "Referenced block not in value map!");
730 }
731 }
732
Devang Patelc0174042011-08-04 20:02:18 +0000733 // Remap attached metadata.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000734 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
Devang Patelc0174042011-08-04 20:02:18 +0000735 I->getAllMetadata(MDs);
Duncan P. N. Exon Smithe08bcbf2015-08-03 03:27:12 +0000736 for (const auto &MI : MDs) {
737 MDNode *Old = MI.second;
Duncan P. N. Exon Smith46d7af52014-12-19 06:06:18 +0000738 MDNode *New = MapMetadata(Old, VMap, Flags, TypeMapper, Materializer);
Dan Gohmanca26f792010-08-26 15:41:53 +0000739 if (New != Old)
Duncan P. N. Exon Smithe08bcbf2015-08-03 03:27:12 +0000740 I->setMetadata(MI.first, New);
Dan Gohmanca26f792010-08-26 15:41:53 +0000741 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000742
David Blaikie348de692015-04-23 21:36:23 +0000743 if (!TypeMapper)
744 return;
745
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000746 // If the instruction's type is being remapped, do so now.
David Blaikie348de692015-04-23 21:36:23 +0000747 if (auto CS = CallSite(I)) {
748 SmallVector<Type *, 3> Tys;
749 FunctionType *FTy = CS.getFunctionType();
750 Tys.reserve(FTy->getNumParams());
751 for (Type *Ty : FTy->params())
752 Tys.push_back(TypeMapper->remapType(Ty));
753 CS.mutateFunctionType(FunctionType::get(
754 TypeMapper->remapType(I->getType()), Tys, FTy->isVarArg()));
David Blaikiebf0a42a2015-04-29 23:00:35 +0000755 return;
756 }
757 if (auto *AI = dyn_cast<AllocaInst>(I))
758 AI->setAllocatedType(TypeMapper->remapType(AI->getAllocatedType()));
David Blaikief5147ef2015-06-01 03:09:34 +0000759 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
David Blaikie73cf8722015-05-05 18:03:48 +0000760 GEP->setSourceElementType(
761 TypeMapper->remapType(GEP->getSourceElementType()));
David Blaikief5147ef2015-06-01 03:09:34 +0000762 GEP->setResultElementType(
763 TypeMapper->remapType(GEP->getResultElementType()));
764 }
David Blaikiebf0a42a2015-04-29 23:00:35 +0000765 I->mutateType(TypeMapper->remapType(I->getType()));
Dan Gohmanca26f792010-08-26 15:41:53 +0000766}