blob: c6285de4add057531456d21cd4c2dd48e8a15f53 [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) {
277 assert(!(Flags & RF_IgnoreMissingEntries) &&
278 "Illegal to specify both RF_NullMapMissingGlobalValues and "
279 "RF_IgnoreMissingEntries");
280 return nullptr;
281 }
Chris Lattner43f8d162011-01-08 08:15:20 +0000282 return VM[V] = const_cast<Value*>(V);
Teresa Johnson83d03dd2015-11-15 14:50:14 +0000283 }
284
Chris Lattner8b4cf5e2011-07-15 23:18:40 +0000285 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
286 // Inline asm may need *type* remapping.
287 FunctionType *NewTy = IA->getFunctionType();
288 if (TypeMapper) {
289 NewTy = cast<FunctionType>(TypeMapper->remapType(NewTy));
290
291 if (NewTy != IA->getFunctionType())
292 V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),
293 IA->hasSideEffects(), IA->isAlignStack());
294 }
295
296 return VM[V] = const_cast<Value*>(V);
297 }
Chris Lattner6aa34b02003-10-06 15:23:43 +0000298
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000299 if (const auto *MDV = dyn_cast<MetadataAsValue>(V)) {
300 const Metadata *MD = MDV->getMetadata();
Chris Lattner43f8d162011-01-08 08:15:20 +0000301 // If this is a module-level metadata and we know that nothing at the module
302 // level is changing, then use an identity mapping.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000303 if (!isa<LocalAsMetadata>(MD) && (Flags & RF_NoModuleLevelChanges))
304 return VM[V] = const_cast<Value *>(V);
Dan Gohmanca26f792010-08-26 15:41:53 +0000305
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000306 auto *MappedMD = mapMetadata(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000307 if (MD == MappedMD || (!MappedMD && (Flags & RF_IgnoreMissingEntries)))
308 return VM[V] = const_cast<Value *>(V);
Dan Gohmanca26f792010-08-26 15:41:53 +0000309
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000310 return VM[V] = MetadataAsValue::get(V->getContext(), MappedMD);
Victor Hernandez5fa88d42010-01-20 05:49:59 +0000311 }
312
Chris Lattner43f8d162011-01-08 08:15:20 +0000313 // Okay, this either must be a constant (which may or may not be mappable) or
314 // is something that is not in the mapping table.
Chris Lattnercf5a47d2009-10-29 00:28:30 +0000315 Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
Craig Topperf40110f2014-04-25 05:29:35 +0000316 if (!C)
317 return nullptr;
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000318
319 if (BlockAddress *BA = dyn_cast<BlockAddress>(C))
320 return mapBlockAddress(*BA);
321
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000322 // Otherwise, we have some other constant to remap. Start by checking to see
323 // if all operands have an identity remapping.
324 unsigned OpNo = 0, NumOperands = C->getNumOperands();
Craig Topperf40110f2014-04-25 05:29:35 +0000325 Value *Mapped = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000326 for (; OpNo != NumOperands; ++OpNo) {
327 Value *Op = C->getOperand(OpNo);
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000328 Mapped = mapValue(Op);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000329 if (Mapped != C) break;
Chris Lattnercf5a47d2009-10-29 00:28:30 +0000330 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000331
332 // See if the type mapper wants to remap the type as well.
333 Type *NewTy = C->getType();
334 if (TypeMapper)
335 NewTy = TypeMapper->remapType(NewTy);
Chris Lattner43f8d162011-01-08 08:15:20 +0000336
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000337 // If the result type and all operands match up, then just insert an identity
338 // mapping.
339 if (OpNo == NumOperands && NewTy == C->getType())
340 return VM[V] = C;
341
342 // Okay, we need to create a new constant. We've already processed some or
343 // all of the operands, set them all up now.
344 SmallVector<Constant*, 8> Ops;
345 Ops.reserve(NumOperands);
346 for (unsigned j = 0; j != OpNo; ++j)
347 Ops.push_back(cast<Constant>(C->getOperand(j)));
348
349 // If one of the operands mismatch, push it and the other mapped operands.
350 if (OpNo != NumOperands) {
351 Ops.push_back(cast<Constant>(Mapped));
352
353 // Map the rest of the operands that aren't processed yet.
354 for (++OpNo; OpNo != NumOperands; ++OpNo)
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000355 Ops.push_back(cast<Constant>(mapValue(C->getOperand(OpNo))));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000356 }
David Blaikie88208842015-08-21 20:16:51 +0000357 Type *NewSrcTy = nullptr;
358 if (TypeMapper)
359 if (auto *GEPO = dyn_cast<GEPOperator>(C))
360 NewSrcTy = TypeMapper->remapType(GEPO->getSourceElementType());
361
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000362 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
David Blaikie88208842015-08-21 20:16:51 +0000363 return VM[V] = CE->getWithOperands(Ops, NewTy, false, NewSrcTy);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000364 if (isa<ConstantArray>(C))
365 return VM[V] = ConstantArray::get(cast<ArrayType>(NewTy), Ops);
366 if (isa<ConstantStruct>(C))
367 return VM[V] = ConstantStruct::get(cast<StructType>(NewTy), Ops);
368 if (isa<ConstantVector>(C))
369 return VM[V] = ConstantVector::get(Ops);
370 // If this is a no-operand constant, it must be because the type was remapped.
371 if (isa<UndefValue>(C))
372 return VM[V] = UndefValue::get(NewTy);
373 if (isa<ConstantAggregateZero>(C))
374 return VM[V] = ConstantAggregateZero::get(NewTy);
375 assert(isa<ConstantPointerNull>(C));
376 return VM[V] = ConstantPointerNull::get(cast<PointerType>(NewTy));
Chris Lattnere4dbb1a2002-11-20 20:47:41 +0000377}
Brian Gaeke6182acf2004-05-19 09:08:12 +0000378
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000379Value *Mapper::mapBlockAddress(const BlockAddress &BA) {
380 Function *F = cast<Function>(mapValue(BA.getFunction()));
381
382 // F may not have materialized its initializer. In that case, create a
383 // dummy basic block for now, and replace it once we've materialized all
384 // the initializers.
385 BasicBlock *BB;
386 if (F->isDeclaration()) {
387 BB = cast_or_null<BasicBlock>(mapValue(BA.getBasicBlock()));
388 } else {
389 DelayedBBs.push_back(DelayedBasicBlock(BA));
390 BB = DelayedBBs.back().TempBB.get();
391 }
392
393 return VM[&BA] = BlockAddress::get(F, BB ? BB : BA.getBasicBlock());
394}
395
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000396Metadata *Mapper::mapToMetadata(const Metadata *Key, Metadata *Val) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000397 VM.MD()[Key].reset(Val);
398 return Val;
399}
400
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000401Metadata *Mapper::mapToSelf(const Metadata *MD) {
402 return mapToMetadata(MD, const_cast<Metadata *>(MD));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000403}
404
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000405bool MDNodeMapper::mapOperand(const Metadata *Op) {
406 if (!Op)
407 return false;
408
409 if (Optional<Metadata *> MappedOp = M.mapSimpleMetadata(Op)) {
410 assert(M.VM.getMappedMD(Op) && "Expected result to be memoized");
411 return *MappedOp != Op;
412 }
413
414 return push(*cast<MDNode>(Op)).HasChangedAddress;
415}
416
417Optional<Metadata *> MDNodeMapper::getMappedOp(const Metadata *Op) const {
Duncan P. N. Exon Smith077affd2015-01-14 01:01:19 +0000418 if (!Op)
419 return nullptr;
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000420
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000421 if (Optional<Metadata *> MappedOp = M.VM.getMappedMD(Op))
422 return *MappedOp;
Duncan P. N. Exon Smith077affd2015-01-14 01:01:19 +0000423
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000424 return None;
Duncan P. N. Exon Smith077affd2015-01-14 01:01:19 +0000425}
426
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000427Metadata &MDNodeMapper::getFwdReference(const Data &D, MDNode &Op) {
428 auto Where = Info.find(&Op);
429 assert(Where != Info.end() && "Expected a valid reference");
430
431 auto &OpD = Where->second;
432 assert(OpD.ID > D.ID && "Expected a forward reference");
433
434 if (!OpD.HasChangedAddress)
435 return Op;
436
437 // Lazily construct a temporary node.
438 if (!OpD.Placeholder)
439 OpD.Placeholder = Op.clone();
440
441 return *OpD.Placeholder;
442}
443
444void MDNodeMapper::remapOperands(const Data &D, MDNode &N) {
445 for (unsigned I = 0, E = N.getNumOperands(); I != E; ++I) {
446 Metadata *Old = N.getOperand(I);
447 Metadata *New;
448 if (Optional<Metadata *> MappedOp = getMappedOp(Old)){
449 New = *MappedOp;
450 } else {
451 assert(!N.isDistinct() &&
452 "Expected all nodes to be pre-mapped for distinct operands");
453 MDNode &OldN = *cast<MDNode>(Old);
454 assert(!OldN.isDistinct() && "Expected distinct nodes to be pre-mapped");
455 New = &getFwdReference(D, OldN);
456 }
457
458 if (Old != New)
459 N.replaceOperandWith(I, New);
460 }
461}
462
463MDNodeMapper::Data &MDNodeMapper::push(const MDNode &N) {
464 auto Insertion = Info.insert(std::make_pair(&N, Data()));
465 auto &D = Insertion.first->second;
466 if (!Insertion.second)
467 return D;
468
469 // Add to the worklist; check for distinct nodes that are required to be
470 // copied.
471 Worklist.push_back(std::make_pair(&const_cast<MDNode &>(N), false));
472 D.HasChangedAddress = !(M.Flags & RF_MoveDistinctMDs) && N.isDistinct();
473 return D;
474}
475
476bool MDNodeMapper::tryToPop() {
477 if (!Worklist.back().second) {
478 Worklist.back().second = true;
479 return false;
480 }
481
482 MDNode *N = Worklist.pop_back_val().first;
483 Info[N].ID = POT.size();
484 POT.push_back(N);
485 return true;
486}
487
488bool MDNodeMapper::createPOT(const MDNode &FirstN) {
489 bool AnyChanges = false;
490
491 // Do a traversal of the unmapped subgraph, tracking whether operands change.
492 // In some cases, these changes will propagate naturally, but
493 // propagateChangedOperands() catches the general case.
494 AnyChanges |= push(FirstN).HasChangedAddress;
495 while (hasWork()) {
496 if (tryToPop())
497 continue;
498
499 MDNode &N = getCurrentNode();
500 bool LocalChanges = false;
501 for (const Metadata *Op : N.operands())
502 LocalChanges |= mapOperand(Op);
503
504 if (!LocalChanges)
505 continue;
506
507 AnyChanges = true;
508 auto &D = Info[&N];
509 D.HasChangedOps = true;
510
511 // Uniqued nodes change address when operands change.
512 if (!N.isDistinct())
513 D.HasChangedAddress = true;
514 }
515 return AnyChanges;
516}
517
518void MDNodeMapper::propagateChangedOperands() {
519 bool AnyChangedAddresses;
520 do {
521 AnyChangedAddresses = false;
522 for (MDNode *N : POT) {
523 auto &NI = Info[N];
524 if (NI.HasChangedOps)
525 continue;
526
527 if (!llvm::any_of(N->operands(), [&](const Metadata *Op) {
528 auto Where = Info.find(Op);
529 return Where != Info.end() && Where->second.HasChangedAddress;
530 }))
531 continue;
532
533 NI.HasChangedOps = true;
534 if (!N->isDistinct()) {
535 NI.HasChangedAddress = true;
536 AnyChangedAddresses = true;
537 }
538 }
539 } while (AnyChangedAddresses);
540}
541
542void MDNodeMapper::mapDistinctNodes() {
543 // Map all the distinct nodes in POT.
544 for (MDNode *N : POT) {
545 if (!N->isDistinct())
546 continue;
547
548 if (M.Flags & RF_MoveDistinctMDs)
549 M.mapToSelf(N);
550 else
551 M.mapToMetadata(N, MDNode::replaceWithDistinct(N->clone()));
552 }
553}
554
555void MDNodeMapper::mapUniquedNodes() {
556 // Construct uniqued nodes, building forward references as necessary.
557 for (auto *N : POT) {
558 if (N->isDistinct())
559 continue;
560
561 auto &D = Info[N];
562 assert(D.HasChangedAddress == D.HasChangedOps &&
563 "Uniqued nodes should change address iff ops change");
564 if (!D.HasChangedAddress) {
565 M.mapToSelf(N);
566 continue;
567 }
568
569 TempMDNode ClonedN = D.Placeholder ? std::move(D.Placeholder) : N->clone();
570 remapOperands(D, *ClonedN);
571 M.mapToMetadata(N, MDNode::replaceWithUniqued(std::move(ClonedN)));
572 }
573
574 // Resolve cycles.
575 for (auto *N : POT)
Teresa Johnsonb703c772016-03-29 18:24:19 +0000576 if (!N->isResolved())
577 N->resolveCycles();
Duncan P. N. Exon Smithc9fdbdb2015-08-07 00:39:26 +0000578}
579
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000580void MDNodeMapper::remapDistinctOperands() {
581 for (auto *N : POT) {
582 if (!N->isDistinct())
583 continue;
Duncan P. N. Exon Smith6dc22bf2015-01-19 22:44:32 +0000584
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000585 auto &D = Info[N];
586 if (!D.HasChangedOps)
587 continue;
Duncan P. N. Exon Smith8c9dcac2015-08-07 00:44:55 +0000588
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000589 assert(D.HasChangedAddress == !bool(M.Flags & RF_MoveDistinctMDs) &&
590 "Distinct nodes should change address iff they cannot be moved");
591 remapOperands(D, D.HasChangedAddress ? *cast<MDNode>(*getMappedOp(N)) : *N);
Duncan P. N. Exon Smith6dc22bf2015-01-19 22:44:32 +0000592 }
Duncan P. N. Exon Smith6dc22bf2015-01-19 22:44:32 +0000593}
594
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000595Metadata *MDNodeMapper::map(const MDNode &FirstN) {
596 assert(!(M.Flags & RF_NoModuleLevelChanges) &&
597 "MDNodeMapper::map assumes module-level changes");
598 assert(POT.empty() && "MDNodeMapper::map is not re-entrant");
Duncan P. N. Exon Smith14cc94c2015-01-14 01:03:05 +0000599
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000600 // Require resolved nodes whenever metadata might be remapped.
601 assert(FirstN.isResolved() && "Unexpected unresolved node");
Duncan P. N. Exon Smith920df5c2015-02-04 19:44:34 +0000602
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000603 // Return early if nothing at all changed.
604 if (!createPOT(FirstN)) {
605 for (const MDNode *N : POT)
606 M.mapToSelf(N);
607 return &const_cast<MDNode &>(FirstN);
Duncan P. N. Exon Smith706f37e2015-08-04 06:42:31 +0000608 }
Duncan P. N. Exon Smith0dcffe22015-01-19 22:39:07 +0000609
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000610 propagateChangedOperands();
611 mapDistinctNodes();
612 mapUniquedNodes();
613 remapDistinctOperands();
614
615 // Return the original node, remapped.
616 return *getMappedOp(&FirstN);
Duncan P. N. Exon Smithb5579892015-01-14 01:06:21 +0000617}
618
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +0000619Optional<Metadata *> Mapper::mapSimpleMetadata(const Metadata *MD) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000620 // If the value already exists in the map, use it.
Duncan P. N. Exon Smithda4a56d2016-04-02 17:04:38 +0000621 if (Optional<Metadata *> NewMD = VM.getMappedMD(MD))
622 return *NewMD;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000623
624 if (isa<MDString>(MD))
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000625 return mapToSelf(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000626
627 if (isa<ConstantAsMetadata>(MD))
628 if ((Flags & RF_NoModuleLevelChanges))
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000629 return mapToSelf(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000630
631 if (const auto *VMD = dyn_cast<ValueAsMetadata>(MD)) {
Duncan P. N. Exon Smith756e1c32016-04-03 20:54:51 +0000632 // Disallow recursion into metadata mapping through mapValue.
633 VM.disableMapMetadata();
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000634 Value *MappedV = mapValue(VMD->getValue());
Duncan P. N. Exon Smith756e1c32016-04-03 20:54:51 +0000635 VM.enableMapMetadata();
636
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000637 if (VMD->getValue() == MappedV ||
638 (!MappedV && (Flags & RF_IgnoreMissingEntries)))
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000639 return mapToSelf(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000640
Duncan P. N. Exon Smith8e65f8d2016-04-04 04:59:56 +0000641 return mapToMetadata(MD, MappedV ? ValueAsMetadata::get(MappedV) : nullptr);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000642 }
643
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +0000644 assert(isa<MDNode>(MD) && "Expected a metadata node");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000645
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000646 // If this is a module-level metadata and we know that nothing at the
647 // module level is changing, then use an identity mapping.
648 if (Flags & RF_NoModuleLevelChanges)
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000649 return mapToSelf(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000650
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +0000651 return None;
652}
653
Duncan P. N. Exon Smith46d7af52014-12-19 06:06:18 +0000654Metadata *llvm::MapMetadata(const Metadata *MD, ValueToValueMapTy &VM,
655 RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
656 ValueMaterializer *Materializer) {
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000657 return Mapper(VM, Flags, TypeMapper, Materializer).mapMetadata(MD);
658}
659
660Metadata *Mapper::mapMetadata(const Metadata *MD) {
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000661 if (Optional<Metadata *> NewMD = mapSimpleMetadata(MD))
662 return *NewMD;
Duncan P. N. Exon Smith920df5c2015-02-04 19:44:34 +0000663
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000664 return MDNodeMapper(*this).map(*cast<MDNode>(MD));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000665}
666
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000667Mapper::~Mapper() {
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000668 // Materialize global initializers.
669 while (!DelayedInits.empty()) {
670 auto Init = DelayedInits.pop_back_val();
671 Materializer->materializeInitFor(Init.New, Init.Old);
672 }
673
674 // Process block addresses delayed until global inits.
675 while (!DelayedBBs.empty()) {
676 DelayedBasicBlock DBB = DelayedBBs.pop_back_val();
677 BasicBlock *BB = cast_or_null<BasicBlock>(mapValue(DBB.OldBB));
678 DBB.TempBB->replaceAllUsesWith(BB ? BB : DBB.OldBB);
679 }
680
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000681 // We don't expect these to grow after clearing.
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000682 assert(DelayedInits.empty());
683 assert(DelayedBBs.empty());
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000684}
685
Duncan P. N. Exon Smith46d7af52014-12-19 06:06:18 +0000686MDNode *llvm::MapMetadata(const MDNode *MD, ValueToValueMapTy &VM,
687 RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
688 ValueMaterializer *Materializer) {
Duncan P. N. Exon Smithda4a56d2016-04-02 17:04:38 +0000689 return cast_or_null<MDNode>(MapMetadata(static_cast<const Metadata *>(MD), VM,
690 Flags, TypeMapper, Materializer));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000691}
692
Brian Gaeke6182acf2004-05-19 09:08:12 +0000693/// RemapInstruction - Convert the instruction operands from referencing the
Devang Patelb8f11de2010-06-23 23:55:51 +0000694/// current values into those specified by VMap.
Brian Gaeke6182acf2004-05-19 09:08:12 +0000695///
Dan Gohmanca26f792010-08-26 15:41:53 +0000696void llvm::RemapInstruction(Instruction *I, ValueToValueMapTy &VMap,
James Molloyf6f121e2013-05-28 15:17:05 +0000697 RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
698 ValueMaterializer *Materializer){
Dan Gohmanca26f792010-08-26 15:41:53 +0000699 // Remap operands.
Gabor Greif5df43262008-05-30 21:24:22 +0000700 for (User::op_iterator op = I->op_begin(), E = I->op_end(); op != E; ++op) {
James Molloyf6f121e2013-05-28 15:17:05 +0000701 Value *V = MapValue(*op, VMap, Flags, TypeMapper, Materializer);
Chris Lattner43f8d162011-01-08 08:15:20 +0000702 // If we aren't ignoring missing entries, assert that something happened.
Craig Topperf40110f2014-04-25 05:29:35 +0000703 if (V)
Chris Lattner43f8d162011-01-08 08:15:20 +0000704 *op = V;
705 else
706 assert((Flags & RF_IgnoreMissingEntries) &&
707 "Referenced value not in value map!");
Brian Gaeke6182acf2004-05-19 09:08:12 +0000708 }
Daniel Dunbar95fe13c2010-08-26 03:48:08 +0000709
Jay Foad61ea0e42011-06-23 09:09:15 +0000710 // Remap phi nodes' incoming blocks.
711 if (PHINode *PN = dyn_cast<PHINode>(I)) {
712 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
713 Value *V = MapValue(PN->getIncomingBlock(i), VMap, Flags);
714 // If we aren't ignoring missing entries, assert that something happened.
Craig Topperf40110f2014-04-25 05:29:35 +0000715 if (V)
Jay Foad61ea0e42011-06-23 09:09:15 +0000716 PN->setIncomingBlock(i, cast<BasicBlock>(V));
717 else
718 assert((Flags & RF_IgnoreMissingEntries) &&
719 "Referenced block not in value map!");
720 }
721 }
722
Devang Patelc0174042011-08-04 20:02:18 +0000723 // Remap attached metadata.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000724 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
Devang Patelc0174042011-08-04 20:02:18 +0000725 I->getAllMetadata(MDs);
Duncan P. N. Exon Smithe08bcbf2015-08-03 03:27:12 +0000726 for (const auto &MI : MDs) {
727 MDNode *Old = MI.second;
Duncan P. N. Exon Smith46d7af52014-12-19 06:06:18 +0000728 MDNode *New = MapMetadata(Old, VMap, Flags, TypeMapper, Materializer);
Dan Gohmanca26f792010-08-26 15:41:53 +0000729 if (New != Old)
Duncan P. N. Exon Smithe08bcbf2015-08-03 03:27:12 +0000730 I->setMetadata(MI.first, New);
Dan Gohmanca26f792010-08-26 15:41:53 +0000731 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000732
David Blaikie348de692015-04-23 21:36:23 +0000733 if (!TypeMapper)
734 return;
735
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000736 // If the instruction's type is being remapped, do so now.
David Blaikie348de692015-04-23 21:36:23 +0000737 if (auto CS = CallSite(I)) {
738 SmallVector<Type *, 3> Tys;
739 FunctionType *FTy = CS.getFunctionType();
740 Tys.reserve(FTy->getNumParams());
741 for (Type *Ty : FTy->params())
742 Tys.push_back(TypeMapper->remapType(Ty));
743 CS.mutateFunctionType(FunctionType::get(
744 TypeMapper->remapType(I->getType()), Tys, FTy->isVarArg()));
David Blaikiebf0a42a2015-04-29 23:00:35 +0000745 return;
746 }
747 if (auto *AI = dyn_cast<AllocaInst>(I))
748 AI->setAllocatedType(TypeMapper->remapType(AI->getAllocatedType()));
David Blaikief5147ef2015-06-01 03:09:34 +0000749 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
David Blaikie73cf8722015-05-05 18:03:48 +0000750 GEP->setSourceElementType(
751 TypeMapper->remapType(GEP->getSourceElementType()));
David Blaikief5147ef2015-06-01 03:09:34 +0000752 GEP->setResultElementType(
753 TypeMapper->remapType(GEP->getResultElementType()));
754 }
David Blaikiebf0a42a2015-04-29 23:00:35 +0000755 I->mutateType(TypeMapper->remapType(I->getType()));
Dan Gohmanca26f792010-08-26 15:41:53 +0000756}