1 //===- ValueMapper.cpp - Interface shared by lib/Transforms/Utils ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the MapValue function, which is shared by various parts of
11 // the lib/Transforms/Utils library.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Transforms/Utils/ValueMapper.h"
16 #include "llvm/IR/CallSite.h"
17 #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"
22 #include "llvm/IR/Operator.h"
23 using namespace llvm;
24 
25 // Out of line method to get vtable etc for class.
26 void ValueMapTypeRemapper::anchor() {}
27 void ValueMaterializer::anchor() {}
28 void ValueMaterializer::materializeInitFor(GlobalValue *New, GlobalValue *Old) {
29 }
30 
31 namespace {
32 
33 /// A GlobalValue whose initializer needs to be materialized.
34 struct 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.
43 struct DelayedBasicBlock {
44   BasicBlock *OldBB;
45   std::unique_ptr<BasicBlock> TempBB;
46 
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 
56   DelayedBasicBlock(const BlockAddress &Old)
57       : OldBB(Old.getBasicBlock()),
58         TempBB(BasicBlock::Create(Old.getContext())) {}
59 };
60 
61 class MDNodeMapper;
62 class Mapper {
63   friend class MDNodeMapper;
64 
65   ValueToValueMapTy &VM;
66   RemapFlags Flags;
67   ValueMapTypeRemapper *TypeMapper;
68   ValueMaterializer *Materializer;
69 
70   SmallVector<DelayedGlobalValueInit, 8> DelayedInits;
71   SmallVector<DelayedBasicBlock, 1> DelayedBBs;
72 
73 public:
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   void remapInstruction(Instruction *I);
83   void remapFunction(Function &F);
84 
85   /// Map metadata.
86   ///
87   /// Find the mapping for MD.  Guarantees that the return will be resolved
88   /// (not an MDNode, or MDNode::isResolved() returns true).
89   Metadata *mapMetadata(const Metadata *MD);
90 
91   // Map LocalAsMetadata, which never gets memoized.
92   //
93   // If the referenced local is not mapped, the principled return is nullptr.
94   // However, optimization passes sometimes move metadata operands *before* the
95   // SSA values they reference.  To prevent crashes in \a RemapInstruction(),
96   // return "!{}" when RF_IgnoreMissingLocals is not set.
97   //
98   // \note Adding a mapping for LocalAsMetadata is unsupported.  Add a mapping
99   // to the value map for the SSA value in question instead.
100   //
101   // FIXME: Once we have a verifier check for forward references to SSA values
102   // through metadata operands, always return nullptr on unmapped locals.
103   Metadata *mapLocalAsMetadata(const LocalAsMetadata &LAM);
104 
105 private:
106   Value *mapBlockAddress(const BlockAddress &BA);
107 
108   /// Map metadata that doesn't require visiting operands.
109   Optional<Metadata *> mapSimpleMetadata(const Metadata *MD);
110 
111   Metadata *mapToMetadata(const Metadata *Key, Metadata *Val);
112   Metadata *mapToSelf(const Metadata *MD);
113 };
114 
115 class MDNodeMapper {
116   Mapper &M;
117 
118   struct Data {
119     bool HasChangedOps = false;
120     bool HasChangedAddress = false;
121     unsigned ID = ~0u;
122     TempMDNode Placeholder;
123 
124     Data() {}
125     Data(Data &&X)
126         : HasChangedOps(std::move(X.HasChangedOps)),
127           HasChangedAddress(std::move(X.HasChangedAddress)),
128           ID(std::move(X.ID)), Placeholder(std::move(X.Placeholder)) {}
129     Data &operator=(Data &&X) {
130       HasChangedOps = std::move(X.HasChangedOps);
131       HasChangedAddress = std::move(X.HasChangedAddress);
132       ID = std::move(X.ID);
133       Placeholder = std::move(X.Placeholder);
134       return *this;
135     }
136   };
137 
138   SmallDenseMap<const Metadata *, Data, 32> Info;
139   SmallVector<std::pair<MDNode *, bool>, 16> Worklist;
140   SmallVector<MDNode *, 16> POT;
141 
142 public:
143   MDNodeMapper(Mapper &M) : M(M) {}
144 
145   /// Map a metadata node (and its transitive operands).
146   ///
147   /// This is the only entry point into MDNodeMapper.  It works as follows:
148   ///
149   ///  1. \a createPOT(): use a worklist to perform a post-order traversal of
150   ///     the transitively referenced unmapped nodes.
151   ///
152   ///  2. \a propagateChangedOperands(): track which nodes will change
153   ///     operands, and which will have new addresses in the mapped scheme.
154   ///     Propagate the changes through the POT until fixed point, to pick up
155   ///     uniquing cycles that need to change.
156   ///
157   ///  3. \a mapDistinctNodes(): map all the distinct nodes without touching
158   ///     their operands.  If RF_MoveDistinctMetadata, they get mapped to
159   ///     themselves; otherwise, they get mapped to clones.
160   ///
161   ///  4. \a mapUniquedNodes(): map the uniqued nodes (bottom-up), lazily
162   ///     creating temporaries for forward references as needed.
163   ///
164   ///  5. \a remapDistinctOperands(): remap the operands of the distinct nodes.
165   Metadata *map(const MDNode &FirstN);
166 
167 private:
168   /// Return \c true as long as there's work to do.
169   bool hasWork() const { return !Worklist.empty(); }
170 
171   /// Get the current node in the worklist.
172   MDNode &getCurrentNode() const { return *Worklist.back().first; }
173 
174   /// Push a node onto the worklist.
175   ///
176   /// Adds \c N to \a Worklist and \a Info, unless it's already inserted.  If
177   /// \c N.isDistinct(), \a Data::HasChangedAddress will be set based on \a
178   /// RF_MoveDistinctMDs.
179   ///
180   /// Returns the data for the node.
181   ///
182   /// \post Data::HasChangedAddress iff !RF_MoveDistinctMDs && N.isDistinct().
183   /// \post Worklist.back().first == &N.
184   /// \post Worklist.back().second == false.
185   Data &push(const MDNode &N);
186 
187   /// Map a node operand, and return true if it changes.
188   ///
189   /// \post getMappedOp(Op) does not return None.
190   bool mapOperand(const Metadata *Op);
191 
192   /// Get a previously mapped node.
193   Optional<Metadata *> getMappedOp(const Metadata *Op) const;
194 
195   /// Try to pop a node off the worklist and store it in POT.
196   ///
197   /// Returns \c true if it popped; \c false if its operands need to be
198   /// visited.
199   ///
200   /// \post If Worklist.back().second == false: Worklist.back().second == true.
201   /// \post Else: Worklist.back() has been popped off and added to \a POT.
202   bool tryToPop();
203 
204   /// Get a forward reference to a node to use as an operand.
205   ///
206   /// Returns \c Op if it's not changing; otherwise, lazily creates a temporary
207   /// node and returns it.
208   Metadata &getFwdReference(const Data &D, MDNode &Op);
209 
210   /// Create a post-order traversal from the given node.
211   ///
212   /// This traverses the metadata graph deeply enough to map \c FirstN.  It
213   /// uses \a mapOperand() (indirectly, \a Mapper::mapSimplifiedNode()), so any
214   /// metadata that has already been mapped will not be part of the POT.
215   ///
216   /// \post \a POT is a post-order traversal ending with \c FirstN.
217   bool createPOT(const MDNode &FirstN);
218 
219   /// Propagate changed operands through post-order traversal.
220   ///
221   /// Until fixed point, iteratively update:
222   ///
223   ///   - \a Data::HasChangedOps based on \a Data::HasChangedAddress of operands;
224   ///   - \a Data::HasChangedAddress based on Data::HasChangedOps.
225   ///
226   /// This algorithm never changes \a Data::HasChangedAddress for distinct
227   /// nodes.
228   ///
229   /// \post \a POT is a post-order traversal ending with \c FirstN.
230   void propagateChangedOperands();
231 
232   /// Map all distinct nodes in POT.
233   ///
234   /// \post \a getMappedOp() returns the correct node for every distinct node.
235   void mapDistinctNodes();
236 
237   /// Map all uniqued nodes in POT with the correct operands.
238   ///
239   /// \pre Distinct nodes are mapped (\a mapDistinctNodes() has been called).
240   /// \post \a getMappedOp() returns the correct node for every node.
241   /// \post \a MDNode::operands() is correct for every uniqued node.
242   /// \post \a MDNode::isResolved() returns true for every node.
243   void mapUniquedNodes();
244 
245   /// Re-map the operands for distinct nodes in POT.
246   ///
247   /// \pre Distinct nodes are mapped (\a mapDistinctNodes() has been called).
248   /// \pre Uniqued nodes are mapped (\a mapUniquedNodes() has been called).
249   /// \post \a MDNode::operands() is correct for every distinct node.
250   void remapDistinctOperands();
251 
252   /// Remap a node's operands.
253   ///
254   /// Iterate through operands and update them in place using \a getMappedOp()
255   /// and \a getFwdReference().
256   ///
257   /// \pre N.isDistinct() or N.isTemporary().
258   /// \pre Distinct nodes are mapped (\a mapDistinctNodes() has been called).
259   /// \pre If \c N is distinct, all uniqued nodes are already mapped.
260   void remapOperands(const Data &D, MDNode &N);
261 };
262 
263 } // end namespace
264 
265 Value *llvm::MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags,
266                       ValueMapTypeRemapper *TypeMapper,
267                       ValueMaterializer *Materializer) {
268   return Mapper(VM, Flags, TypeMapper, Materializer).mapValue(V);
269 }
270 
271 Value *Mapper::mapValue(const Value *V) {
272   ValueToValueMapTy::iterator I = VM.find(V);
273 
274   // If the value already exists in the map, use it.
275   if (I != VM.end() && I->second) return I->second;
276 
277   // If we have a materializer and it can materialize a value, use that.
278   if (Materializer) {
279     if (Value *NewV =
280             Materializer->materializeDeclFor(const_cast<Value *>(V))) {
281       VM[V] = NewV;
282       if (auto *NewGV = dyn_cast<GlobalValue>(NewV))
283         DelayedInits.push_back(
284             DelayedGlobalValueInit(cast<GlobalValue>(V), NewGV));
285       return NewV;
286     }
287   }
288 
289   // Global values do not need to be seeded into the VM if they
290   // are using the identity mapping.
291   if (isa<GlobalValue>(V)) {
292     if (Flags & RF_NullMapMissingGlobalValues)
293       return nullptr;
294     return VM[V] = const_cast<Value*>(V);
295   }
296 
297   if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
298     // Inline asm may need *type* remapping.
299     FunctionType *NewTy = IA->getFunctionType();
300     if (TypeMapper) {
301       NewTy = cast<FunctionType>(TypeMapper->remapType(NewTy));
302 
303       if (NewTy != IA->getFunctionType())
304         V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),
305                            IA->hasSideEffects(), IA->isAlignStack());
306     }
307 
308     return VM[V] = const_cast<Value*>(V);
309   }
310 
311   if (const auto *MDV = dyn_cast<MetadataAsValue>(V)) {
312     const Metadata *MD = MDV->getMetadata();
313 
314     if (auto *LAM = dyn_cast<LocalAsMetadata>(MD)) {
315       // Look through to grab the local value.
316       if (Value *LV = mapValue(LAM->getValue())) {
317         if (V == LAM->getValue())
318           return const_cast<Value *>(V);
319         return MetadataAsValue::get(V->getContext(), ValueAsMetadata::get(LV));
320       }
321 
322       // FIXME: always return nullptr once Verifier::verifyDominatesUse()
323       // ensures metadata operands only reference defined SSA values.
324       return (Flags & RF_IgnoreMissingLocals)
325                  ? nullptr
326                  : MetadataAsValue::get(V->getContext(),
327                                         MDTuple::get(V->getContext(), None));
328     }
329 
330     // If this is a module-level metadata and we know that nothing at the module
331     // level is changing, then use an identity mapping.
332     if (Flags & RF_NoModuleLevelChanges)
333       return VM[V] = const_cast<Value *>(V);
334 
335     // Map the metadata and turn it into a value.
336     auto *MappedMD = mapMetadata(MD);
337     if (MD == MappedMD)
338       return VM[V] = const_cast<Value *>(V);
339     return VM[V] = MetadataAsValue::get(V->getContext(), MappedMD);
340   }
341 
342   // Okay, this either must be a constant (which may or may not be mappable) or
343   // is something that is not in the mapping table.
344   Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
345   if (!C)
346     return nullptr;
347 
348   if (BlockAddress *BA = dyn_cast<BlockAddress>(C))
349     return mapBlockAddress(*BA);
350 
351   // Otherwise, we have some other constant to remap.  Start by checking to see
352   // if all operands have an identity remapping.
353   unsigned OpNo = 0, NumOperands = C->getNumOperands();
354   Value *Mapped = nullptr;
355   for (; OpNo != NumOperands; ++OpNo) {
356     Value *Op = C->getOperand(OpNo);
357     Mapped = mapValue(Op);
358     if (Mapped != C) break;
359   }
360 
361   // See if the type mapper wants to remap the type as well.
362   Type *NewTy = C->getType();
363   if (TypeMapper)
364     NewTy = TypeMapper->remapType(NewTy);
365 
366   // If the result type and all operands match up, then just insert an identity
367   // mapping.
368   if (OpNo == NumOperands && NewTy == C->getType())
369     return VM[V] = C;
370 
371   // Okay, we need to create a new constant.  We've already processed some or
372   // all of the operands, set them all up now.
373   SmallVector<Constant*, 8> Ops;
374   Ops.reserve(NumOperands);
375   for (unsigned j = 0; j != OpNo; ++j)
376     Ops.push_back(cast<Constant>(C->getOperand(j)));
377 
378   // If one of the operands mismatch, push it and the other mapped operands.
379   if (OpNo != NumOperands) {
380     Ops.push_back(cast<Constant>(Mapped));
381 
382     // Map the rest of the operands that aren't processed yet.
383     for (++OpNo; OpNo != NumOperands; ++OpNo)
384       Ops.push_back(cast<Constant>(mapValue(C->getOperand(OpNo))));
385   }
386   Type *NewSrcTy = nullptr;
387   if (TypeMapper)
388     if (auto *GEPO = dyn_cast<GEPOperator>(C))
389       NewSrcTy = TypeMapper->remapType(GEPO->getSourceElementType());
390 
391   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
392     return VM[V] = CE->getWithOperands(Ops, NewTy, false, NewSrcTy);
393   if (isa<ConstantArray>(C))
394     return VM[V] = ConstantArray::get(cast<ArrayType>(NewTy), Ops);
395   if (isa<ConstantStruct>(C))
396     return VM[V] = ConstantStruct::get(cast<StructType>(NewTy), Ops);
397   if (isa<ConstantVector>(C))
398     return VM[V] = ConstantVector::get(Ops);
399   // If this is a no-operand constant, it must be because the type was remapped.
400   if (isa<UndefValue>(C))
401     return VM[V] = UndefValue::get(NewTy);
402   if (isa<ConstantAggregateZero>(C))
403     return VM[V] = ConstantAggregateZero::get(NewTy);
404   assert(isa<ConstantPointerNull>(C));
405   return VM[V] = ConstantPointerNull::get(cast<PointerType>(NewTy));
406 }
407 
408 Value *Mapper::mapBlockAddress(const BlockAddress &BA) {
409   Function *F = cast<Function>(mapValue(BA.getFunction()));
410 
411   // F may not have materialized its initializer.  In that case, create a
412   // dummy basic block for now, and replace it once we've materialized all
413   // the initializers.
414   BasicBlock *BB;
415   if (F->empty()) {
416     DelayedBBs.push_back(DelayedBasicBlock(BA));
417     BB = DelayedBBs.back().TempBB.get();
418   } else {
419     BB = cast_or_null<BasicBlock>(mapValue(BA.getBasicBlock()));
420   }
421 
422   return VM[&BA] = BlockAddress::get(F, BB ? BB : BA.getBasicBlock());
423 }
424 
425 Metadata *Mapper::mapToMetadata(const Metadata *Key, Metadata *Val) {
426   VM.MD()[Key].reset(Val);
427   return Val;
428 }
429 
430 Metadata *Mapper::mapToSelf(const Metadata *MD) {
431   return mapToMetadata(MD, const_cast<Metadata *>(MD));
432 }
433 
434 bool MDNodeMapper::mapOperand(const Metadata *Op) {
435   if (!Op)
436     return false;
437 
438   if (Optional<Metadata *> MappedOp = M.mapSimpleMetadata(Op)) {
439     assert((isa<MDString>(Op) || M.VM.getMappedMD(Op)) &&
440            "Expected result to be memoized");
441     return *MappedOp != Op;
442   }
443 
444   return push(*cast<MDNode>(Op)).HasChangedAddress;
445 }
446 
447 Optional<Metadata *> MDNodeMapper::getMappedOp(const Metadata *Op) const {
448   if (!Op)
449     return nullptr;
450 
451   if (Optional<Metadata *> MappedOp = M.VM.getMappedMD(Op))
452     return *MappedOp;
453 
454   if (isa<MDString>(Op))
455     return const_cast<Metadata *>(Op);
456 
457   return None;
458 }
459 
460 Metadata &MDNodeMapper::getFwdReference(const Data &D, MDNode &Op) {
461   auto Where = Info.find(&Op);
462   assert(Where != Info.end() && "Expected a valid reference");
463 
464   auto &OpD = Where->second;
465   assert(OpD.ID > D.ID && "Expected a forward reference");
466 
467   if (!OpD.HasChangedAddress)
468     return Op;
469 
470   // Lazily construct a temporary node.
471   if (!OpD.Placeholder)
472     OpD.Placeholder = Op.clone();
473 
474   return *OpD.Placeholder;
475 }
476 
477 void MDNodeMapper::remapOperands(const Data &D, MDNode &N) {
478   for (unsigned I = 0, E = N.getNumOperands(); I != E; ++I) {
479     Metadata *Old = N.getOperand(I);
480     Metadata *New;
481     if (Optional<Metadata *> MappedOp = getMappedOp(Old)){
482       New = *MappedOp;
483     } else {
484       assert(!N.isDistinct() &&
485              "Expected all nodes to be pre-mapped for distinct operands");
486       MDNode &OldN = *cast<MDNode>(Old);
487       assert(!OldN.isDistinct() && "Expected distinct nodes to be pre-mapped");
488       New = &getFwdReference(D, OldN);
489     }
490 
491     if (Old != New)
492       N.replaceOperandWith(I, New);
493   }
494 }
495 
496 MDNodeMapper::Data &MDNodeMapper::push(const MDNode &N) {
497   auto Insertion = Info.insert(std::make_pair(&N, Data()));
498   auto &D = Insertion.first->second;
499   if (!Insertion.second)
500     return D;
501 
502   // Add to the worklist; check for distinct nodes that are required to be
503   // copied.
504   Worklist.push_back(std::make_pair(&const_cast<MDNode &>(N), false));
505   D.HasChangedAddress = !(M.Flags & RF_MoveDistinctMDs) && N.isDistinct();
506   return D;
507 }
508 
509 bool MDNodeMapper::tryToPop() {
510   if (!Worklist.back().second) {
511     Worklist.back().second = true;
512     return false;
513   }
514 
515   MDNode *N = Worklist.pop_back_val().first;
516   Info[N].ID = POT.size();
517   POT.push_back(N);
518   return true;
519 }
520 
521 bool MDNodeMapper::createPOT(const MDNode &FirstN) {
522   bool AnyChanges = false;
523 
524   // Do a traversal of the unmapped subgraph, tracking whether operands change.
525   // In some cases, these changes will propagate naturally, but
526   // propagateChangedOperands() catches the general case.
527   AnyChanges |= push(FirstN).HasChangedAddress;
528   while (hasWork()) {
529     if (tryToPop())
530       continue;
531 
532     MDNode &N = getCurrentNode();
533     bool LocalChanges = false;
534     for (const Metadata *Op : N.operands())
535       LocalChanges |= mapOperand(Op);
536 
537     if (!LocalChanges)
538       continue;
539 
540     AnyChanges = true;
541     auto &D = Info[&N];
542     D.HasChangedOps = true;
543 
544     // Uniqued nodes change address when operands change.
545     if (!N.isDistinct())
546       D.HasChangedAddress = true;
547   }
548   return AnyChanges;
549 }
550 
551 void MDNodeMapper::propagateChangedOperands() {
552   bool AnyChangedAddresses;
553   do {
554     AnyChangedAddresses = false;
555     for (MDNode *N : POT) {
556       auto &NI = Info[N];
557       if (NI.HasChangedOps)
558         continue;
559 
560       if (!llvm::any_of(N->operands(), [&](const Metadata *Op) {
561             auto Where = Info.find(Op);
562             return Where != Info.end() && Where->second.HasChangedAddress;
563           }))
564         continue;
565 
566       NI.HasChangedOps = true;
567       if (!N->isDistinct()) {
568         NI.HasChangedAddress = true;
569         AnyChangedAddresses = true;
570       }
571     }
572   } while (AnyChangedAddresses);
573 }
574 
575 void MDNodeMapper::mapDistinctNodes() {
576   // Map all the distinct nodes in POT.
577   for (MDNode *N : POT) {
578     if (!N->isDistinct())
579       continue;
580 
581     if (M.Flags & RF_MoveDistinctMDs)
582       M.mapToSelf(N);
583     else
584       M.mapToMetadata(N, MDNode::replaceWithDistinct(N->clone()));
585   }
586 }
587 
588 void MDNodeMapper::mapUniquedNodes() {
589   // Construct uniqued nodes, building forward references as necessary.
590   for (auto *N : POT) {
591     if (N->isDistinct())
592       continue;
593 
594     auto &D = Info[N];
595     assert(D.HasChangedAddress == D.HasChangedOps &&
596            "Uniqued nodes should change address iff ops change");
597     if (!D.HasChangedAddress) {
598       M.mapToSelf(N);
599       continue;
600     }
601 
602     TempMDNode ClonedN = D.Placeholder ? std::move(D.Placeholder) : N->clone();
603     remapOperands(D, *ClonedN);
604     M.mapToMetadata(N, MDNode::replaceWithUniqued(std::move(ClonedN)));
605   }
606 
607   // Resolve cycles.
608   for (auto *N : POT)
609     if (!N->isResolved())
610       N->resolveCycles();
611 }
612 
613 void MDNodeMapper::remapDistinctOperands() {
614   for (auto *N : POT) {
615     if (!N->isDistinct())
616       continue;
617 
618     auto &D = Info[N];
619     if (!D.HasChangedOps)
620       continue;
621 
622     assert(D.HasChangedAddress == !bool(M.Flags & RF_MoveDistinctMDs) &&
623            "Distinct nodes should change address iff they cannot be moved");
624     remapOperands(D, D.HasChangedAddress ? *cast<MDNode>(*getMappedOp(N)) : *N);
625   }
626 }
627 
628 Metadata *MDNodeMapper::map(const MDNode &FirstN) {
629   assert(!(M.Flags & RF_NoModuleLevelChanges) &&
630          "MDNodeMapper::map assumes module-level changes");
631   assert(POT.empty() && "MDNodeMapper::map is not re-entrant");
632 
633   // Require resolved nodes whenever metadata might be remapped.
634   assert(FirstN.isResolved() && "Unexpected unresolved node");
635 
636   // Return early if nothing at all changed.
637   if (!createPOT(FirstN)) {
638     for (const MDNode *N : POT)
639       M.mapToSelf(N);
640     return &const_cast<MDNode &>(FirstN);
641   }
642 
643   propagateChangedOperands();
644   mapDistinctNodes();
645   mapUniquedNodes();
646   remapDistinctOperands();
647 
648   // Return the original node, remapped.
649   return *getMappedOp(&FirstN);
650 }
651 
652 Optional<Metadata *> Mapper::mapSimpleMetadata(const Metadata *MD) {
653   // If the value already exists in the map, use it.
654   if (Optional<Metadata *> NewMD = VM.getMappedMD(MD))
655     return *NewMD;
656 
657   if (isa<MDString>(MD))
658     return const_cast<Metadata *>(MD);
659 
660   // This is a module-level metadata.  If nothing at the module level is
661   // changing, use an identity mapping.
662   if ((Flags & RF_NoModuleLevelChanges))
663     return const_cast<Metadata *>(MD);
664 
665   if (auto *CMD = dyn_cast<ConstantAsMetadata>(MD)) {
666     // Disallow recursion into metadata mapping through mapValue.
667     VM.disableMapMetadata();
668     Value *MappedV = mapValue(CMD->getValue());
669     VM.enableMapMetadata();
670 
671     if (CMD->getValue() == MappedV)
672       return mapToSelf(MD);
673 
674     return mapToMetadata(MD, MappedV ? ValueAsMetadata::get(MappedV) : nullptr);
675   }
676 
677   assert(isa<MDNode>(MD) && "Expected a metadata node");
678 
679   return None;
680 }
681 
682 Metadata *llvm::MapMetadata(const Metadata *MD, ValueToValueMapTy &VM,
683                             RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
684                             ValueMaterializer *Materializer) {
685   return Mapper(VM, Flags, TypeMapper, Materializer).mapMetadata(MD);
686 }
687 
688 Metadata *Mapper::mapLocalAsMetadata(const LocalAsMetadata &LAM) {
689   // Lookup the mapping for the value itself, and return the appropriate
690   // metadata.
691   if (Value *V = mapValue(LAM.getValue())) {
692     if (V == LAM.getValue())
693       return const_cast<LocalAsMetadata *>(&LAM);
694     return ValueAsMetadata::get(V);
695   }
696 
697   // FIXME: always return nullptr once Verifier::verifyDominatesUse() ensures
698   // metadata operands only reference defined SSA values.
699   return (Flags & RF_IgnoreMissingLocals)
700              ? nullptr
701              : MDTuple::get(LAM.getContext(), None);
702 }
703 
704 Metadata *Mapper::mapMetadata(const Metadata *MD) {
705   assert(MD && "Expected valid metadata");
706   assert(!isa<LocalAsMetadata>(MD) && "Unexpected local metadata");
707 
708   if (Optional<Metadata *> NewMD = mapSimpleMetadata(MD))
709     return *NewMD;
710 
711   return MDNodeMapper(*this).map(*cast<MDNode>(MD));
712 }
713 
714 Mapper::~Mapper() {
715   // Materialize global initializers.
716   while (!DelayedInits.empty()) {
717     auto Init = DelayedInits.pop_back_val();
718     Materializer->materializeInitFor(Init.New, Init.Old);
719   }
720 
721   // Process block addresses delayed until global inits.
722   while (!DelayedBBs.empty()) {
723     DelayedBasicBlock DBB = DelayedBBs.pop_back_val();
724     BasicBlock *BB = cast_or_null<BasicBlock>(mapValue(DBB.OldBB));
725     DBB.TempBB->replaceAllUsesWith(BB ? BB : DBB.OldBB);
726   }
727 
728   // We don't expect these to grow after clearing.
729   assert(DelayedInits.empty());
730   assert(DelayedBBs.empty());
731 }
732 
733 MDNode *llvm::MapMetadata(const MDNode *MD, ValueToValueMapTy &VM,
734                           RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
735                           ValueMaterializer *Materializer) {
736   return cast_or_null<MDNode>(MapMetadata(static_cast<const Metadata *>(MD), VM,
737                                           Flags, TypeMapper, Materializer));
738 }
739 
740 void llvm::RemapInstruction(Instruction *I, ValueToValueMapTy &VM,
741                             RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
742                             ValueMaterializer *Materializer) {
743   Mapper(VM, Flags, TypeMapper, Materializer).remapInstruction(I);
744 }
745 
746 void Mapper::remapInstruction(Instruction *I) {
747   // Remap operands.
748   for (User::op_iterator op = I->op_begin(), E = I->op_end(); op != E; ++op) {
749     Value *V = mapValue(*op);
750     // If we aren't ignoring missing entries, assert that something happened.
751     if (V)
752       *op = V;
753     else
754       assert((Flags & RF_IgnoreMissingLocals) &&
755              "Referenced value not in value map!");
756   }
757 
758   // Remap phi nodes' incoming blocks.
759   if (PHINode *PN = dyn_cast<PHINode>(I)) {
760     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
761       Value *V = mapValue(PN->getIncomingBlock(i));
762       // If we aren't ignoring missing entries, assert that something happened.
763       if (V)
764         PN->setIncomingBlock(i, cast<BasicBlock>(V));
765       else
766         assert((Flags & RF_IgnoreMissingLocals) &&
767                "Referenced block not in value map!");
768     }
769   }
770 
771   // Remap attached metadata.
772   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
773   I->getAllMetadata(MDs);
774   for (const auto &MI : MDs) {
775     MDNode *Old = MI.second;
776     MDNode *New = cast_or_null<MDNode>(mapMetadata(Old));
777     if (New != Old)
778       I->setMetadata(MI.first, New);
779   }
780 
781   if (!TypeMapper)
782     return;
783 
784   // If the instruction's type is being remapped, do so now.
785   if (auto CS = CallSite(I)) {
786     SmallVector<Type *, 3> Tys;
787     FunctionType *FTy = CS.getFunctionType();
788     Tys.reserve(FTy->getNumParams());
789     for (Type *Ty : FTy->params())
790       Tys.push_back(TypeMapper->remapType(Ty));
791     CS.mutateFunctionType(FunctionType::get(
792         TypeMapper->remapType(I->getType()), Tys, FTy->isVarArg()));
793     return;
794   }
795   if (auto *AI = dyn_cast<AllocaInst>(I))
796     AI->setAllocatedType(TypeMapper->remapType(AI->getAllocatedType()));
797   if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
798     GEP->setSourceElementType(
799         TypeMapper->remapType(GEP->getSourceElementType()));
800     GEP->setResultElementType(
801         TypeMapper->remapType(GEP->getResultElementType()));
802   }
803   I->mutateType(TypeMapper->remapType(I->getType()));
804 }
805 
806 void llvm::RemapFunction(Function &F, ValueToValueMapTy &VM, RemapFlags Flags,
807                          ValueMapTypeRemapper *TypeMapper,
808                          ValueMaterializer *Materializer) {
809   Mapper(VM, Flags, TypeMapper, Materializer).remapFunction(F);
810 }
811 
812 void Mapper::remapFunction(Function &F) {
813   // Remap the operands.
814   for (Use &Op : F.operands())
815     if (Op)
816       Op = mapValue(Op);
817 
818   // Remap the metadata attachments.
819   SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
820   F.getAllMetadata(MDs);
821   for (const auto &I : MDs)
822     F.setMetadata(I.first, cast_or_null<MDNode>(mapMetadata(I.second)));
823 
824   // Remap the argument types.
825   if (TypeMapper)
826     for (Argument &A : F.args())
827       A.mutateType(TypeMapper->remapType(A.getType()));
828 
829   // Remap the instructions.
830   for (BasicBlock &BB : F)
831     for (Instruction &I : BB)
832       remapInstruction(&I);
833 }
834