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/ADT/DenseSet.h"
17 #include "llvm/IR/CallSite.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DebugInfoMetadata.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/GlobalAlias.h"
22 #include "llvm/IR/GlobalVariable.h"
23 #include "llvm/IR/InlineAsm.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/Metadata.h"
26 #include "llvm/IR/Operator.h"
27 using namespace llvm;
28 
29 // Out of line method to get vtable etc for class.
30 void ValueMapTypeRemapper::anchor() {}
31 void ValueMaterializer::anchor() {}
32 
33 namespace {
34 
35 /// A basic block used in a BlockAddress whose function body is not yet
36 /// materialized.
37 struct DelayedBasicBlock {
38   BasicBlock *OldBB;
39   std::unique_ptr<BasicBlock> TempBB;
40 
41   // Explicit move for MSVC.
42   DelayedBasicBlock(DelayedBasicBlock &&X)
43       : OldBB(std::move(X.OldBB)), TempBB(std::move(X.TempBB)) {}
44   DelayedBasicBlock &operator=(DelayedBasicBlock &&X) {
45     OldBB = std::move(X.OldBB);
46     TempBB = std::move(X.TempBB);
47     return *this;
48   }
49 
50   DelayedBasicBlock(const BlockAddress &Old)
51       : OldBB(Old.getBasicBlock()),
52         TempBB(BasicBlock::Create(Old.getContext())) {}
53 };
54 
55 struct WorklistEntry {
56   enum EntryKind {
57     MapGlobalInit,
58     MapAppendingVar,
59     MapGlobalAliasee,
60     RemapFunction
61   };
62   struct GVInitTy {
63     GlobalVariable *GV;
64     Constant *Init;
65   };
66   struct AppendingGVTy {
67     GlobalVariable *GV;
68     Constant *InitPrefix;
69   };
70   struct GlobalAliaseeTy {
71     GlobalAlias *GA;
72     Constant *Aliasee;
73   };
74 
75   unsigned Kind : 2;
76   unsigned MCID : 29;
77   unsigned AppendingGVIsOldCtorDtor : 1;
78   unsigned AppendingGVNumNewMembers;
79   union {
80     GVInitTy GVInit;
81     AppendingGVTy AppendingGV;
82     GlobalAliaseeTy GlobalAliasee;
83     Function *RemapF;
84   } Data;
85 };
86 
87 struct MappingContext {
88   ValueToValueMapTy *VM;
89   ValueMaterializer *Materializer = nullptr;
90 
91   /// Construct a MappingContext with a value map and materializer.
92   explicit MappingContext(ValueToValueMapTy &VM,
93                           ValueMaterializer *Materializer = nullptr)
94       : VM(&VM), Materializer(Materializer) {}
95 };
96 
97 class MDNodeMapper;
98 class Mapper {
99   friend class MDNodeMapper;
100 
101 #ifndef NDEBUG
102   DenseSet<GlobalValue *> AlreadyScheduled;
103 #endif
104 
105   RemapFlags Flags;
106   ValueMapTypeRemapper *TypeMapper;
107   unsigned CurrentMCID = 0;
108   SmallVector<MappingContext, 2> MCs;
109   SmallVector<WorklistEntry, 4> Worklist;
110   SmallVector<DelayedBasicBlock, 1> DelayedBBs;
111   SmallVector<Constant *, 16> AppendingInits;
112 
113 public:
114   Mapper(ValueToValueMapTy &VM, RemapFlags Flags,
115          ValueMapTypeRemapper *TypeMapper, ValueMaterializer *Materializer)
116       : Flags(Flags), TypeMapper(TypeMapper),
117         MCs(1, MappingContext(VM, Materializer)) {}
118 
119   /// ValueMapper should explicitly call \a flush() before destruction.
120   ~Mapper() { assert(!hasWorkToDo() && "Expected to be flushed"); }
121 
122   bool hasWorkToDo() const { return !Worklist.empty(); }
123 
124   unsigned
125   registerAlternateMappingContext(ValueToValueMapTy &VM,
126                                   ValueMaterializer *Materializer = nullptr) {
127     MCs.push_back(MappingContext(VM, Materializer));
128     return MCs.size() - 1;
129   }
130 
131   void addFlags(RemapFlags Flags);
132 
133   Value *mapValue(const Value *V);
134   void remapInstruction(Instruction *I);
135   void remapFunction(Function &F);
136 
137   Constant *mapConstant(const Constant *C) {
138     return cast_or_null<Constant>(mapValue(C));
139   }
140 
141   /// Map metadata.
142   ///
143   /// Find the mapping for MD.  Guarantees that the return will be resolved
144   /// (not an MDNode, or MDNode::isResolved() returns true).
145   Metadata *mapMetadata(const Metadata *MD);
146 
147   // Map LocalAsMetadata, which never gets memoized.
148   //
149   // If the referenced local is not mapped, the principled return is nullptr.
150   // However, optimization passes sometimes move metadata operands *before* the
151   // SSA values they reference.  To prevent crashes in \a RemapInstruction(),
152   // return "!{}" when RF_IgnoreMissingLocals is not set.
153   //
154   // \note Adding a mapping for LocalAsMetadata is unsupported.  Add a mapping
155   // to the value map for the SSA value in question instead.
156   //
157   // FIXME: Once we have a verifier check for forward references to SSA values
158   // through metadata operands, always return nullptr on unmapped locals.
159   Metadata *mapLocalAsMetadata(const LocalAsMetadata &LAM);
160 
161   void scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init,
162                                     unsigned MCID);
163   void scheduleMapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
164                                     bool IsOldCtorDtor,
165                                     ArrayRef<Constant *> NewMembers,
166                                     unsigned MCID);
167   void scheduleMapGlobalAliasee(GlobalAlias &GA, Constant &Aliasee,
168                                 unsigned MCID);
169   void scheduleRemapFunction(Function &F, unsigned MCID);
170 
171   void flush();
172 
173 private:
174   void mapGlobalInitializer(GlobalVariable &GV, Constant &Init);
175   void mapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
176                             bool IsOldCtorDtor,
177                             ArrayRef<Constant *> NewMembers);
178   void mapGlobalAliasee(GlobalAlias &GA, Constant &Aliasee);
179   void remapFunction(Function &F, ValueToValueMapTy &VM);
180 
181   ValueToValueMapTy &getVM() { return *MCs[CurrentMCID].VM; }
182   ValueMaterializer *getMaterializer() { return MCs[CurrentMCID].Materializer; }
183 
184   Value *mapBlockAddress(const BlockAddress &BA);
185 
186   /// Map metadata that doesn't require visiting operands.
187   Optional<Metadata *> mapSimpleMetadata(const Metadata *MD);
188 
189   Metadata *mapToMetadata(const Metadata *Key, Metadata *Val);
190   Metadata *mapToSelf(const Metadata *MD);
191 };
192 
193 class MDNodeMapper {
194   Mapper &M;
195 
196   /// Data about a node in \a UniquedGraph.
197   struct Data {
198     bool HasChanged = false;
199     unsigned ID = ~0u;
200     TempMDNode Placeholder;
201 
202     Data() {}
203     Data(Data &&X)
204         : HasChanged(std::move(X.HasChanged)), ID(std::move(X.ID)),
205           Placeholder(std::move(X.Placeholder)) {}
206     Data &operator=(Data &&X) {
207       HasChanged = std::move(X.HasChanged);
208       ID = std::move(X.ID);
209       Placeholder = std::move(X.Placeholder);
210       return *this;
211     }
212   };
213 
214   /// A graph of uniqued nodes.
215   struct UniquedGraph {
216     SmallDenseMap<const Metadata *, Data, 32> Info; // Node properties.
217     SmallVector<MDNode *, 16> POT;                  // Post-order traversal.
218 
219     /// Propagate changed operands through the post-order traversal.
220     ///
221     /// Iteratively update \a Data::HasChanged for each node based on \a
222     /// Data::HasChanged of its operands, until fixed point.
223     void propagateChanges();
224 
225     /// Get a forward reference to a node to use as an operand.
226     Metadata &getFwdReference(MDNode &Op);
227   };
228 
229   /// Worklist of distinct nodes whose operands need to be remapped.
230   SmallVector<MDNode *, 16> DistinctWorklist;
231 
232   // Storage for a UniquedGraph.
233   SmallDenseMap<const Metadata *, Data, 32> InfoStorage;
234   SmallVector<MDNode *, 16> POTStorage;
235 
236 public:
237   MDNodeMapper(Mapper &M) : M(M) {}
238 
239   /// Map a metadata node (and its transitive operands).
240   ///
241   /// Map all the (unmapped) nodes in the subgraph under \c N.  The iterative
242   /// algorithm handles distinct nodes and uniqued node subgraphs using
243   /// different strategies.
244   ///
245   /// Distinct nodes are immediately mapped and added to \a DistinctWorklist
246   /// using \a mapDistinctNode().  Their mapping can always be computed
247   /// immediately without visiting operands, even if their operands change.
248   ///
249   /// The mapping for uniqued nodes depends on whether their operands change.
250   /// \a mapTopLevelUniquedNode() traverses the transitive uniqued subgraph of
251   /// a node to calculate uniqued node mappings in bulk.  Distinct leafs are
252   /// added to \a DistinctWorklist with \a mapDistinctNode().
253   ///
254   /// After mapping \c N itself, this function remaps the operands of the
255   /// distinct nodes in \a DistinctWorklist until the entire subgraph under \c
256   /// N has been mapped.
257   Metadata *map(const MDNode &N);
258 
259 private:
260   /// Map a top-level uniqued node and the uniqued subgraph underneath it.
261   ///
262   /// This builds up a post-order traversal of the (unmapped) uniqued subgraph
263   /// underneath \c FirstN and calculates the nodes' mapping.  Each node uses
264   /// the identity mapping (\a Mapper::mapToSelf()) as long as all of its
265   /// operands uses the identity mapping.
266   ///
267   /// The algorithm works as follows:
268   ///
269   ///  1. \a createPOT(): traverse the uniqued subgraph under \c FirstN and
270   ///     save the post-order traversal in the given \a UniquedGraph, tracking
271   ///     nodes' operands change.
272   ///
273   ///  2. \a UniquedGraph::propagateChanges(): propagate changed operands
274   ///     through the \a UniquedGraph until fixed point, following the rule
275   ///     that if a node changes, any node that references must also change.
276   ///
277   ///  3. \a mapNodesInPOT(): map the uniqued nodes, creating new uniqued nodes
278   ///     (referencing new operands) where necessary.
279   Metadata *mapTopLevelUniquedNode(const MDNode &FirstN);
280 
281   /// Try to map the operand of an \a MDNode.
282   ///
283   /// If \c Op is already mapped, return the mapping.  If it's not an \a
284   /// MDNode, compute and return the mapping.  If it's a distinct \a MDNode,
285   /// return the result of \a mapDistinctNode().
286   ///
287   /// \return None if \c Op is an unmapped uniqued \a MDNode.
288   /// \post getMappedOp(Op) only returns None if this returns None.
289   Optional<Metadata *> tryToMapOperand(const Metadata *Op);
290 
291   /// Map a distinct node.
292   ///
293   /// Return the mapping for the distinct node \c N, saving the result in \a
294   /// DistinctWorklist for later remapping.
295   ///
296   /// \pre \c N is not yet mapped.
297   /// \pre \c N.isDistinct().
298   MDNode *mapDistinctNode(const MDNode &N);
299 
300   /// Get a previously mapped node.
301   Optional<Metadata *> getMappedOp(const Metadata *Op) const;
302 
303   /// Create a post-order traversal of an unmapped uniqued node subgraph.
304   ///
305   /// This traverses the metadata graph deeply enough to map \c FirstN.  It
306   /// uses \a tryToMapOperand() (via \a Mapper::mapSimplifiedNode()), so any
307   /// metadata that has already been mapped will not be part of the POT.
308   ///
309   /// Each node that has a changed operand from outside the graph (e.g., a
310   /// distinct node, an already-mapped uniqued node, or \a ConstantAsMetadata)
311   /// is marked with \a Data::HasChanged.
312   ///
313   /// \return \c true if any nodes in \c G have \a Data::HasChanged.
314   /// \post \c G.POT is a post-order traversal ending with \c FirstN.
315   /// \post \a Data::hasChanged in \c G.Info indicates whether any node needs
316   /// to change because of operands outside the graph.
317   bool createPOT(UniquedGraph &G, const MDNode &FirstN);
318 
319   /// Visit the operands of a uniqued node in the POT.
320   ///
321   /// Visit the operands in the range from \c I to \c E, returning the first
322   /// uniqued node we find that isn't yet in \c G.  \c I is always advanced to
323   /// where to continue the loop through the operands.
324   ///
325   /// This sets \c HasChanged if any of the visited operands change.
326   MDNode *visitOperands(UniquedGraph &G, MDNode::op_iterator &I,
327                         MDNode::op_iterator E, bool &HasChanged);
328 
329   /// Map all the nodes in the given uniqued graph.
330   ///
331   /// This visits all the nodes in \c G in post-order, using the identity
332   /// mapping or creating a new node depending on \a Data::HasChanged.
333   ///
334   /// \pre \a getMappedOp() returns None for nodes in \c G, but not for any of
335   /// their operands outside of \c G.
336   /// \pre \a Data::HasChanged is true for a node in \c G iff any of its
337   /// operands have changed.
338   /// \post \a getMappedOp() returns the mapped node for every node in \c G.
339   void mapNodesInPOT(UniquedGraph &G);
340 
341   /// Remap a node's operands using the given functor.
342   ///
343   /// Iterate through the operands of \c N and update them in place using \c
344   /// mapOperand.
345   ///
346   /// \pre N.isDistinct() or N.isTemporary().
347   template <class OperandMapper>
348   void remapOperands(MDNode &N, OperandMapper mapOperand);
349 };
350 
351 } // end namespace
352 
353 Value *Mapper::mapValue(const Value *V) {
354   ValueToValueMapTy::iterator I = getVM().find(V);
355 
356   // If the value already exists in the map, use it.
357   if (I != getVM().end()) {
358     assert(I->second && "Unexpected null mapping");
359     return I->second;
360   }
361 
362   // If we have a materializer and it can materialize a value, use that.
363   if (auto *Materializer = getMaterializer()) {
364     if (Value *NewV = Materializer->materialize(const_cast<Value *>(V))) {
365       getVM()[V] = NewV;
366       return NewV;
367     }
368   }
369 
370   // Global values do not need to be seeded into the VM if they
371   // are using the identity mapping.
372   if (isa<GlobalValue>(V)) {
373     if (Flags & RF_NullMapMissingGlobalValues)
374       return nullptr;
375     return getVM()[V] = const_cast<Value *>(V);
376   }
377 
378   if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
379     // Inline asm may need *type* remapping.
380     FunctionType *NewTy = IA->getFunctionType();
381     if (TypeMapper) {
382       NewTy = cast<FunctionType>(TypeMapper->remapType(NewTy));
383 
384       if (NewTy != IA->getFunctionType())
385         V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),
386                            IA->hasSideEffects(), IA->isAlignStack());
387     }
388 
389     return getVM()[V] = const_cast<Value *>(V);
390   }
391 
392   if (const auto *MDV = dyn_cast<MetadataAsValue>(V)) {
393     const Metadata *MD = MDV->getMetadata();
394 
395     if (auto *LAM = dyn_cast<LocalAsMetadata>(MD)) {
396       // Look through to grab the local value.
397       if (Value *LV = mapValue(LAM->getValue())) {
398         if (V == LAM->getValue())
399           return const_cast<Value *>(V);
400         return MetadataAsValue::get(V->getContext(), ValueAsMetadata::get(LV));
401       }
402 
403       // FIXME: always return nullptr once Verifier::verifyDominatesUse()
404       // ensures metadata operands only reference defined SSA values.
405       return (Flags & RF_IgnoreMissingLocals)
406                  ? nullptr
407                  : MetadataAsValue::get(V->getContext(),
408                                         MDTuple::get(V->getContext(), None));
409     }
410 
411     // If this is a module-level metadata and we know that nothing at the module
412     // level is changing, then use an identity mapping.
413     if (Flags & RF_NoModuleLevelChanges)
414       return getVM()[V] = const_cast<Value *>(V);
415 
416     // Map the metadata and turn it into a value.
417     auto *MappedMD = mapMetadata(MD);
418     if (MD == MappedMD)
419       return getVM()[V] = const_cast<Value *>(V);
420     return getVM()[V] = MetadataAsValue::get(V->getContext(), MappedMD);
421   }
422 
423   // Okay, this either must be a constant (which may or may not be mappable) or
424   // is something that is not in the mapping table.
425   Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
426   if (!C)
427     return nullptr;
428 
429   if (BlockAddress *BA = dyn_cast<BlockAddress>(C))
430     return mapBlockAddress(*BA);
431 
432   // Otherwise, we have some other constant to remap.  Start by checking to see
433   // if all operands have an identity remapping.
434   unsigned OpNo = 0, NumOperands = C->getNumOperands();
435   Value *Mapped = nullptr;
436   for (; OpNo != NumOperands; ++OpNo) {
437     Value *Op = C->getOperand(OpNo);
438     Mapped = mapValue(Op);
439     if (Mapped != Op)
440       break;
441   }
442 
443   // See if the type mapper wants to remap the type as well.
444   Type *NewTy = C->getType();
445   if (TypeMapper)
446     NewTy = TypeMapper->remapType(NewTy);
447 
448   // If the result type and all operands match up, then just insert an identity
449   // mapping.
450   if (OpNo == NumOperands && NewTy == C->getType())
451     return getVM()[V] = C;
452 
453   // Okay, we need to create a new constant.  We've already processed some or
454   // all of the operands, set them all up now.
455   SmallVector<Constant*, 8> Ops;
456   Ops.reserve(NumOperands);
457   for (unsigned j = 0; j != OpNo; ++j)
458     Ops.push_back(cast<Constant>(C->getOperand(j)));
459 
460   // If one of the operands mismatch, push it and the other mapped operands.
461   if (OpNo != NumOperands) {
462     Ops.push_back(cast<Constant>(Mapped));
463 
464     // Map the rest of the operands that aren't processed yet.
465     for (++OpNo; OpNo != NumOperands; ++OpNo)
466       Ops.push_back(cast<Constant>(mapValue(C->getOperand(OpNo))));
467   }
468   Type *NewSrcTy = nullptr;
469   if (TypeMapper)
470     if (auto *GEPO = dyn_cast<GEPOperator>(C))
471       NewSrcTy = TypeMapper->remapType(GEPO->getSourceElementType());
472 
473   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
474     return getVM()[V] = CE->getWithOperands(Ops, NewTy, false, NewSrcTy);
475   if (isa<ConstantArray>(C))
476     return getVM()[V] = ConstantArray::get(cast<ArrayType>(NewTy), Ops);
477   if (isa<ConstantStruct>(C))
478     return getVM()[V] = ConstantStruct::get(cast<StructType>(NewTy), Ops);
479   if (isa<ConstantVector>(C))
480     return getVM()[V] = ConstantVector::get(Ops);
481   // If this is a no-operand constant, it must be because the type was remapped.
482   if (isa<UndefValue>(C))
483     return getVM()[V] = UndefValue::get(NewTy);
484   if (isa<ConstantAggregateZero>(C))
485     return getVM()[V] = ConstantAggregateZero::get(NewTy);
486   assert(isa<ConstantPointerNull>(C));
487   return getVM()[V] = ConstantPointerNull::get(cast<PointerType>(NewTy));
488 }
489 
490 Value *Mapper::mapBlockAddress(const BlockAddress &BA) {
491   Function *F = cast<Function>(mapValue(BA.getFunction()));
492 
493   // F may not have materialized its initializer.  In that case, create a
494   // dummy basic block for now, and replace it once we've materialized all
495   // the initializers.
496   BasicBlock *BB;
497   if (F->empty()) {
498     DelayedBBs.push_back(DelayedBasicBlock(BA));
499     BB = DelayedBBs.back().TempBB.get();
500   } else {
501     BB = cast_or_null<BasicBlock>(mapValue(BA.getBasicBlock()));
502   }
503 
504   return getVM()[&BA] = BlockAddress::get(F, BB ? BB : BA.getBasicBlock());
505 }
506 
507 Metadata *Mapper::mapToMetadata(const Metadata *Key, Metadata *Val) {
508   getVM().MD()[Key].reset(Val);
509   return Val;
510 }
511 
512 Metadata *Mapper::mapToSelf(const Metadata *MD) {
513   return mapToMetadata(MD, const_cast<Metadata *>(MD));
514 }
515 
516 Optional<Metadata *> MDNodeMapper::tryToMapOperand(const Metadata *Op) {
517   if (!Op)
518     return nullptr;
519 
520   if (Optional<Metadata *> MappedOp = M.mapSimpleMetadata(Op)) {
521 #ifndef NDEBUG
522     if (auto *CMD = dyn_cast<ConstantAsMetadata>(Op))
523       assert((!*MappedOp || M.getVM().count(CMD->getValue()) ||
524               M.getVM().getMappedMD(Op)) &&
525              "Expected Value to be memoized");
526     else
527       assert((isa<MDString>(Op) || M.getVM().getMappedMD(Op)) &&
528              "Expected result to be memoized");
529 #endif
530     return *MappedOp;
531   }
532 
533   const MDNode &N = *cast<MDNode>(Op);
534   if (N.isDistinct())
535     return mapDistinctNode(N);
536   return None;
537 }
538 
539 MDNode *MDNodeMapper::mapDistinctNode(const MDNode &N) {
540   assert(N.isDistinct() && "Expected a distinct node");
541   assert(!M.getVM().getMappedMD(&N) && "Expected an unmapped node");
542   DistinctWorklist.push_back(cast<MDNode>(
543       (M.Flags & RF_MoveDistinctMDs)
544           ? M.mapToSelf(&N)
545           : M.mapToMetadata(&N, MDNode::replaceWithDistinct(N.clone()))));
546   return DistinctWorklist.back();
547 }
548 
549 static ConstantAsMetadata *wrapConstantAsMetadata(const ConstantAsMetadata &CMD,
550                                                   Value *MappedV) {
551   if (CMD.getValue() == MappedV)
552     return const_cast<ConstantAsMetadata *>(&CMD);
553   return MappedV ? ConstantAsMetadata::getConstant(MappedV) : nullptr;
554 }
555 
556 Optional<Metadata *> MDNodeMapper::getMappedOp(const Metadata *Op) const {
557   if (!Op)
558     return nullptr;
559 
560   if (Optional<Metadata *> MappedOp = M.getVM().getMappedMD(Op))
561     return *MappedOp;
562 
563   if (isa<MDString>(Op))
564     return const_cast<Metadata *>(Op);
565 
566   if (auto *CMD = dyn_cast<ConstantAsMetadata>(Op))
567     return wrapConstantAsMetadata(*CMD, M.getVM().lookup(CMD->getValue()));
568 
569   return None;
570 }
571 
572 Metadata &MDNodeMapper::UniquedGraph::getFwdReference(MDNode &Op) {
573   auto Where = Info.find(&Op);
574   assert(Where != Info.end() && "Expected a valid reference");
575 
576   auto &OpD = Where->second;
577   if (!OpD.HasChanged)
578     return Op;
579 
580   // Lazily construct a temporary node.
581   if (!OpD.Placeholder)
582     OpD.Placeholder = Op.clone();
583 
584   return *OpD.Placeholder;
585 }
586 
587 template <class OperandMapper>
588 void MDNodeMapper::remapOperands(MDNode &N, OperandMapper mapOperand) {
589   assert(!N.isUniqued() && "Expected distinct or temporary nodes");
590   for (unsigned I = 0, E = N.getNumOperands(); I != E; ++I) {
591     Metadata *Old = N.getOperand(I);
592     Metadata *New = mapOperand(Old);
593 
594     if (Old != New)
595       N.replaceOperandWith(I, New);
596   }
597 }
598 
599 namespace {
600 /// An entry in the worklist for the post-order traversal.
601 struct POTWorklistEntry {
602   MDNode *N;              ///< Current node.
603   MDNode::op_iterator Op; ///< Current operand of \c N.
604 
605   /// Keep a flag of whether operands have changed in the worklist to avoid
606   /// hitting the map in \a UniquedGraph.
607   bool HasChanged = false;
608 
609   POTWorklistEntry(MDNode &N) : N(&N), Op(N.op_begin()) {}
610 };
611 } // end namespace
612 
613 bool MDNodeMapper::createPOT(UniquedGraph &G, const MDNode &FirstN) {
614   assert(G.Info.empty() && "Expected a fresh traversal");
615   assert(FirstN.isUniqued() && "Expected uniqued node in POT");
616 
617   // Construct a post-order traversal of the uniqued subgraph under FirstN.
618   bool AnyChanges = false;
619   SmallVector<POTWorklistEntry, 16> Worklist;
620   Worklist.push_back(POTWorklistEntry(const_cast<MDNode &>(FirstN)));
621   (void)G.Info[&FirstN];
622   while (!Worklist.empty()) {
623     // Start or continue the traversal through the this node's operands.
624     auto &WE = Worklist.back();
625     if (MDNode *N = visitOperands(G, WE.Op, WE.N->op_end(), WE.HasChanged)) {
626       // Push a new node to traverse first.
627       Worklist.push_back(POTWorklistEntry(*N));
628       continue;
629     }
630 
631     // Push the node onto the POT.
632     assert(WE.N->isUniqued() && "Expected only uniqued nodes");
633     assert(WE.Op == WE.N->op_end() && "Expected to visit all operands");
634     auto &D = G.Info[WE.N];
635     AnyChanges |= D.HasChanged = WE.HasChanged;
636     D.ID = G.POT.size();
637     G.POT.push_back(WE.N);
638 
639     // Pop the node off the worklist.
640     Worklist.pop_back();
641   }
642   return AnyChanges;
643 }
644 
645 MDNode *MDNodeMapper::visitOperands(UniquedGraph &G, MDNode::op_iterator &I,
646                                     MDNode::op_iterator E, bool &HasChanged) {
647   while (I != E) {
648     Metadata *Op = *I++; // Increment even on early return.
649     if (Optional<Metadata *> MappedOp = tryToMapOperand(Op)) {
650       // Check if the operand changes.
651       HasChanged |= Op != *MappedOp;
652       continue;
653     }
654 
655     // A uniqued metadata node.
656     MDNode &OpN = *cast<MDNode>(Op);
657     assert(OpN.isUniqued() &&
658            "Only uniqued operands cannot be mapped immediately");
659     if (G.Info.insert(std::make_pair(&OpN, Data())).second)
660       return &OpN; // This is a new one.  Return it.
661   }
662   return nullptr;
663 }
664 
665 void MDNodeMapper::UniquedGraph::propagateChanges() {
666   bool AnyChanges;
667   do {
668     AnyChanges = false;
669     for (MDNode *N : POT) {
670       auto &D = Info[N];
671       if (D.HasChanged)
672         continue;
673 
674       if (!llvm::any_of(N->operands(), [&](const Metadata *Op) {
675             auto Where = Info.find(Op);
676             return Where != Info.end() && Where->second.HasChanged;
677           }))
678         continue;
679 
680       AnyChanges = D.HasChanged = true;
681     }
682   } while (AnyChanges);
683 }
684 
685 void MDNodeMapper::mapNodesInPOT(UniquedGraph &G) {
686   // Construct uniqued nodes, building forward references as necessary.
687   SmallVector<MDNode *, 16> CyclicNodes;
688   for (auto *N : G.POT) {
689     auto &D = G.Info[N];
690     if (!D.HasChanged) {
691       // The node hasn't changed.
692       M.mapToSelf(N);
693       continue;
694     }
695 
696     // Remember whether this node had a placeholder.
697     bool HadPlaceholder(D.Placeholder);
698 
699     // Clone the uniqued node and remap the operands.
700     TempMDNode ClonedN = D.Placeholder ? std::move(D.Placeholder) : N->clone();
701     remapOperands(*ClonedN, [this, &D, &G](Metadata *Old) {
702       if (Optional<Metadata *> MappedOp = getMappedOp(Old))
703         return *MappedOp;
704       assert(G.Info[Old].ID > D.ID && "Expected a forward reference");
705       return &G.getFwdReference(*cast<MDNode>(Old));
706     });
707 
708     auto *NewN = MDNode::replaceWithUniqued(std::move(ClonedN));
709     M.mapToMetadata(N, NewN);
710 
711     // Nodes that were referenced out of order in the POT are involved in a
712     // uniquing cycle.
713     if (HadPlaceholder)
714       CyclicNodes.push_back(NewN);
715   }
716 
717   // Resolve cycles.
718   for (auto *N : CyclicNodes)
719     if (!N->isResolved())
720       N->resolveCycles();
721 }
722 
723 Metadata *MDNodeMapper::map(const MDNode &N) {
724   assert(DistinctWorklist.empty() && "MDNodeMapper::map is not recursive");
725   assert(!(M.Flags & RF_NoModuleLevelChanges) &&
726          "MDNodeMapper::map assumes module-level changes");
727 
728   // Require resolved nodes whenever metadata might be remapped.
729   assert(N.isResolved() && "Unexpected unresolved node");
730 
731   Metadata *MappedN =
732       N.isUniqued() ? mapTopLevelUniquedNode(N) : mapDistinctNode(N);
733   while (!DistinctWorklist.empty())
734     remapOperands(*DistinctWorklist.pop_back_val(), [this](Metadata *Old) {
735       if (Optional<Metadata *> MappedOp = tryToMapOperand(Old))
736         return *MappedOp;
737       return mapTopLevelUniquedNode(*cast<MDNode>(Old));
738     });
739   return MappedN;
740 }
741 
742 Metadata *MDNodeMapper::mapTopLevelUniquedNode(const MDNode &FirstN) {
743   assert(FirstN.isUniqued() && "Expected uniqued node");
744 
745   // Create a post-order traversal of uniqued nodes under FirstN.
746   UniquedGraph G;
747   if (!createPOT(G, FirstN)) {
748     // Return early if no nodes have changed.
749     for (const MDNode *N : G.POT)
750       M.mapToSelf(N);
751     return &const_cast<MDNode &>(FirstN);
752   }
753 
754   // Update graph with all nodes that have changed.
755   G.propagateChanges();
756 
757   // Map all the nodes in the graph.
758   mapNodesInPOT(G);
759 
760   // Return the original node, remapped.
761   return *getMappedOp(&FirstN);
762 }
763 
764 namespace {
765 
766 struct MapMetadataDisabler {
767   ValueToValueMapTy &VM;
768 
769   MapMetadataDisabler(ValueToValueMapTy &VM) : VM(VM) {
770     VM.disableMapMetadata();
771   }
772   ~MapMetadataDisabler() { VM.enableMapMetadata(); }
773 };
774 
775 } // end namespace
776 
777 Optional<Metadata *> Mapper::mapSimpleMetadata(const Metadata *MD) {
778   // If the value already exists in the map, use it.
779   if (Optional<Metadata *> NewMD = getVM().getMappedMD(MD))
780     return *NewMD;
781 
782   if (isa<MDString>(MD))
783     return const_cast<Metadata *>(MD);
784 
785   // This is a module-level metadata.  If nothing at the module level is
786   // changing, use an identity mapping.
787   if ((Flags & RF_NoModuleLevelChanges))
788     return const_cast<Metadata *>(MD);
789 
790   if (auto *CMD = dyn_cast<ConstantAsMetadata>(MD)) {
791     // Disallow recursion into metadata mapping through mapValue.
792     MapMetadataDisabler MMD(getVM());
793 
794     // Don't memoize ConstantAsMetadata.  Instead of lasting until the
795     // LLVMContext is destroyed, they can be deleted when the GlobalValue they
796     // reference is destructed.  These aren't super common, so the extra
797     // indirection isn't that expensive.
798     return wrapConstantAsMetadata(*CMD, mapValue(CMD->getValue()));
799   }
800 
801   assert(isa<MDNode>(MD) && "Expected a metadata node");
802 
803   return None;
804 }
805 
806 Metadata *Mapper::mapLocalAsMetadata(const LocalAsMetadata &LAM) {
807   // Lookup the mapping for the value itself, and return the appropriate
808   // metadata.
809   if (Value *V = mapValue(LAM.getValue())) {
810     if (V == LAM.getValue())
811       return const_cast<LocalAsMetadata *>(&LAM);
812     return ValueAsMetadata::get(V);
813   }
814 
815   // FIXME: always return nullptr once Verifier::verifyDominatesUse() ensures
816   // metadata operands only reference defined SSA values.
817   return (Flags & RF_IgnoreMissingLocals)
818              ? nullptr
819              : MDTuple::get(LAM.getContext(), None);
820 }
821 
822 Metadata *Mapper::mapMetadata(const Metadata *MD) {
823   assert(MD && "Expected valid metadata");
824   assert(!isa<LocalAsMetadata>(MD) && "Unexpected local metadata");
825 
826   if (Optional<Metadata *> NewMD = mapSimpleMetadata(MD))
827     return *NewMD;
828 
829   return MDNodeMapper(*this).map(*cast<MDNode>(MD));
830 }
831 
832 void Mapper::flush() {
833   // Flush out the worklist of global values.
834   while (!Worklist.empty()) {
835     WorklistEntry E = Worklist.pop_back_val();
836     CurrentMCID = E.MCID;
837     switch (E.Kind) {
838     case WorklistEntry::MapGlobalInit:
839       E.Data.GVInit.GV->setInitializer(mapConstant(E.Data.GVInit.Init));
840       break;
841     case WorklistEntry::MapAppendingVar: {
842       unsigned PrefixSize = AppendingInits.size() - E.AppendingGVNumNewMembers;
843       mapAppendingVariable(*E.Data.AppendingGV.GV,
844                            E.Data.AppendingGV.InitPrefix,
845                            E.AppendingGVIsOldCtorDtor,
846                            makeArrayRef(AppendingInits).slice(PrefixSize));
847       AppendingInits.resize(PrefixSize);
848       break;
849     }
850     case WorklistEntry::MapGlobalAliasee:
851       E.Data.GlobalAliasee.GA->setAliasee(
852           mapConstant(E.Data.GlobalAliasee.Aliasee));
853       break;
854     case WorklistEntry::RemapFunction:
855       remapFunction(*E.Data.RemapF);
856       break;
857     }
858   }
859   CurrentMCID = 0;
860 
861   // Finish logic for block addresses now that all global values have been
862   // handled.
863   while (!DelayedBBs.empty()) {
864     DelayedBasicBlock DBB = DelayedBBs.pop_back_val();
865     BasicBlock *BB = cast_or_null<BasicBlock>(mapValue(DBB.OldBB));
866     DBB.TempBB->replaceAllUsesWith(BB ? BB : DBB.OldBB);
867   }
868 }
869 
870 void Mapper::remapInstruction(Instruction *I) {
871   // Remap operands.
872   for (Use &Op : I->operands()) {
873     Value *V = mapValue(Op);
874     // If we aren't ignoring missing entries, assert that something happened.
875     if (V)
876       Op = V;
877     else
878       assert((Flags & RF_IgnoreMissingLocals) &&
879              "Referenced value not in value map!");
880   }
881 
882   // Remap phi nodes' incoming blocks.
883   if (PHINode *PN = dyn_cast<PHINode>(I)) {
884     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
885       Value *V = mapValue(PN->getIncomingBlock(i));
886       // If we aren't ignoring missing entries, assert that something happened.
887       if (V)
888         PN->setIncomingBlock(i, cast<BasicBlock>(V));
889       else
890         assert((Flags & RF_IgnoreMissingLocals) &&
891                "Referenced block not in value map!");
892     }
893   }
894 
895   // Remap attached metadata.
896   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
897   I->getAllMetadata(MDs);
898   for (const auto &MI : MDs) {
899     MDNode *Old = MI.second;
900     MDNode *New = cast_or_null<MDNode>(mapMetadata(Old));
901     if (New != Old)
902       I->setMetadata(MI.first, New);
903   }
904 
905   if (!TypeMapper)
906     return;
907 
908   // If the instruction's type is being remapped, do so now.
909   if (auto CS = CallSite(I)) {
910     SmallVector<Type *, 3> Tys;
911     FunctionType *FTy = CS.getFunctionType();
912     Tys.reserve(FTy->getNumParams());
913     for (Type *Ty : FTy->params())
914       Tys.push_back(TypeMapper->remapType(Ty));
915     CS.mutateFunctionType(FunctionType::get(
916         TypeMapper->remapType(I->getType()), Tys, FTy->isVarArg()));
917     return;
918   }
919   if (auto *AI = dyn_cast<AllocaInst>(I))
920     AI->setAllocatedType(TypeMapper->remapType(AI->getAllocatedType()));
921   if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
922     GEP->setSourceElementType(
923         TypeMapper->remapType(GEP->getSourceElementType()));
924     GEP->setResultElementType(
925         TypeMapper->remapType(GEP->getResultElementType()));
926   }
927   I->mutateType(TypeMapper->remapType(I->getType()));
928 }
929 
930 void Mapper::remapFunction(Function &F) {
931   // Remap the operands.
932   for (Use &Op : F.operands())
933     if (Op)
934       Op = mapValue(Op);
935 
936   // Remap the metadata attachments.
937   SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
938   F.getAllMetadata(MDs);
939   for (const auto &I : MDs)
940     F.setMetadata(I.first, cast_or_null<MDNode>(mapMetadata(I.second)));
941 
942   // Remap the argument types.
943   if (TypeMapper)
944     for (Argument &A : F.args())
945       A.mutateType(TypeMapper->remapType(A.getType()));
946 
947   // Remap the instructions.
948   for (BasicBlock &BB : F)
949     for (Instruction &I : BB)
950       remapInstruction(&I);
951 }
952 
953 void Mapper::mapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
954                                   bool IsOldCtorDtor,
955                                   ArrayRef<Constant *> NewMembers) {
956   SmallVector<Constant *, 16> Elements;
957   if (InitPrefix) {
958     unsigned NumElements =
959         cast<ArrayType>(InitPrefix->getType())->getNumElements();
960     for (unsigned I = 0; I != NumElements; ++I)
961       Elements.push_back(InitPrefix->getAggregateElement(I));
962   }
963 
964   PointerType *VoidPtrTy;
965   Type *EltTy;
966   if (IsOldCtorDtor) {
967     // FIXME: This upgrade is done during linking to support the C API.  See
968     // also IRLinker::linkAppendingVarProto() in IRMover.cpp.
969     VoidPtrTy = Type::getInt8Ty(GV.getContext())->getPointerTo();
970     auto &ST = *cast<StructType>(NewMembers.front()->getType());
971     Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
972     EltTy = StructType::get(GV.getContext(), Tys, false);
973   }
974 
975   for (auto *V : NewMembers) {
976     Constant *NewV;
977     if (IsOldCtorDtor) {
978       auto *S = cast<ConstantStruct>(V);
979       auto *E1 = mapValue(S->getOperand(0));
980       auto *E2 = mapValue(S->getOperand(1));
981       Value *Null = Constant::getNullValue(VoidPtrTy);
982       NewV =
983           ConstantStruct::get(cast<StructType>(EltTy), E1, E2, Null, nullptr);
984     } else {
985       NewV = cast_or_null<Constant>(mapValue(V));
986     }
987     Elements.push_back(NewV);
988   }
989 
990   GV.setInitializer(ConstantArray::get(
991       cast<ArrayType>(GV.getType()->getElementType()), Elements));
992 }
993 
994 void Mapper::scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init,
995                                           unsigned MCID) {
996   assert(AlreadyScheduled.insert(&GV).second && "Should not reschedule");
997   assert(MCID < MCs.size() && "Invalid mapping context");
998 
999   WorklistEntry WE;
1000   WE.Kind = WorklistEntry::MapGlobalInit;
1001   WE.MCID = MCID;
1002   WE.Data.GVInit.GV = &GV;
1003   WE.Data.GVInit.Init = &Init;
1004   Worklist.push_back(WE);
1005 }
1006 
1007 void Mapper::scheduleMapAppendingVariable(GlobalVariable &GV,
1008                                           Constant *InitPrefix,
1009                                           bool IsOldCtorDtor,
1010                                           ArrayRef<Constant *> NewMembers,
1011                                           unsigned MCID) {
1012   assert(AlreadyScheduled.insert(&GV).second && "Should not reschedule");
1013   assert(MCID < MCs.size() && "Invalid mapping context");
1014 
1015   WorklistEntry WE;
1016   WE.Kind = WorklistEntry::MapAppendingVar;
1017   WE.MCID = MCID;
1018   WE.Data.AppendingGV.GV = &GV;
1019   WE.Data.AppendingGV.InitPrefix = InitPrefix;
1020   WE.AppendingGVIsOldCtorDtor = IsOldCtorDtor;
1021   WE.AppendingGVNumNewMembers = NewMembers.size();
1022   Worklist.push_back(WE);
1023   AppendingInits.append(NewMembers.begin(), NewMembers.end());
1024 }
1025 
1026 void Mapper::scheduleMapGlobalAliasee(GlobalAlias &GA, Constant &Aliasee,
1027                                       unsigned MCID) {
1028   assert(AlreadyScheduled.insert(&GA).second && "Should not reschedule");
1029   assert(MCID < MCs.size() && "Invalid mapping context");
1030 
1031   WorklistEntry WE;
1032   WE.Kind = WorklistEntry::MapGlobalAliasee;
1033   WE.MCID = MCID;
1034   WE.Data.GlobalAliasee.GA = &GA;
1035   WE.Data.GlobalAliasee.Aliasee = &Aliasee;
1036   Worklist.push_back(WE);
1037 }
1038 
1039 void Mapper::scheduleRemapFunction(Function &F, unsigned MCID) {
1040   assert(AlreadyScheduled.insert(&F).second && "Should not reschedule");
1041   assert(MCID < MCs.size() && "Invalid mapping context");
1042 
1043   WorklistEntry WE;
1044   WE.Kind = WorklistEntry::RemapFunction;
1045   WE.MCID = MCID;
1046   WE.Data.RemapF = &F;
1047   Worklist.push_back(WE);
1048 }
1049 
1050 void Mapper::addFlags(RemapFlags Flags) {
1051   assert(!hasWorkToDo() && "Expected to have flushed the worklist");
1052   this->Flags = this->Flags | Flags;
1053 }
1054 
1055 static Mapper *getAsMapper(void *pImpl) {
1056   return reinterpret_cast<Mapper *>(pImpl);
1057 }
1058 
1059 namespace {
1060 
1061 class FlushingMapper {
1062   Mapper &M;
1063 
1064 public:
1065   explicit FlushingMapper(void *pImpl) : M(*getAsMapper(pImpl)) {
1066     assert(!M.hasWorkToDo() && "Expected to be flushed");
1067   }
1068   ~FlushingMapper() { M.flush(); }
1069   Mapper *operator->() const { return &M; }
1070 };
1071 
1072 } // end namespace
1073 
1074 ValueMapper::ValueMapper(ValueToValueMapTy &VM, RemapFlags Flags,
1075                          ValueMapTypeRemapper *TypeMapper,
1076                          ValueMaterializer *Materializer)
1077     : pImpl(new Mapper(VM, Flags, TypeMapper, Materializer)) {}
1078 
1079 ValueMapper::~ValueMapper() { delete getAsMapper(pImpl); }
1080 
1081 unsigned
1082 ValueMapper::registerAlternateMappingContext(ValueToValueMapTy &VM,
1083                                              ValueMaterializer *Materializer) {
1084   return getAsMapper(pImpl)->registerAlternateMappingContext(VM, Materializer);
1085 }
1086 
1087 void ValueMapper::addFlags(RemapFlags Flags) {
1088   FlushingMapper(pImpl)->addFlags(Flags);
1089 }
1090 
1091 Value *ValueMapper::mapValue(const Value &V) {
1092   return FlushingMapper(pImpl)->mapValue(&V);
1093 }
1094 
1095 Constant *ValueMapper::mapConstant(const Constant &C) {
1096   return cast_or_null<Constant>(mapValue(C));
1097 }
1098 
1099 Metadata *ValueMapper::mapMetadata(const Metadata &MD) {
1100   return FlushingMapper(pImpl)->mapMetadata(&MD);
1101 }
1102 
1103 MDNode *ValueMapper::mapMDNode(const MDNode &N) {
1104   return cast_or_null<MDNode>(mapMetadata(N));
1105 }
1106 
1107 void ValueMapper::remapInstruction(Instruction &I) {
1108   FlushingMapper(pImpl)->remapInstruction(&I);
1109 }
1110 
1111 void ValueMapper::remapFunction(Function &F) {
1112   FlushingMapper(pImpl)->remapFunction(F);
1113 }
1114 
1115 void ValueMapper::scheduleMapGlobalInitializer(GlobalVariable &GV,
1116                                                Constant &Init,
1117                                                unsigned MCID) {
1118   getAsMapper(pImpl)->scheduleMapGlobalInitializer(GV, Init, MCID);
1119 }
1120 
1121 void ValueMapper::scheduleMapAppendingVariable(GlobalVariable &GV,
1122                                                Constant *InitPrefix,
1123                                                bool IsOldCtorDtor,
1124                                                ArrayRef<Constant *> NewMembers,
1125                                                unsigned MCID) {
1126   getAsMapper(pImpl)->scheduleMapAppendingVariable(
1127       GV, InitPrefix, IsOldCtorDtor, NewMembers, MCID);
1128 }
1129 
1130 void ValueMapper::scheduleMapGlobalAliasee(GlobalAlias &GA, Constant &Aliasee,
1131                                            unsigned MCID) {
1132   getAsMapper(pImpl)->scheduleMapGlobalAliasee(GA, Aliasee, MCID);
1133 }
1134 
1135 void ValueMapper::scheduleRemapFunction(Function &F, unsigned MCID) {
1136   getAsMapper(pImpl)->scheduleRemapFunction(F, MCID);
1137 }
1138