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