1 //===- ValueMapper.cpp - Interface shared by lib/Transforms/Utils ---------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file defines the MapValue function, which is shared by various parts of
10 // the lib/Transforms/Utils library.
12 //===----------------------------------------------------------------------===//
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/STLExtras.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/IR/Argument.h"
21 #include "llvm/IR/BasicBlock.h"
22 #include "llvm/IR/Constant.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DebugInfoMetadata.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/GlobalAlias.h"
28 #include "llvm/IR/GlobalIFunc.h"
29 #include "llvm/IR/GlobalObject.h"
30 #include "llvm/IR/GlobalVariable.h"
31 #include "llvm/IR/InlineAsm.h"
32 #include "llvm/IR/Instruction.h"
33 #include "llvm/IR/Instructions.h"
34 #include "llvm/IR/Metadata.h"
35 #include "llvm/IR/Operator.h"
36 #include "llvm/IR/Type.h"
37 #include "llvm/IR/Value.h"
38 #include "llvm/Support/Casting.h"
39 #include "llvm/Support/Debug.h"
47 #define DEBUG_TYPE "value-mapper"
49 // Out of line method to get vtable etc for class.
50 void ValueMapTypeRemapper::anchor() {}
51 void ValueMaterializer::anchor() {}
55 /// A basic block used in a BlockAddress whose function body is not yet
57 struct DelayedBasicBlock {
59 std::unique_ptr<BasicBlock> TempBB;
61 DelayedBasicBlock(const BlockAddress &Old)
62 : OldBB(Old.getBasicBlock()),
63 TempBB(BasicBlock::Create(Old.getContext())) {}
66 struct WorklistEntry {
77 struct AppendingGVTy {
81 struct AliasOrIFuncTy {
88 unsigned AppendingGVIsOldCtorDtor : 1;
89 unsigned AppendingGVNumNewMembers;
92 AppendingGVTy AppendingGV;
93 AliasOrIFuncTy AliasOrIFunc;
98 struct MappingContext {
99 ValueToValueMapTy *VM;
100 ValueMaterializer *Materializer = nullptr;
102 /// Construct a MappingContext with a value map and materializer.
103 explicit MappingContext(ValueToValueMapTy &VM,
104 ValueMaterializer *Materializer = nullptr)
105 : VM(&VM), Materializer(Materializer) {}
109 friend class MDNodeMapper;
112 DenseSet<GlobalValue *> AlreadyScheduled;
116 ValueMapTypeRemapper *TypeMapper;
117 unsigned CurrentMCID = 0;
118 SmallVector<MappingContext, 2> MCs;
119 SmallVector<WorklistEntry, 4> Worklist;
120 SmallVector<DelayedBasicBlock, 1> DelayedBBs;
121 SmallVector<Constant *, 16> AppendingInits;
124 Mapper(ValueToValueMapTy &VM, RemapFlags Flags,
125 ValueMapTypeRemapper *TypeMapper, ValueMaterializer *Materializer)
126 : Flags(Flags), TypeMapper(TypeMapper),
127 MCs(1, MappingContext(VM, Materializer)) {}
129 /// ValueMapper should explicitly call \a flush() before destruction.
130 ~Mapper() { assert(!hasWorkToDo() && "Expected to be flushed"); }
132 bool hasWorkToDo() const { return !Worklist.empty(); }
135 registerAlternateMappingContext(ValueToValueMapTy &VM,
136 ValueMaterializer *Materializer = nullptr) {
137 MCs.push_back(MappingContext(VM, Materializer));
138 return MCs.size() - 1;
141 void addFlags(RemapFlags Flags);
143 void remapGlobalObjectMetadata(GlobalObject &GO);
145 Value *mapValue(const Value *V);
146 void remapInstruction(Instruction *I);
147 void remapFunction(Function &F);
149 Constant *mapConstant(const Constant *C) {
150 return cast_or_null<Constant>(mapValue(C));
155 /// Find the mapping for MD. Guarantees that the return will be resolved
156 /// (not an MDNode, or MDNode::isResolved() returns true).
157 Metadata *mapMetadata(const Metadata *MD);
159 void scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init,
161 void scheduleMapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
163 ArrayRef<Constant *> NewMembers,
165 void scheduleMapAliasOrIFunc(GlobalValue &GV, Constant &Target,
167 void scheduleRemapFunction(Function &F, unsigned MCID);
172 void mapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
174 ArrayRef<Constant *> NewMembers);
176 ValueToValueMapTy &getVM() { return *MCs[CurrentMCID].VM; }
177 ValueMaterializer *getMaterializer() { return MCs[CurrentMCID].Materializer; }
179 Value *mapBlockAddress(const BlockAddress &BA);
181 /// Map metadata that doesn't require visiting operands.
182 std::optional<Metadata *> mapSimpleMetadata(const Metadata *MD);
184 Metadata *mapToMetadata(const Metadata *Key, Metadata *Val);
185 Metadata *mapToSelf(const Metadata *MD);
191 /// Data about a node in \a UniquedGraph.
193 bool HasChanged = false;
194 unsigned ID = std::numeric_limits<unsigned>::max();
195 TempMDNode Placeholder;
198 /// A graph of uniqued nodes.
199 struct UniquedGraph {
200 SmallDenseMap<const Metadata *, Data, 32> Info; // Node properties.
201 SmallVector<MDNode *, 16> POT; // Post-order traversal.
203 /// Propagate changed operands through the post-order traversal.
205 /// Iteratively update \a Data::HasChanged for each node based on \a
206 /// Data::HasChanged of its operands, until fixed point.
207 void propagateChanges();
209 /// Get a forward reference to a node to use as an operand.
210 Metadata &getFwdReference(MDNode &Op);
213 /// Worklist of distinct nodes whose operands need to be remapped.
214 SmallVector<MDNode *, 16> DistinctWorklist;
216 // Storage for a UniquedGraph.
217 SmallDenseMap<const Metadata *, Data, 32> InfoStorage;
218 SmallVector<MDNode *, 16> POTStorage;
221 MDNodeMapper(Mapper &M) : M(M) {}
223 /// Map a metadata node (and its transitive operands).
225 /// Map all the (unmapped) nodes in the subgraph under \c N. The iterative
226 /// algorithm handles distinct nodes and uniqued node subgraphs using
227 /// different strategies.
229 /// Distinct nodes are immediately mapped and added to \a DistinctWorklist
230 /// using \a mapDistinctNode(). Their mapping can always be computed
231 /// immediately without visiting operands, even if their operands change.
233 /// The mapping for uniqued nodes depends on whether their operands change.
234 /// \a mapTopLevelUniquedNode() traverses the transitive uniqued subgraph of
235 /// a node to calculate uniqued node mappings in bulk. Distinct leafs are
236 /// added to \a DistinctWorklist with \a mapDistinctNode().
238 /// After mapping \c N itself, this function remaps the operands of the
239 /// distinct nodes in \a DistinctWorklist until the entire subgraph under \c
240 /// N has been mapped.
241 Metadata *map(const MDNode &N);
244 /// Map a top-level uniqued node and the uniqued subgraph underneath it.
246 /// This builds up a post-order traversal of the (unmapped) uniqued subgraph
247 /// underneath \c FirstN and calculates the nodes' mapping. Each node uses
248 /// the identity mapping (\a Mapper::mapToSelf()) as long as all of its
249 /// operands uses the identity mapping.
251 /// The algorithm works as follows:
253 /// 1. \a createPOT(): traverse the uniqued subgraph under \c FirstN and
254 /// save the post-order traversal in the given \a UniquedGraph, tracking
255 /// nodes' operands change.
257 /// 2. \a UniquedGraph::propagateChanges(): propagate changed operands
258 /// through the \a UniquedGraph until fixed point, following the rule
259 /// that if a node changes, any node that references must also change.
261 /// 3. \a mapNodesInPOT(): map the uniqued nodes, creating new uniqued nodes
262 /// (referencing new operands) where necessary.
263 Metadata *mapTopLevelUniquedNode(const MDNode &FirstN);
265 /// Try to map the operand of an \a MDNode.
267 /// If \c Op is already mapped, return the mapping. If it's not an \a
268 /// MDNode, compute and return the mapping. If it's a distinct \a MDNode,
269 /// return the result of \a mapDistinctNode().
271 /// \return std::nullopt if \c Op is an unmapped uniqued \a MDNode.
272 /// \post getMappedOp(Op) only returns std::nullopt if this returns
274 std::optional<Metadata *> tryToMapOperand(const Metadata *Op);
276 /// Map a distinct node.
278 /// Return the mapping for the distinct node \c N, saving the result in \a
279 /// DistinctWorklist for later remapping.
281 /// \pre \c N is not yet mapped.
282 /// \pre \c N.isDistinct().
283 MDNode *mapDistinctNode(const MDNode &N);
285 /// Get a previously mapped node.
286 std::optional<Metadata *> getMappedOp(const Metadata *Op) const;
288 /// Create a post-order traversal of an unmapped uniqued node subgraph.
290 /// This traverses the metadata graph deeply enough to map \c FirstN. It
291 /// uses \a tryToMapOperand() (via \a Mapper::mapSimplifiedNode()), so any
292 /// metadata that has already been mapped will not be part of the POT.
294 /// Each node that has a changed operand from outside the graph (e.g., a
295 /// distinct node, an already-mapped uniqued node, or \a ConstantAsMetadata)
296 /// is marked with \a Data::HasChanged.
298 /// \return \c true if any nodes in \c G have \a Data::HasChanged.
299 /// \post \c G.POT is a post-order traversal ending with \c FirstN.
300 /// \post \a Data::hasChanged in \c G.Info indicates whether any node needs
301 /// to change because of operands outside the graph.
302 bool createPOT(UniquedGraph &G, const MDNode &FirstN);
304 /// Visit the operands of a uniqued node in the POT.
306 /// Visit the operands in the range from \c I to \c E, returning the first
307 /// uniqued node we find that isn't yet in \c G. \c I is always advanced to
308 /// where to continue the loop through the operands.
310 /// This sets \c HasChanged if any of the visited operands change.
311 MDNode *visitOperands(UniquedGraph &G, MDNode::op_iterator &I,
312 MDNode::op_iterator E, bool &HasChanged);
314 /// Map all the nodes in the given uniqued graph.
316 /// This visits all the nodes in \c G in post-order, using the identity
317 /// mapping or creating a new node depending on \a Data::HasChanged.
319 /// \pre \a getMappedOp() returns std::nullopt for nodes in \c G, but not for
320 /// any of their operands outside of \c G. \pre \a Data::HasChanged is true
321 /// for a node in \c G iff any of its operands have changed. \post \a
322 /// getMappedOp() returns the mapped node for every node in \c G.
323 void mapNodesInPOT(UniquedGraph &G);
325 /// Remap a node's operands using the given functor.
327 /// Iterate through the operands of \c N and update them in place using \c
330 /// \pre N.isDistinct() or N.isTemporary().
331 template <class OperandMapper>
332 void remapOperands(MDNode &N, OperandMapper mapOperand);
335 } // end anonymous namespace
337 Value *Mapper::mapValue(const Value *V) {
338 ValueToValueMapTy::iterator I = getVM().find(V);
340 // If the value already exists in the map, use it.
341 if (I != getVM().end()) {
342 assert(I->second && "Unexpected null mapping");
346 // If we have a materializer and it can materialize a value, use that.
347 if (auto *Materializer = getMaterializer()) {
348 if (Value *NewV = Materializer->materialize(const_cast<Value *>(V))) {
354 // Global values do not need to be seeded into the VM if they
355 // are using the identity mapping.
356 if (isa<GlobalValue>(V)) {
357 if (Flags & RF_NullMapMissingGlobalValues)
359 return getVM()[V] = const_cast<Value *>(V);
362 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
363 // Inline asm may need *type* remapping.
364 FunctionType *NewTy = IA->getFunctionType();
366 NewTy = cast<FunctionType>(TypeMapper->remapType(NewTy));
368 if (NewTy != IA->getFunctionType())
369 V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),
370 IA->hasSideEffects(), IA->isAlignStack(),
371 IA->getDialect(), IA->canThrow());
374 return getVM()[V] = const_cast<Value *>(V);
377 if (const auto *MDV = dyn_cast<MetadataAsValue>(V)) {
378 const Metadata *MD = MDV->getMetadata();
380 if (auto *LAM = dyn_cast<LocalAsMetadata>(MD)) {
381 // Look through to grab the local value.
382 if (Value *LV = mapValue(LAM->getValue())) {
383 if (V == LAM->getValue())
384 return const_cast<Value *>(V);
385 return MetadataAsValue::get(V->getContext(), ValueAsMetadata::get(LV));
388 // FIXME: always return nullptr once Verifier::verifyDominatesUse()
389 // ensures metadata operands only reference defined SSA values.
390 return (Flags & RF_IgnoreMissingLocals)
392 : MetadataAsValue::get(
394 MDTuple::get(V->getContext(), std::nullopt));
396 if (auto *AL = dyn_cast<DIArgList>(MD)) {
397 SmallVector<ValueAsMetadata *, 4> MappedArgs;
398 for (auto *VAM : AL->getArgs()) {
399 // Map both Local and Constant VAMs here; they will both ultimately
400 // be mapped via mapValue. The exceptions are constants when we have no
401 // module level changes and locals when they have no existing mapped
402 // value and RF_IgnoreMissingLocals is set; these have identity
404 if ((Flags & RF_NoModuleLevelChanges) && isa<ConstantAsMetadata>(VAM)) {
405 MappedArgs.push_back(VAM);
406 } else if (Value *LV = mapValue(VAM->getValue())) {
407 MappedArgs.push_back(
408 LV == VAM->getValue() ? VAM : ValueAsMetadata::get(LV));
409 } else if ((Flags & RF_IgnoreMissingLocals) && isa<LocalAsMetadata>(VAM)) {
410 MappedArgs.push_back(VAM);
412 // If we cannot map the value, set the argument as undef.
413 MappedArgs.push_back(ValueAsMetadata::get(
414 UndefValue::get(VAM->getValue()->getType())));
417 return MetadataAsValue::get(V->getContext(),
418 DIArgList::get(V->getContext(), MappedArgs));
421 // If this is a module-level metadata and we know that nothing at the module
422 // level is changing, then use an identity mapping.
423 if (Flags & RF_NoModuleLevelChanges)
424 return getVM()[V] = const_cast<Value *>(V);
426 // Map the metadata and turn it into a value.
427 auto *MappedMD = mapMetadata(MD);
429 return getVM()[V] = const_cast<Value *>(V);
430 return getVM()[V] = MetadataAsValue::get(V->getContext(), MappedMD);
433 // Okay, this either must be a constant (which may or may not be mappable) or
434 // is something that is not in the mapping table.
435 Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
439 if (BlockAddress *BA = dyn_cast<BlockAddress>(C))
440 return mapBlockAddress(*BA);
442 if (const auto *E = dyn_cast<DSOLocalEquivalent>(C)) {
443 auto *Val = mapValue(E->getGlobalValue());
444 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
446 return getVM()[E] = DSOLocalEquivalent::get(GV);
448 auto *Func = cast<Function>(Val->stripPointerCastsAndAliases());
449 Type *NewTy = E->getType();
451 NewTy = TypeMapper->remapType(NewTy);
452 return getVM()[E] = llvm::ConstantExpr::getBitCast(
453 DSOLocalEquivalent::get(Func), NewTy);
456 if (const auto *NC = dyn_cast<NoCFIValue>(C)) {
457 auto *Val = mapValue(NC->getGlobalValue());
458 GlobalValue *GV = cast<GlobalValue>(Val);
459 return getVM()[NC] = NoCFIValue::get(GV);
462 auto mapValueOrNull = [this](Value *V) {
463 auto Mapped = mapValue(V);
464 assert((Mapped || (Flags & RF_NullMapMissingGlobalValues)) &&
465 "Unexpected null mapping for constant operand without "
466 "NullMapMissingGlobalValues flag");
470 // Otherwise, we have some other constant to remap. Start by checking to see
471 // if all operands have an identity remapping.
472 unsigned OpNo = 0, NumOperands = C->getNumOperands();
473 Value *Mapped = nullptr;
474 for (; OpNo != NumOperands; ++OpNo) {
475 Value *Op = C->getOperand(OpNo);
476 Mapped = mapValueOrNull(Op);
483 // See if the type mapper wants to remap the type as well.
484 Type *NewTy = C->getType();
486 NewTy = TypeMapper->remapType(NewTy);
488 // If the result type and all operands match up, then just insert an identity
490 if (OpNo == NumOperands && NewTy == C->getType())
491 return getVM()[V] = C;
493 // Okay, we need to create a new constant. We've already processed some or
494 // all of the operands, set them all up now.
495 SmallVector<Constant*, 8> Ops;
496 Ops.reserve(NumOperands);
497 for (unsigned j = 0; j != OpNo; ++j)
498 Ops.push_back(cast<Constant>(C->getOperand(j)));
500 // If one of the operands mismatch, push it and the other mapped operands.
501 if (OpNo != NumOperands) {
502 Ops.push_back(cast<Constant>(Mapped));
504 // Map the rest of the operands that aren't processed yet.
505 for (++OpNo; OpNo != NumOperands; ++OpNo) {
506 Mapped = mapValueOrNull(C->getOperand(OpNo));
509 Ops.push_back(cast<Constant>(Mapped));
512 Type *NewSrcTy = nullptr;
514 if (auto *GEPO = dyn_cast<GEPOperator>(C))
515 NewSrcTy = TypeMapper->remapType(GEPO->getSourceElementType());
517 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
518 return getVM()[V] = CE->getWithOperands(Ops, NewTy, false, NewSrcTy);
519 if (isa<ConstantArray>(C))
520 return getVM()[V] = ConstantArray::get(cast<ArrayType>(NewTy), Ops);
521 if (isa<ConstantStruct>(C))
522 return getVM()[V] = ConstantStruct::get(cast<StructType>(NewTy), Ops);
523 if (isa<ConstantVector>(C))
524 return getVM()[V] = ConstantVector::get(Ops);
525 // If this is a no-operand constant, it must be because the type was remapped.
526 if (isa<PoisonValue>(C))
527 return getVM()[V] = PoisonValue::get(NewTy);
528 if (isa<UndefValue>(C))
529 return getVM()[V] = UndefValue::get(NewTy);
530 if (isa<ConstantAggregateZero>(C))
531 return getVM()[V] = ConstantAggregateZero::get(NewTy);
532 if (isa<ConstantTargetNone>(C))
533 return getVM()[V] = Constant::getNullValue(NewTy);
534 assert(isa<ConstantPointerNull>(C));
535 return getVM()[V] = ConstantPointerNull::get(cast<PointerType>(NewTy));
538 Value *Mapper::mapBlockAddress(const BlockAddress &BA) {
539 Function *F = cast<Function>(mapValue(BA.getFunction()));
541 // F may not have materialized its initializer. In that case, create a
542 // dummy basic block for now, and replace it once we've materialized all
546 DelayedBBs.push_back(DelayedBasicBlock(BA));
547 BB = DelayedBBs.back().TempBB.get();
549 BB = cast_or_null<BasicBlock>(mapValue(BA.getBasicBlock()));
552 return getVM()[&BA] = BlockAddress::get(F, BB ? BB : BA.getBasicBlock());
555 Metadata *Mapper::mapToMetadata(const Metadata *Key, Metadata *Val) {
556 getVM().MD()[Key].reset(Val);
560 Metadata *Mapper::mapToSelf(const Metadata *MD) {
561 return mapToMetadata(MD, const_cast<Metadata *>(MD));
564 std::optional<Metadata *> MDNodeMapper::tryToMapOperand(const Metadata *Op) {
568 if (std::optional<Metadata *> MappedOp = M.mapSimpleMetadata(Op)) {
570 if (auto *CMD = dyn_cast<ConstantAsMetadata>(Op))
571 assert((!*MappedOp || M.getVM().count(CMD->getValue()) ||
572 M.getVM().getMappedMD(Op)) &&
573 "Expected Value to be memoized");
575 assert((isa<MDString>(Op) || M.getVM().getMappedMD(Op)) &&
576 "Expected result to be memoized");
581 const MDNode &N = *cast<MDNode>(Op);
583 return mapDistinctNode(N);
587 MDNode *MDNodeMapper::mapDistinctNode(const MDNode &N) {
588 assert(N.isDistinct() && "Expected a distinct node");
589 assert(!M.getVM().getMappedMD(&N) && "Expected an unmapped node");
590 Metadata *NewM = nullptr;
592 if (M.Flags & RF_ReuseAndMutateDistinctMDs) {
593 NewM = M.mapToSelf(&N);
595 NewM = MDNode::replaceWithDistinct(N.clone());
596 LLVM_DEBUG(dbgs() << "\nMap " << N << "\n"
597 << "To " << *NewM << "\n\n");
598 M.mapToMetadata(&N, NewM);
600 DistinctWorklist.push_back(cast<MDNode>(NewM));
602 return DistinctWorklist.back();
605 static ConstantAsMetadata *wrapConstantAsMetadata(const ConstantAsMetadata &CMD,
607 if (CMD.getValue() == MappedV)
608 return const_cast<ConstantAsMetadata *>(&CMD);
609 return MappedV ? ConstantAsMetadata::getConstant(MappedV) : nullptr;
612 std::optional<Metadata *> MDNodeMapper::getMappedOp(const Metadata *Op) const {
616 if (std::optional<Metadata *> MappedOp = M.getVM().getMappedMD(Op))
619 if (isa<MDString>(Op))
620 return const_cast<Metadata *>(Op);
622 if (auto *CMD = dyn_cast<ConstantAsMetadata>(Op))
623 return wrapConstantAsMetadata(*CMD, M.getVM().lookup(CMD->getValue()));
628 Metadata &MDNodeMapper::UniquedGraph::getFwdReference(MDNode &Op) {
629 auto Where = Info.find(&Op);
630 assert(Where != Info.end() && "Expected a valid reference");
632 auto &OpD = Where->second;
636 // Lazily construct a temporary node.
637 if (!OpD.Placeholder)
638 OpD.Placeholder = Op.clone();
640 return *OpD.Placeholder;
643 template <class OperandMapper>
644 void MDNodeMapper::remapOperands(MDNode &N, OperandMapper mapOperand) {
645 assert(!N.isUniqued() && "Expected distinct or temporary nodes");
646 for (unsigned I = 0, E = N.getNumOperands(); I != E; ++I) {
647 Metadata *Old = N.getOperand(I);
648 Metadata *New = mapOperand(Old);
650 LLVM_DEBUG(dbgs() << "Replacing Op " << Old << " with " << New << " in "
654 N.replaceOperandWith(I, New);
660 /// An entry in the worklist for the post-order traversal.
661 struct POTWorklistEntry {
662 MDNode *N; ///< Current node.
663 MDNode::op_iterator Op; ///< Current operand of \c N.
665 /// Keep a flag of whether operands have changed in the worklist to avoid
666 /// hitting the map in \a UniquedGraph.
667 bool HasChanged = false;
669 POTWorklistEntry(MDNode &N) : N(&N), Op(N.op_begin()) {}
672 } // end anonymous namespace
674 bool MDNodeMapper::createPOT(UniquedGraph &G, const MDNode &FirstN) {
675 assert(G.Info.empty() && "Expected a fresh traversal");
676 assert(FirstN.isUniqued() && "Expected uniqued node in POT");
678 // Construct a post-order traversal of the uniqued subgraph under FirstN.
679 bool AnyChanges = false;
680 SmallVector<POTWorklistEntry, 16> Worklist;
681 Worklist.push_back(POTWorklistEntry(const_cast<MDNode &>(FirstN)));
682 (void)G.Info[&FirstN];
683 while (!Worklist.empty()) {
684 // Start or continue the traversal through the this node's operands.
685 auto &WE = Worklist.back();
686 if (MDNode *N = visitOperands(G, WE.Op, WE.N->op_end(), WE.HasChanged)) {
687 // Push a new node to traverse first.
688 Worklist.push_back(POTWorklistEntry(*N));
692 // Push the node onto the POT.
693 assert(WE.N->isUniqued() && "Expected only uniqued nodes");
694 assert(WE.Op == WE.N->op_end() && "Expected to visit all operands");
695 auto &D = G.Info[WE.N];
696 AnyChanges |= D.HasChanged = WE.HasChanged;
698 G.POT.push_back(WE.N);
700 // Pop the node off the worklist.
706 MDNode *MDNodeMapper::visitOperands(UniquedGraph &G, MDNode::op_iterator &I,
707 MDNode::op_iterator E, bool &HasChanged) {
709 Metadata *Op = *I++; // Increment even on early return.
710 if (std::optional<Metadata *> MappedOp = tryToMapOperand(Op)) {
711 // Check if the operand changes.
712 HasChanged |= Op != *MappedOp;
716 // A uniqued metadata node.
717 MDNode &OpN = *cast<MDNode>(Op);
718 assert(OpN.isUniqued() &&
719 "Only uniqued operands cannot be mapped immediately");
720 if (G.Info.insert(std::make_pair(&OpN, Data())).second)
721 return &OpN; // This is a new one. Return it.
726 void MDNodeMapper::UniquedGraph::propagateChanges() {
730 for (MDNode *N : POT) {
735 if (llvm::none_of(N->operands(), [&](const Metadata *Op) {
736 auto Where = Info.find(Op);
737 return Where != Info.end() && Where->second.HasChanged;
741 AnyChanges = D.HasChanged = true;
743 } while (AnyChanges);
746 void MDNodeMapper::mapNodesInPOT(UniquedGraph &G) {
747 // Construct uniqued nodes, building forward references as necessary.
748 SmallVector<MDNode *, 16> CyclicNodes;
749 for (auto *N : G.POT) {
752 // The node hasn't changed.
757 // Remember whether this node had a placeholder.
758 bool HadPlaceholder(D.Placeholder);
760 // Clone the uniqued node and remap the operands.
761 TempMDNode ClonedN = D.Placeholder ? std::move(D.Placeholder) : N->clone();
762 remapOperands(*ClonedN, [this, &D, &G](Metadata *Old) {
763 if (std::optional<Metadata *> MappedOp = getMappedOp(Old))
766 assert(G.Info[Old].ID > D.ID && "Expected a forward reference");
767 return &G.getFwdReference(*cast<MDNode>(Old));
770 auto *NewN = MDNode::replaceWithUniqued(std::move(ClonedN));
771 if (N && NewN && N != NewN) {
772 LLVM_DEBUG(dbgs() << "\nMap " << *N << "\n"
773 << "To " << *NewN << "\n\n");
776 M.mapToMetadata(N, NewN);
778 // Nodes that were referenced out of order in the POT are involved in a
781 CyclicNodes.push_back(NewN);
785 for (auto *N : CyclicNodes)
786 if (!N->isResolved())
790 Metadata *MDNodeMapper::map(const MDNode &N) {
791 assert(DistinctWorklist.empty() && "MDNodeMapper::map is not recursive");
792 assert(!(M.Flags & RF_NoModuleLevelChanges) &&
793 "MDNodeMapper::map assumes module-level changes");
795 // Require resolved nodes whenever metadata might be remapped.
796 assert(N.isResolved() && "Unexpected unresolved node");
799 N.isUniqued() ? mapTopLevelUniquedNode(N) : mapDistinctNode(N);
800 while (!DistinctWorklist.empty())
801 remapOperands(*DistinctWorklist.pop_back_val(), [this](Metadata *Old) {
802 if (std::optional<Metadata *> MappedOp = tryToMapOperand(Old))
804 return mapTopLevelUniquedNode(*cast<MDNode>(Old));
809 Metadata *MDNodeMapper::mapTopLevelUniquedNode(const MDNode &FirstN) {
810 assert(FirstN.isUniqued() && "Expected uniqued node");
812 // Create a post-order traversal of uniqued nodes under FirstN.
814 if (!createPOT(G, FirstN)) {
815 // Return early if no nodes have changed.
816 for (const MDNode *N : G.POT)
818 return &const_cast<MDNode &>(FirstN);
821 // Update graph with all nodes that have changed.
822 G.propagateChanges();
824 // Map all the nodes in the graph.
827 // Return the original node, remapped.
828 return *getMappedOp(&FirstN);
831 std::optional<Metadata *> Mapper::mapSimpleMetadata(const Metadata *MD) {
832 // If the value already exists in the map, use it.
833 if (std::optional<Metadata *> NewMD = getVM().getMappedMD(MD))
836 if (isa<MDString>(MD))
837 return const_cast<Metadata *>(MD);
839 // This is a module-level metadata. If nothing at the module level is
840 // changing, use an identity mapping.
841 if ((Flags & RF_NoModuleLevelChanges))
842 return const_cast<Metadata *>(MD);
844 if (auto *CMD = dyn_cast<ConstantAsMetadata>(MD)) {
845 // Don't memoize ConstantAsMetadata. Instead of lasting until the
846 // LLVMContext is destroyed, they can be deleted when the GlobalValue they
847 // reference is destructed. These aren't super common, so the extra
848 // indirection isn't that expensive.
849 return wrapConstantAsMetadata(*CMD, mapValue(CMD->getValue()));
852 assert(isa<MDNode>(MD) && "Expected a metadata node");
857 Metadata *Mapper::mapMetadata(const Metadata *MD) {
858 assert(MD && "Expected valid metadata");
859 assert(!isa<LocalAsMetadata>(MD) && "Unexpected local metadata");
861 if (std::optional<Metadata *> NewMD = mapSimpleMetadata(MD))
864 return MDNodeMapper(*this).map(*cast<MDNode>(MD));
867 void Mapper::flush() {
868 // Flush out the worklist of global values.
869 while (!Worklist.empty()) {
870 WorklistEntry E = Worklist.pop_back_val();
871 CurrentMCID = E.MCID;
873 case WorklistEntry::MapGlobalInit:
874 E.Data.GVInit.GV->setInitializer(mapConstant(E.Data.GVInit.Init));
875 remapGlobalObjectMetadata(*E.Data.GVInit.GV);
877 case WorklistEntry::MapAppendingVar: {
878 unsigned PrefixSize = AppendingInits.size() - E.AppendingGVNumNewMembers;
879 // mapAppendingVariable call can change AppendingInits if initalizer for
880 // the variable depends on another appending global, because of that inits
881 // need to be extracted and updated before the call.
882 SmallVector<Constant *, 8> NewInits(
883 drop_begin(AppendingInits, PrefixSize));
884 AppendingInits.resize(PrefixSize);
885 mapAppendingVariable(*E.Data.AppendingGV.GV,
886 E.Data.AppendingGV.InitPrefix,
887 E.AppendingGVIsOldCtorDtor, ArrayRef(NewInits));
890 case WorklistEntry::MapAliasOrIFunc: {
891 GlobalValue *GV = E.Data.AliasOrIFunc.GV;
892 Constant *Target = mapConstant(E.Data.AliasOrIFunc.Target);
893 if (auto *GA = dyn_cast<GlobalAlias>(GV))
894 GA->setAliasee(Target);
895 else if (auto *GI = dyn_cast<GlobalIFunc>(GV))
896 GI->setResolver(Target);
898 llvm_unreachable("Not alias or ifunc");
901 case WorklistEntry::RemapFunction:
902 remapFunction(*E.Data.RemapF);
908 // Finish logic for block addresses now that all global values have been
910 while (!DelayedBBs.empty()) {
911 DelayedBasicBlock DBB = DelayedBBs.pop_back_val();
912 BasicBlock *BB = cast_or_null<BasicBlock>(mapValue(DBB.OldBB));
913 DBB.TempBB->replaceAllUsesWith(BB ? BB : DBB.OldBB);
917 void Mapper::remapInstruction(Instruction *I) {
919 for (Use &Op : I->operands()) {
920 Value *V = mapValue(Op);
921 // If we aren't ignoring missing entries, assert that something happened.
925 assert((Flags & RF_IgnoreMissingLocals) &&
926 "Referenced value not in value map!");
929 // Remap phi nodes' incoming blocks.
930 if (PHINode *PN = dyn_cast<PHINode>(I)) {
931 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
932 Value *V = mapValue(PN->getIncomingBlock(i));
933 // If we aren't ignoring missing entries, assert that something happened.
935 PN->setIncomingBlock(i, cast<BasicBlock>(V));
937 assert((Flags & RF_IgnoreMissingLocals) &&
938 "Referenced block not in value map!");
942 // Remap attached metadata.
943 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
944 I->getAllMetadata(MDs);
945 for (const auto &MI : MDs) {
946 MDNode *Old = MI.second;
947 MDNode *New = cast_or_null<MDNode>(mapMetadata(Old));
949 I->setMetadata(MI.first, New);
955 // If the instruction's type is being remapped, do so now.
956 if (auto *CB = dyn_cast<CallBase>(I)) {
957 SmallVector<Type *, 3> Tys;
958 FunctionType *FTy = CB->getFunctionType();
959 Tys.reserve(FTy->getNumParams());
960 for (Type *Ty : FTy->params())
961 Tys.push_back(TypeMapper->remapType(Ty));
962 CB->mutateFunctionType(FunctionType::get(
963 TypeMapper->remapType(I->getType()), Tys, FTy->isVarArg()));
965 LLVMContext &C = CB->getContext();
966 AttributeList Attrs = CB->getAttributes();
967 for (unsigned i = 0; i < Attrs.getNumAttrSets(); ++i) {
968 for (int AttrIdx = Attribute::FirstTypeAttr;
969 AttrIdx <= Attribute::LastTypeAttr; AttrIdx++) {
970 Attribute::AttrKind TypedAttr = (Attribute::AttrKind)AttrIdx;
972 Attrs.getAttributeAtIndex(i, TypedAttr).getValueAsType()) {
973 Attrs = Attrs.replaceAttributeTypeAtIndex(C, i, TypedAttr,
974 TypeMapper->remapType(Ty));
979 CB->setAttributes(Attrs);
982 if (auto *AI = dyn_cast<AllocaInst>(I))
983 AI->setAllocatedType(TypeMapper->remapType(AI->getAllocatedType()));
984 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
985 GEP->setSourceElementType(
986 TypeMapper->remapType(GEP->getSourceElementType()));
987 GEP->setResultElementType(
988 TypeMapper->remapType(GEP->getResultElementType()));
990 I->mutateType(TypeMapper->remapType(I->getType()));
993 void Mapper::remapGlobalObjectMetadata(GlobalObject &GO) {
994 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
995 GO.getAllMetadata(MDs);
997 for (const auto &I : MDs)
998 GO.addMetadata(I.first, *cast<MDNode>(mapMetadata(I.second)));
1001 void Mapper::remapFunction(Function &F) {
1002 // Remap the operands.
1003 for (Use &Op : F.operands())
1007 // Remap the metadata attachments.
1008 remapGlobalObjectMetadata(F);
1010 // Remap the argument types.
1012 for (Argument &A : F.args())
1013 A.mutateType(TypeMapper->remapType(A.getType()));
1015 // Remap the instructions.
1016 for (BasicBlock &BB : F)
1017 for (Instruction &I : BB)
1018 remapInstruction(&I);
1021 void Mapper::mapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
1023 ArrayRef<Constant *> NewMembers) {
1024 SmallVector<Constant *, 16> Elements;
1026 unsigned NumElements =
1027 cast<ArrayType>(InitPrefix->getType())->getNumElements();
1028 for (unsigned I = 0; I != NumElements; ++I)
1029 Elements.push_back(InitPrefix->getAggregateElement(I));
1032 PointerType *VoidPtrTy;
1034 if (IsOldCtorDtor) {
1035 // FIXME: This upgrade is done during linking to support the C API. See
1036 // also IRLinker::linkAppendingVarProto() in IRMover.cpp.
1037 VoidPtrTy = PointerType::getUnqual(GV.getContext());
1038 auto &ST = *cast<StructType>(NewMembers.front()->getType());
1039 Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
1040 EltTy = StructType::get(GV.getContext(), Tys, false);
1043 for (auto *V : NewMembers) {
1045 if (IsOldCtorDtor) {
1046 auto *S = cast<ConstantStruct>(V);
1047 auto *E1 = cast<Constant>(mapValue(S->getOperand(0)));
1048 auto *E2 = cast<Constant>(mapValue(S->getOperand(1)));
1049 Constant *Null = Constant::getNullValue(VoidPtrTy);
1050 NewV = ConstantStruct::get(cast<StructType>(EltTy), E1, E2, Null);
1052 NewV = cast_or_null<Constant>(mapValue(V));
1054 Elements.push_back(NewV);
1058 ConstantArray::get(cast<ArrayType>(GV.getValueType()), Elements));
1061 void Mapper::scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init,
1063 assert(AlreadyScheduled.insert(&GV).second && "Should not reschedule");
1064 assert(MCID < MCs.size() && "Invalid mapping context");
1067 WE.Kind = WorklistEntry::MapGlobalInit;
1069 WE.Data.GVInit.GV = &GV;
1070 WE.Data.GVInit.Init = &Init;
1071 Worklist.push_back(WE);
1074 void Mapper::scheduleMapAppendingVariable(GlobalVariable &GV,
1075 Constant *InitPrefix,
1077 ArrayRef<Constant *> NewMembers,
1079 assert(AlreadyScheduled.insert(&GV).second && "Should not reschedule");
1080 assert(MCID < MCs.size() && "Invalid mapping context");
1083 WE.Kind = WorklistEntry::MapAppendingVar;
1085 WE.Data.AppendingGV.GV = &GV;
1086 WE.Data.AppendingGV.InitPrefix = InitPrefix;
1087 WE.AppendingGVIsOldCtorDtor = IsOldCtorDtor;
1088 WE.AppendingGVNumNewMembers = NewMembers.size();
1089 Worklist.push_back(WE);
1090 AppendingInits.append(NewMembers.begin(), NewMembers.end());
1093 void Mapper::scheduleMapAliasOrIFunc(GlobalValue &GV, Constant &Target,
1095 assert(AlreadyScheduled.insert(&GV).second && "Should not reschedule");
1096 assert((isa<GlobalAlias>(GV) || isa<GlobalIFunc>(GV)) &&
1097 "Should be alias or ifunc");
1098 assert(MCID < MCs.size() && "Invalid mapping context");
1101 WE.Kind = WorklistEntry::MapAliasOrIFunc;
1103 WE.Data.AliasOrIFunc.GV = &GV;
1104 WE.Data.AliasOrIFunc.Target = &Target;
1105 Worklist.push_back(WE);
1108 void Mapper::scheduleRemapFunction(Function &F, unsigned MCID) {
1109 assert(AlreadyScheduled.insert(&F).second && "Should not reschedule");
1110 assert(MCID < MCs.size() && "Invalid mapping context");
1113 WE.Kind = WorklistEntry::RemapFunction;
1115 WE.Data.RemapF = &F;
1116 Worklist.push_back(WE);
1119 void Mapper::addFlags(RemapFlags Flags) {
1120 assert(!hasWorkToDo() && "Expected to have flushed the worklist");
1121 this->Flags = this->Flags | Flags;
1124 static Mapper *getAsMapper(void *pImpl) {
1125 return reinterpret_cast<Mapper *>(pImpl);
1130 class FlushingMapper {
1134 explicit FlushingMapper(void *pImpl) : M(*getAsMapper(pImpl)) {
1135 assert(!M.hasWorkToDo() && "Expected to be flushed");
1138 ~FlushingMapper() { M.flush(); }
1140 Mapper *operator->() const { return &M; }
1143 } // end anonymous namespace
1145 ValueMapper::ValueMapper(ValueToValueMapTy &VM, RemapFlags Flags,
1146 ValueMapTypeRemapper *TypeMapper,
1147 ValueMaterializer *Materializer)
1148 : pImpl(new Mapper(VM, Flags, TypeMapper, Materializer)) {}
1150 ValueMapper::~ValueMapper() { delete getAsMapper(pImpl); }
1153 ValueMapper::registerAlternateMappingContext(ValueToValueMapTy &VM,
1154 ValueMaterializer *Materializer) {
1155 return getAsMapper(pImpl)->registerAlternateMappingContext(VM, Materializer);
1158 void ValueMapper::addFlags(RemapFlags Flags) {
1159 FlushingMapper(pImpl)->addFlags(Flags);
1162 Value *ValueMapper::mapValue(const Value &V) {
1163 return FlushingMapper(pImpl)->mapValue(&V);
1166 Constant *ValueMapper::mapConstant(const Constant &C) {
1167 return cast_or_null<Constant>(mapValue(C));
1170 Metadata *ValueMapper::mapMetadata(const Metadata &MD) {
1171 return FlushingMapper(pImpl)->mapMetadata(&MD);
1174 MDNode *ValueMapper::mapMDNode(const MDNode &N) {
1175 return cast_or_null<MDNode>(mapMetadata(N));
1178 void ValueMapper::remapInstruction(Instruction &I) {
1179 FlushingMapper(pImpl)->remapInstruction(&I);
1182 void ValueMapper::remapFunction(Function &F) {
1183 FlushingMapper(pImpl)->remapFunction(F);
1186 void ValueMapper::remapGlobalObjectMetadata(GlobalObject &GO) {
1187 FlushingMapper(pImpl)->remapGlobalObjectMetadata(GO);
1190 void ValueMapper::scheduleMapGlobalInitializer(GlobalVariable &GV,
1193 getAsMapper(pImpl)->scheduleMapGlobalInitializer(GV, Init, MCID);
1196 void ValueMapper::scheduleMapAppendingVariable(GlobalVariable &GV,
1197 Constant *InitPrefix,
1199 ArrayRef<Constant *> NewMembers,
1201 getAsMapper(pImpl)->scheduleMapAppendingVariable(
1202 GV, InitPrefix, IsOldCtorDtor, NewMembers, MCID);
1205 void ValueMapper::scheduleMapGlobalAlias(GlobalAlias &GA, Constant &Aliasee,
1207 getAsMapper(pImpl)->scheduleMapAliasOrIFunc(GA, Aliasee, MCID);
1210 void ValueMapper::scheduleMapGlobalIFunc(GlobalIFunc &GI, Constant &Resolver,
1212 getAsMapper(pImpl)->scheduleMapAliasOrIFunc(GI, Resolver, MCID);
1215 void ValueMapper::scheduleRemapFunction(Function &F, unsigned MCID) {
1216 getAsMapper(pImpl)->scheduleRemapFunction(F, MCID);