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