LLVM 22.0.0git
ValueMapper.cpp
Go to the documentation of this file.
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
15#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/DenseSet.h"
18#include "llvm/ADT/STLExtras.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"
26#include "llvm/IR/Function.h"
27#include "llvm/IR/GlobalAlias.h"
28#include "llvm/IR/GlobalIFunc.h"
31#include "llvm/IR/InlineAsm.h"
32#include "llvm/IR/Instruction.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"
40#include "llvm/Support/Debug.h"
41#include <cassert>
42#include <limits>
43#include <memory>
44#include <utility>
45
46using namespace llvm;
47
48#define DEBUG_TYPE "value-mapper"
49
50// Out of line method to get vtable etc for class.
51void ValueMapTypeRemapper::anchor() {}
52void ValueMaterializer::anchor() {}
53
54namespace {
55
56/// A basic block used in a BlockAddress whose function body is not yet
57/// materialized.
58struct DelayedBasicBlock {
59 BasicBlock *OldBB;
60 std::unique_ptr<BasicBlock> TempBB;
61
62 DelayedBasicBlock(const BlockAddress &Old)
63 : OldBB(Old.getBasicBlock()),
64 TempBB(BasicBlock::Create(Old.getContext())) {}
65};
66
67struct WorklistEntry {
68 enum EntryKind {
69 MapGlobalInit,
70 MapAppendingVar,
71 MapAliasOrIFunc,
73 };
74 struct GVInitTy {
77 };
78 struct AppendingGVTy {
80 Constant *InitPrefix;
81 };
82 struct AliasOrIFuncTy {
83 GlobalValue *GV;
85 };
86
87 unsigned Kind : 2;
88 unsigned MCID : 29;
89 unsigned AppendingGVIsOldCtorDtor : 1;
90 unsigned AppendingGVNumNewMembers;
91 union {
92 GVInitTy GVInit;
93 AppendingGVTy AppendingGV;
94 AliasOrIFuncTy AliasOrIFunc;
95 Function *RemapF;
96 } Data;
97};
98
99struct MappingContext {
101 ValueMaterializer *Materializer = nullptr;
102
103 /// Construct a MappingContext with a value map and materializer.
104 explicit MappingContext(ValueToValueMapTy &VM,
105 ValueMaterializer *Materializer = nullptr)
106 : VM(&VM), Materializer(Materializer) {}
107};
108
109class Mapper {
110 friend class MDNodeMapper;
111
112#ifndef NDEBUG
113 DenseSet<GlobalValue *> AlreadyScheduled;
114#endif
115
117 ValueMapTypeRemapper *TypeMapper;
118 unsigned CurrentMCID = 0;
122 SmallVector<Constant *, 16> AppendingInits;
123 const MetadataPredicate *IdentityMD;
124
125public:
126 Mapper(ValueToValueMapTy &VM, RemapFlags Flags,
127 ValueMapTypeRemapper *TypeMapper, ValueMaterializer *Materializer,
128 const MetadataPredicate *IdentityMD)
129 : Flags(Flags), TypeMapper(TypeMapper),
130 MCs(1, MappingContext(VM, Materializer)), IdentityMD(IdentityMD) {}
131
132 /// ValueMapper should explicitly call \a flush() before destruction.
133 ~Mapper() { assert(!hasWorkToDo() && "Expected to be flushed"); }
134
135 bool hasWorkToDo() const { return !Worklist.empty(); }
136
137 unsigned
138 registerAlternateMappingContext(ValueToValueMapTy &VM,
139 ValueMaterializer *Materializer = nullptr) {
140 MCs.push_back(MappingContext(VM, Materializer));
141 return MCs.size() - 1;
142 }
143
144 void addFlags(RemapFlags Flags);
145
146 void remapGlobalObjectMetadata(GlobalObject &GO);
147
148 Value *mapValue(const Value *V);
149 void remapInstruction(Instruction *I);
150 void remapFunction(Function &F);
151 void remapDbgRecord(DbgRecord &DVR);
152
153 Constant *mapConstant(const Constant *C) {
154 return cast_or_null<Constant>(mapValue(C));
155 }
156
157 /// Map metadata.
158 ///
159 /// Find the mapping for MD. Guarantees that the return will be resolved
160 /// (not an MDNode, or MDNode::isResolved() returns true).
161 Metadata *mapMetadata(const Metadata *MD);
162
163 void scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init,
164 unsigned MCID);
165 void scheduleMapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
166 bool IsOldCtorDtor,
167 ArrayRef<Constant *> NewMembers,
168 unsigned MCID);
169 void scheduleMapAliasOrIFunc(GlobalValue &GV, Constant &Target,
170 unsigned MCID);
171 void scheduleRemapFunction(Function &F, unsigned MCID);
172
173 void flush();
174
175private:
176 void mapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
177 bool IsOldCtorDtor,
178 ArrayRef<Constant *> NewMembers);
179
180 ValueToValueMapTy &getVM() { return *MCs[CurrentMCID].VM; }
181 ValueMaterializer *getMaterializer() { return MCs[CurrentMCID].Materializer; }
182
183 Value *mapBlockAddress(const BlockAddress &BA);
184
185 /// Map metadata that doesn't require visiting operands.
186 std::optional<Metadata *> mapSimpleMetadata(const Metadata *MD);
187
188 Metadata *mapToMetadata(const Metadata *Key, Metadata *Val);
189 Metadata *mapToSelf(const Metadata *MD);
190};
191
192class MDNodeMapper {
193 Mapper &M;
194
195 /// Data about a node in \a UniquedGraph.
196 struct Data {
197 bool HasChanged = false;
198 unsigned ID = std::numeric_limits<unsigned>::max();
199 TempMDNode Placeholder;
200 };
201
202 /// A graph of uniqued nodes.
203 struct UniquedGraph {
205 SmallVector<MDNode *, 16> POT; // Post-order traversal.
206
207 /// Propagate changed operands through the post-order traversal.
208 ///
209 /// Iteratively update \a Data::HasChanged for each node based on \a
210 /// Data::HasChanged of its operands, until fixed point.
211 void propagateChanges();
212
213 /// Get a forward reference to a node to use as an operand.
214 Metadata &getFwdReference(MDNode &Op);
215 };
216
217 /// Worklist of distinct nodes whose operands need to be remapped.
218 SmallVector<MDNode *, 16> DistinctWorklist;
219
220 // Storage for a UniquedGraph.
222 SmallVector<MDNode *, 16> POTStorage;
223
224public:
225 MDNodeMapper(Mapper &M) : M(M) {}
226
227 /// Map a metadata node (and its transitive operands).
228 ///
229 /// Map all the (unmapped) nodes in the subgraph under \c N. The iterative
230 /// algorithm handles distinct nodes and uniqued node subgraphs using
231 /// different strategies.
232 ///
233 /// Distinct nodes are immediately mapped and added to \a DistinctWorklist
234 /// using \a mapDistinctNode(). Their mapping can always be computed
235 /// immediately without visiting operands, even if their operands change.
236 ///
237 /// The mapping for uniqued nodes depends on whether their operands change.
238 /// \a mapTopLevelUniquedNode() traverses the transitive uniqued subgraph of
239 /// a node to calculate uniqued node mappings in bulk. Distinct leafs are
240 /// added to \a DistinctWorklist with \a mapDistinctNode().
241 ///
242 /// After mapping \c N itself, this function remaps the operands of the
243 /// distinct nodes in \a DistinctWorklist until the entire subgraph under \c
244 /// N has been mapped.
245 Metadata *map(const MDNode &N);
246
247private:
248 /// Map a top-level uniqued node and the uniqued subgraph underneath it.
249 ///
250 /// This builds up a post-order traversal of the (unmapped) uniqued subgraph
251 /// underneath \c FirstN and calculates the nodes' mapping. Each node uses
252 /// the identity mapping (\a Mapper::mapToSelf()) as long as all of its
253 /// operands uses the identity mapping.
254 ///
255 /// The algorithm works as follows:
256 ///
257 /// 1. \a createPOT(): traverse the uniqued subgraph under \c FirstN and
258 /// save the post-order traversal in the given \a UniquedGraph, tracking
259 /// nodes' operands change.
260 ///
261 /// 2. \a UniquedGraph::propagateChanges(): propagate changed operands
262 /// through the \a UniquedGraph until fixed point, following the rule
263 /// that if a node changes, any node that references must also change.
264 ///
265 /// 3. \a mapNodesInPOT(): map the uniqued nodes, creating new uniqued nodes
266 /// (referencing new operands) where necessary.
267 Metadata *mapTopLevelUniquedNode(const MDNode &FirstN);
268
269 /// Try to map the operand of an \a MDNode.
270 ///
271 /// If \c Op is already mapped, return the mapping. If it's not an \a
272 /// MDNode, compute and return the mapping. If it's a distinct \a MDNode,
273 /// return the result of \a mapDistinctNode().
274 ///
275 /// \return std::nullopt if \c Op is an unmapped uniqued \a MDNode.
276 /// \post getMappedOp(Op) only returns std::nullopt if this returns
277 /// std::nullopt.
278 std::optional<Metadata *> tryToMapOperand(const Metadata *Op);
279
280 /// Map a distinct node.
281 ///
282 /// Return the mapping for the distinct node \c N, saving the result in \a
283 /// DistinctWorklist for later remapping.
284 ///
285 /// \pre \c N is not yet mapped.
286 /// \pre \c N.isDistinct().
287 MDNode *mapDistinctNode(const MDNode &N);
288
289 /// Get a previously mapped node.
290 std::optional<Metadata *> getMappedOp(const Metadata *Op) const;
291
292 /// Create a post-order traversal of an unmapped uniqued node subgraph.
293 ///
294 /// This traverses the metadata graph deeply enough to map \c FirstN. It
295 /// uses \a tryToMapOperand() (via \a Mapper::mapSimplifiedNode()), so any
296 /// metadata that has already been mapped will not be part of the POT.
297 ///
298 /// Each node that has a changed operand from outside the graph (e.g., a
299 /// distinct node, an already-mapped uniqued node, or \a ConstantAsMetadata)
300 /// is marked with \a Data::HasChanged.
301 ///
302 /// \return \c true if any nodes in \c G have \a Data::HasChanged.
303 /// \post \c G.POT is a post-order traversal ending with \c FirstN.
304 /// \post \a Data::hasChanged in \c G.Info indicates whether any node needs
305 /// to change because of operands outside the graph.
306 bool createPOT(UniquedGraph &G, const MDNode &FirstN);
307
308 /// Visit the operands of a uniqued node in the POT.
309 ///
310 /// Visit the operands in the range from \c I to \c E, returning the first
311 /// uniqued node we find that isn't yet in \c G. \c I is always advanced to
312 /// where to continue the loop through the operands.
313 ///
314 /// This sets \c HasChanged if any of the visited operands change.
315 MDNode *visitOperands(UniquedGraph &G, MDNode::op_iterator &I,
316 MDNode::op_iterator E, bool &HasChanged);
317
318 /// Map all the nodes in the given uniqued graph.
319 ///
320 /// This visits all the nodes in \c G in post-order, using the identity
321 /// mapping or creating a new node depending on \a Data::HasChanged.
322 ///
323 /// \pre \a getMappedOp() returns std::nullopt for nodes in \c G, but not for
324 /// any of their operands outside of \c G. \pre \a Data::HasChanged is true
325 /// for a node in \c G iff any of its operands have changed. \post \a
326 /// getMappedOp() returns the mapped node for every node in \c G.
327 void mapNodesInPOT(UniquedGraph &G);
328
329 /// Remap a node's operands using the given functor.
330 ///
331 /// Iterate through the operands of \c N and update them in place using \c
332 /// mapOperand.
333 ///
334 /// \pre N.isDistinct() or N.isTemporary().
335 template <class OperandMapper>
336 void remapOperands(MDNode &N, OperandMapper mapOperand);
337};
338
339} // end anonymous namespace
340
341Value *Mapper::mapValue(const Value *V) {
342 ValueToValueMapTy::iterator I = getVM().find(V);
343
344 // If the value already exists in the map, use it.
345 if (I != getVM().end()) {
346 assert(I->second && "Unexpected null mapping");
347 return I->second;
348 }
349
350 // If we have a materializer and it can materialize a value, use that.
351 if (auto *Materializer = getMaterializer()) {
352 if (Value *NewV = Materializer->materialize(const_cast<Value *>(V))) {
353 getVM()[V] = NewV;
354 return NewV;
355 }
356 }
357
358 // Global values do not need to be seeded into the VM if they
359 // are using the identity mapping.
360 if (isa<GlobalValue>(V)) {
362 return nullptr;
363 return getVM()[V] = const_cast<Value *>(V);
364 }
365
366 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
367 // Inline asm may need *type* remapping.
368 FunctionType *NewTy = IA->getFunctionType();
369 if (TypeMapper) {
370 NewTy = cast<FunctionType>(TypeMapper->remapType(NewTy));
371
372 if (NewTy != IA->getFunctionType())
373 V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),
374 IA->hasSideEffects(), IA->isAlignStack(),
375 IA->getDialect(), IA->canThrow());
376 }
377
378 return getVM()[V] = const_cast<Value *>(V);
379 }
380
381 if (const auto *MDV = dyn_cast<MetadataAsValue>(V)) {
382 const Metadata *MD = MDV->getMetadata();
383
384 if (auto *LAM = dyn_cast<LocalAsMetadata>(MD)) {
385 // Look through to grab the local value.
386 if (Value *LV = mapValue(LAM->getValue())) {
387 if (V == LAM->getValue())
388 return const_cast<Value *>(V);
389 return MetadataAsValue::get(V->getContext(), ValueAsMetadata::get(LV));
390 }
391
392 // FIXME: always return nullptr once Verifier::verifyDominatesUse()
393 // ensures metadata operands only reference defined SSA values.
394 return (Flags & RF_IgnoreMissingLocals)
395 ? nullptr
396 : MetadataAsValue::get(V->getContext(),
397 MDTuple::get(V->getContext(), {}));
398 }
399 if (auto *AL = dyn_cast<DIArgList>(MD)) {
401 for (auto *VAM : AL->getArgs()) {
402 // Map both Local and Constant VAMs here; they will both ultimately
403 // be mapped via mapValue. The exceptions are constants when we have no
404 // module level changes and locals when they have no existing mapped
405 // value and RF_IgnoreMissingLocals is set; these have identity
406 // mappings.
407 if ((Flags & RF_NoModuleLevelChanges) && isa<ConstantAsMetadata>(VAM)) {
408 MappedArgs.push_back(VAM);
409 } else if (Value *LV = mapValue(VAM->getValue())) {
410 MappedArgs.push_back(
411 LV == VAM->getValue() ? VAM : ValueAsMetadata::get(LV));
412 } else if ((Flags & RF_IgnoreMissingLocals) && isa<LocalAsMetadata>(VAM)) {
413 MappedArgs.push_back(VAM);
414 } else {
415 // If we cannot map the value, set the argument as poison.
417 PoisonValue::get(VAM->getValue()->getType())));
418 }
419 }
420 return MetadataAsValue::get(V->getContext(),
421 DIArgList::get(V->getContext(), MappedArgs));
422 }
423
424 // If this is a module-level metadata and we know that nothing at the module
425 // level is changing, then use an identity mapping.
426 if (Flags & RF_NoModuleLevelChanges)
427 return getVM()[V] = const_cast<Value *>(V);
428
429 // Map the metadata and turn it into a value.
430 auto *MappedMD = mapMetadata(MD);
431 if (MD == MappedMD)
432 return getVM()[V] = const_cast<Value *>(V);
433 return getVM()[V] = MetadataAsValue::get(V->getContext(), MappedMD);
434 }
435
436 // Okay, this either must be a constant (which may or may not be mappable) or
437 // is something that is not in the mapping table.
438 Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
439 if (!C)
440 return nullptr;
441
442 if (BlockAddress *BA = dyn_cast<BlockAddress>(C))
443 return mapBlockAddress(*BA);
444
445 if (const auto *E = dyn_cast<DSOLocalEquivalent>(C)) {
446 auto *Val = mapValue(E->getGlobalValue());
447 GlobalValue *GV = dyn_cast<GlobalValue>(Val);
448 if (GV)
449 return getVM()[E] = DSOLocalEquivalent::get(GV);
450
451 auto *Func = cast<Function>(Val->stripPointerCastsAndAliases());
452 Type *NewTy = E->getType();
453 if (TypeMapper)
454 NewTy = TypeMapper->remapType(NewTy);
455 return getVM()[E] = llvm::ConstantExpr::getBitCast(
456 DSOLocalEquivalent::get(Func), NewTy);
457 }
458
459 if (const auto *NC = dyn_cast<NoCFIValue>(C)) {
460 auto *Val = mapValue(NC->getGlobalValue());
461 GlobalValue *GV = cast<GlobalValue>(Val);
462 return getVM()[NC] = NoCFIValue::get(GV);
463 }
464
465 auto mapValueOrNull = [this](Value *V) {
466 auto Mapped = mapValue(V);
467 assert((Mapped || (Flags & RF_NullMapMissingGlobalValues)) &&
468 "Unexpected null mapping for constant operand without "
469 "NullMapMissingGlobalValues flag");
470 return Mapped;
471 };
472
473 // Otherwise, we have some other constant to remap. Start by checking to see
474 // if all operands have an identity remapping.
475 unsigned OpNo = 0, NumOperands = C->getNumOperands();
476 Value *Mapped = nullptr;
477 for (; OpNo != NumOperands; ++OpNo) {
478 Value *Op = C->getOperand(OpNo);
479 Mapped = mapValueOrNull(Op);
480 if (!Mapped)
481 return nullptr;
482 if (Mapped != Op)
483 break;
484 }
485
486 // See if the type mapper wants to remap the type as well.
487 Type *NewTy = C->getType();
488 if (TypeMapper)
489 NewTy = TypeMapper->remapType(NewTy);
490
491 // If the result type and all operands match up, then just insert an identity
492 // mapping.
493 if (OpNo == NumOperands && NewTy == C->getType())
494 return getVM()[V] = C;
495
496 // Okay, we need to create a new constant. We've already processed some or
497 // all of the operands, set them all up now.
499 Ops.reserve(NumOperands);
500 for (unsigned j = 0; j != OpNo; ++j)
501 Ops.push_back(cast<Constant>(C->getOperand(j)));
502
503 // If one of the operands mismatch, push it and the other mapped operands.
504 if (OpNo != NumOperands) {
505 Ops.push_back(cast<Constant>(Mapped));
506
507 // Map the rest of the operands that aren't processed yet.
508 for (++OpNo; OpNo != NumOperands; ++OpNo) {
509 Mapped = mapValueOrNull(C->getOperand(OpNo));
510 if (!Mapped)
511 return nullptr;
512 Ops.push_back(cast<Constant>(Mapped));
513 }
514 }
515 Type *NewSrcTy = nullptr;
516 if (TypeMapper)
517 if (auto *GEPO = dyn_cast<GEPOperator>(C))
518 NewSrcTy = TypeMapper->remapType(GEPO->getSourceElementType());
519
520 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
521 return getVM()[V] = CE->getWithOperands(Ops, NewTy, false, NewSrcTy);
522 if (isa<ConstantArray>(C))
523 return getVM()[V] = ConstantArray::get(cast<ArrayType>(NewTy), Ops);
524 if (isa<ConstantStruct>(C))
525 return getVM()[V] = ConstantStruct::get(cast<StructType>(NewTy), Ops);
526 if (isa<ConstantVector>(C))
527 return getVM()[V] = ConstantVector::get(Ops);
528 if (isa<ConstantPtrAuth>(C))
529 return getVM()[V] = ConstantPtrAuth::get(Ops[0], cast<ConstantInt>(Ops[1]),
530 cast<ConstantInt>(Ops[2]), Ops[3]);
531 // If this is a no-operand constant, it must be because the type was remapped.
532 if (isa<PoisonValue>(C))
533 return getVM()[V] = PoisonValue::get(NewTy);
534 if (isa<UndefValue>(C))
535 return getVM()[V] = UndefValue::get(NewTy);
536 if (isa<ConstantAggregateZero>(C))
537 return getVM()[V] = ConstantAggregateZero::get(NewTy);
538 if (isa<ConstantTargetNone>(C))
539 return getVM()[V] = Constant::getNullValue(NewTy);
540 assert(isa<ConstantPointerNull>(C));
541 return getVM()[V] = ConstantPointerNull::get(cast<PointerType>(NewTy));
542}
543
544void Mapper::remapDbgRecord(DbgRecord &DR) {
545 // Remap DILocations.
546 auto *MappedDILoc = mapMetadata(DR.getDebugLoc());
547 DR.setDebugLoc(DebugLoc(cast<DILocation>(MappedDILoc)));
548
549 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
550 // Remap labels.
551 DLR->setLabel(cast<DILabel>(mapMetadata(DLR->getLabel())));
552 return;
553 }
554
555 DbgVariableRecord &V = cast<DbgVariableRecord>(DR);
556 // Remap variables.
557 auto *MappedVar = mapMetadata(V.getVariable());
558 V.setVariable(cast<DILocalVariable>(MappedVar));
559
560 bool IgnoreMissingLocals = Flags & RF_IgnoreMissingLocals;
561
562 if (V.isDbgAssign()) {
563 auto *NewAddr = mapValue(V.getAddress());
564 if (!IgnoreMissingLocals && !NewAddr)
565 V.setKillAddress();
566 else if (NewAddr)
567 V.setAddress(NewAddr);
568 V.setAssignId(cast<DIAssignID>(mapMetadata(V.getAssignID())));
569 }
570
571 // Find Value operands and remap those.
572 SmallVector<Value *, 4> Vals(V.location_ops());
574 for (Value *Val : Vals)
575 NewVals.push_back(mapValue(Val));
576
577 // If there are no changes to the Value operands, finished.
578 if (Vals == NewVals)
579 return;
580
581 // Otherwise, do some replacement.
582 if (!IgnoreMissingLocals && llvm::is_contained(NewVals, nullptr)) {
583 V.setKillLocation();
584 } else {
585 // Either we have all non-empty NewVals, or we're permitted to ignore
586 // missing locals.
587 for (unsigned int I = 0; I < Vals.size(); ++I)
588 if (NewVals[I])
589 V.replaceVariableLocationOp(I, NewVals[I]);
590 }
591}
592
593Value *Mapper::mapBlockAddress(const BlockAddress &BA) {
594 Function *F = cast<Function>(mapValue(BA.getFunction()));
595
596 // F may not have materialized its initializer. In that case, create a
597 // dummy basic block for now, and replace it once we've materialized all
598 // the initializers.
599 BasicBlock *BB;
600 if (F->empty()) {
601 DelayedBBs.push_back(DelayedBasicBlock(BA));
602 BB = DelayedBBs.back().TempBB.get();
603 } else {
604 BB = cast_or_null<BasicBlock>(mapValue(BA.getBasicBlock()));
605 }
606
607 return getVM()[&BA] = BlockAddress::get(F, BB ? BB : BA.getBasicBlock());
608}
609
610Metadata *Mapper::mapToMetadata(const Metadata *Key, Metadata *Val) {
611 getVM().MD()[Key].reset(Val);
612 return Val;
613}
614
615Metadata *Mapper::mapToSelf(const Metadata *MD) {
616 return mapToMetadata(MD, const_cast<Metadata *>(MD));
617}
618
619std::optional<Metadata *> MDNodeMapper::tryToMapOperand(const Metadata *Op) {
620 if (!Op)
621 return nullptr;
622
623 if (std::optional<Metadata *> MappedOp = M.mapSimpleMetadata(Op)) {
624#ifndef NDEBUG
625 if (auto *CMD = dyn_cast<ConstantAsMetadata>(Op))
626 assert((!*MappedOp || M.getVM().count(CMD->getValue()) ||
627 M.getVM().getMappedMD(Op)) &&
628 "Expected Value to be memoized");
629 else
630 assert((isa<MDString>(Op) || M.getVM().getMappedMD(Op)) &&
631 "Expected result to be memoized");
632#endif
633 return *MappedOp;
634 }
635
636 const MDNode &N = *cast<MDNode>(Op);
637 if (N.isDistinct())
638 return mapDistinctNode(N);
639 return std::nullopt;
640}
641
642MDNode *MDNodeMapper::mapDistinctNode(const MDNode &N) {
643 assert(N.isDistinct() && "Expected a distinct node");
644 assert(!M.getVM().getMappedMD(&N) && "Expected an unmapped node");
645 Metadata *NewM = nullptr;
646
647 if (M.Flags & RF_ReuseAndMutateDistinctMDs) {
648 NewM = M.mapToSelf(&N);
649 } else {
650 NewM = MDNode::replaceWithDistinct(N.clone());
651 LLVM_DEBUG(dbgs() << "\nMap " << N << "\n"
652 << "To " << *NewM << "\n\n");
653 M.mapToMetadata(&N, NewM);
654 }
655 DistinctWorklist.push_back(cast<MDNode>(NewM));
656
657 return DistinctWorklist.back();
658}
659
661 Value *MappedV) {
662 if (CMD.getValue() == MappedV)
663 return const_cast<ConstantAsMetadata *>(&CMD);
664 return MappedV ? ConstantAsMetadata::getConstant(MappedV) : nullptr;
665}
666
667std::optional<Metadata *> MDNodeMapper::getMappedOp(const Metadata *Op) const {
668 if (!Op)
669 return nullptr;
670
671 if (std::optional<Metadata *> MappedOp = M.getVM().getMappedMD(Op))
672 return *MappedOp;
673
674 if (isa<MDString>(Op))
675 return const_cast<Metadata *>(Op);
676
677 if (auto *CMD = dyn_cast<ConstantAsMetadata>(Op))
678 return wrapConstantAsMetadata(*CMD, M.getVM().lookup(CMD->getValue()));
679
680 return std::nullopt;
681}
682
683Metadata &MDNodeMapper::UniquedGraph::getFwdReference(MDNode &Op) {
684 auto Where = Info.find(&Op);
685 assert(Where != Info.end() && "Expected a valid reference");
686
687 auto &OpD = Where->second;
688 if (!OpD.HasChanged)
689 return Op;
690
691 // Lazily construct a temporary node.
692 if (!OpD.Placeholder)
693 OpD.Placeholder = Op.clone();
694
695 return *OpD.Placeholder;
696}
697
698template <class OperandMapper>
699void MDNodeMapper::remapOperands(MDNode &N, OperandMapper mapOperand) {
700 assert(!N.isUniqued() && "Expected distinct or temporary nodes");
701 for (unsigned I = 0, E = N.getNumOperands(); I != E; ++I) {
702 Metadata *Old = N.getOperand(I);
703 Metadata *New = mapOperand(Old);
704 if (Old != New)
705 LLVM_DEBUG(dbgs() << "Replacing Op " << Old << " with " << New << " in "
706 << N << "\n");
707
708 if (Old != New)
709 N.replaceOperandWith(I, New);
710 }
711}
712
713namespace {
714
715/// An entry in the worklist for the post-order traversal.
716struct POTWorklistEntry {
717 MDNode *N; ///< Current node.
718 MDNode::op_iterator Op; ///< Current operand of \c N.
719
720 /// Keep a flag of whether operands have changed in the worklist to avoid
721 /// hitting the map in \a UniquedGraph.
722 bool HasChanged = false;
723
724 POTWorklistEntry(MDNode &N) : N(&N), Op(N.op_begin()) {}
725};
726
727} // end anonymous namespace
728
729bool MDNodeMapper::createPOT(UniquedGraph &G, const MDNode &FirstN) {
730 assert(G.Info.empty() && "Expected a fresh traversal");
731 assert(FirstN.isUniqued() && "Expected uniqued node in POT");
732
733 // Construct a post-order traversal of the uniqued subgraph under FirstN.
734 bool AnyChanges = false;
736 Worklist.push_back(POTWorklistEntry(const_cast<MDNode &>(FirstN)));
737 (void)G.Info[&FirstN];
738 while (!Worklist.empty()) {
739 // Start or continue the traversal through the this node's operands.
740 auto &WE = Worklist.back();
741 if (MDNode *N = visitOperands(G, WE.Op, WE.N->op_end(), WE.HasChanged)) {
742 // Push a new node to traverse first.
743 Worklist.push_back(POTWorklistEntry(*N));
744 continue;
745 }
746
747 // Push the node onto the POT.
748 assert(WE.N->isUniqued() && "Expected only uniqued nodes");
749 assert(WE.Op == WE.N->op_end() && "Expected to visit all operands");
750 auto &D = G.Info[WE.N];
751 AnyChanges |= D.HasChanged = WE.HasChanged;
752 D.ID = G.POT.size();
753 G.POT.push_back(WE.N);
754
755 // Pop the node off the worklist.
756 Worklist.pop_back();
757 }
758 return AnyChanges;
759}
760
761MDNode *MDNodeMapper::visitOperands(UniquedGraph &G, MDNode::op_iterator &I,
762 MDNode::op_iterator E, bool &HasChanged) {
763 while (I != E) {
764 Metadata *Op = *I++; // Increment even on early return.
765 if (std::optional<Metadata *> MappedOp = tryToMapOperand(Op)) {
766 // Check if the operand changes.
767 HasChanged |= Op != *MappedOp;
768 continue;
769 }
770
771 // A uniqued metadata node.
772 MDNode &OpN = *cast<MDNode>(Op);
773 assert(OpN.isUniqued() &&
774 "Only uniqued operands cannot be mapped immediately");
775 if (G.Info.try_emplace(&OpN).second)
776 return &OpN; // This is a new one. Return it.
777 }
778 return nullptr;
779}
780
781void MDNodeMapper::UniquedGraph::propagateChanges() {
782 bool AnyChanges;
783 do {
784 AnyChanges = false;
785 for (MDNode *N : POT) {
786 auto &D = Info[N];
787 if (D.HasChanged)
788 continue;
789
790 if (llvm::none_of(N->operands(), [&](const Metadata *Op) {
791 auto Where = Info.find(Op);
792 return Where != Info.end() && Where->second.HasChanged;
793 }))
794 continue;
795
796 AnyChanges = D.HasChanged = true;
797 }
798 } while (AnyChanges);
799}
800
801void MDNodeMapper::mapNodesInPOT(UniquedGraph &G) {
802 // Construct uniqued nodes, building forward references as necessary.
803 SmallVector<MDNode *, 16> CyclicNodes;
804 for (auto *N : G.POT) {
805 auto &D = G.Info[N];
806 if (!D.HasChanged) {
807 // The node hasn't changed.
808 M.mapToSelf(N);
809 continue;
810 }
811
812 // Remember whether this node had a placeholder.
813 bool HadPlaceholder(D.Placeholder);
814
815 // Clone the uniqued node and remap the operands.
816 TempMDNode ClonedN = D.Placeholder ? std::move(D.Placeholder) : N->clone();
817 remapOperands(*ClonedN, [this, &D, &G](Metadata *Old) {
818 if (std::optional<Metadata *> MappedOp = getMappedOp(Old))
819 return *MappedOp;
820 (void)D;
821 assert(G.Info[Old].ID > D.ID && "Expected a forward reference");
822 return &G.getFwdReference(*cast<MDNode>(Old));
823 });
824
825 auto *NewN = MDNode::replaceWithUniqued(std::move(ClonedN));
826 if (N && NewN && N != NewN) {
827 LLVM_DEBUG(dbgs() << "\nMap " << *N << "\n"
828 << "To " << *NewN << "\n\n");
829 }
830
831 M.mapToMetadata(N, NewN);
832
833 // Nodes that were referenced out of order in the POT are involved in a
834 // uniquing cycle.
835 if (HadPlaceholder)
836 CyclicNodes.push_back(NewN);
837 }
838
839 // Resolve cycles.
840 for (auto *N : CyclicNodes)
841 if (!N->isResolved())
842 N->resolveCycles();
843}
844
845Metadata *MDNodeMapper::map(const MDNode &N) {
846 assert(DistinctWorklist.empty() && "MDNodeMapper::map is not recursive");
847 assert(!(M.Flags & RF_NoModuleLevelChanges) &&
848 "MDNodeMapper::map assumes module-level changes");
849
850 // Require resolved nodes whenever metadata might be remapped.
851 assert(N.isResolved() && "Unexpected unresolved node");
852
853 Metadata *MappedN =
854 N.isUniqued() ? mapTopLevelUniquedNode(N) : mapDistinctNode(N);
855 while (!DistinctWorklist.empty())
856 remapOperands(*DistinctWorklist.pop_back_val(), [this](Metadata *Old) {
857 if (std::optional<Metadata *> MappedOp = tryToMapOperand(Old))
858 return *MappedOp;
859 return mapTopLevelUniquedNode(*cast<MDNode>(Old));
860 });
861 return MappedN;
862}
863
864Metadata *MDNodeMapper::mapTopLevelUniquedNode(const MDNode &FirstN) {
865 assert(FirstN.isUniqued() && "Expected uniqued node");
866
867 // Create a post-order traversal of uniqued nodes under FirstN.
868 UniquedGraph G;
869 if (!createPOT(G, FirstN)) {
870 // Return early if no nodes have changed.
871 for (const MDNode *N : G.POT)
872 M.mapToSelf(N);
873 return &const_cast<MDNode &>(FirstN);
874 }
875
876 // Update graph with all nodes that have changed.
877 G.propagateChanges();
878
879 // Map all the nodes in the graph.
880 mapNodesInPOT(G);
881
882 // Return the original node, remapped.
883 return *getMappedOp(&FirstN);
884}
885
886std::optional<Metadata *> Mapper::mapSimpleMetadata(const Metadata *MD) {
887 // If the value already exists in the map, use it.
888 if (std::optional<Metadata *> NewMD = getVM().getMappedMD(MD))
889 return *NewMD;
890
891 if (isa<MDString>(MD))
892 return const_cast<Metadata *>(MD);
893
894 // This is a module-level metadata. If nothing at the module level is
895 // changing, use an identity mapping.
896 if ((Flags & RF_NoModuleLevelChanges))
897 return const_cast<Metadata *>(MD);
898
899 if (auto *CMD = dyn_cast<ConstantAsMetadata>(MD)) {
900 // Don't memoize ConstantAsMetadata. Instead of lasting until the
901 // LLVMContext is destroyed, they can be deleted when the GlobalValue they
902 // reference is destructed. These aren't super common, so the extra
903 // indirection isn't that expensive.
904 return wrapConstantAsMetadata(*CMD, mapValue(CMD->getValue()));
905 }
906
907 // Map metadata matching IdentityMD predicate on first use. We need to add
908 // these nodes to the mapping as otherwise metadata nodes numbering gets
909 // messed up.
910 if (IdentityMD && (*IdentityMD)(MD))
911 return getVM().MD()[MD] = TrackingMDRef(const_cast<Metadata *>(MD));
912
913 assert(isa<MDNode>(MD) && "Expected a metadata node");
914
915 return std::nullopt;
916}
917
918Metadata *Mapper::mapMetadata(const Metadata *MD) {
919 assert(MD && "Expected valid metadata");
920 assert(!isa<LocalAsMetadata>(MD) && "Unexpected local metadata");
921
922 if (std::optional<Metadata *> NewMD = mapSimpleMetadata(MD))
923 return *NewMD;
924
925 return MDNodeMapper(*this).map(*cast<MDNode>(MD));
926}
927
928void Mapper::flush() {
929 // Flush out the worklist of global values.
930 while (!Worklist.empty()) {
931 WorklistEntry E = Worklist.pop_back_val();
932 CurrentMCID = E.MCID;
933 switch (E.Kind) {
934 case WorklistEntry::MapGlobalInit:
935 E.Data.GVInit.GV->setInitializer(mapConstant(E.Data.GVInit.Init));
936 remapGlobalObjectMetadata(*E.Data.GVInit.GV);
937 break;
938 case WorklistEntry::MapAppendingVar: {
939 unsigned PrefixSize = AppendingInits.size() - E.AppendingGVNumNewMembers;
940 // mapAppendingVariable call can change AppendingInits if initalizer for
941 // the variable depends on another appending global, because of that inits
942 // need to be extracted and updated before the call.
944 drop_begin(AppendingInits, PrefixSize));
945 AppendingInits.resize(PrefixSize);
946 mapAppendingVariable(*E.Data.AppendingGV.GV,
947 E.Data.AppendingGV.InitPrefix,
948 E.AppendingGVIsOldCtorDtor, ArrayRef(NewInits));
949 break;
950 }
951 case WorklistEntry::MapAliasOrIFunc: {
952 GlobalValue *GV = E.Data.AliasOrIFunc.GV;
953 Constant *Target = mapConstant(E.Data.AliasOrIFunc.Target);
954 if (auto *GA = dyn_cast<GlobalAlias>(GV))
955 GA->setAliasee(Target);
956 else if (auto *GI = dyn_cast<GlobalIFunc>(GV))
957 GI->setResolver(Target);
958 else
959 llvm_unreachable("Not alias or ifunc");
960 break;
961 }
962 case WorklistEntry::RemapFunction:
963 remapFunction(*E.Data.RemapF);
964 break;
965 }
966 }
967 CurrentMCID = 0;
968
969 // Finish logic for block addresses now that all global values have been
970 // handled.
971 while (!DelayedBBs.empty()) {
972 DelayedBasicBlock DBB = DelayedBBs.pop_back_val();
973 BasicBlock *BB = cast_or_null<BasicBlock>(mapValue(DBB.OldBB));
974 DBB.TempBB->replaceAllUsesWith(BB ? BB : DBB.OldBB);
975 }
976}
977
978void Mapper::remapInstruction(Instruction *I) {
979 // Remap operands.
980 for (Use &Op : I->operands()) {
981 Value *V = mapValue(Op);
982 // If we aren't ignoring missing entries, assert that something happened.
983 if (V)
984 Op = V;
985 else
986 assert((Flags & RF_IgnoreMissingLocals) &&
987 "Referenced value not in value map!");
988 }
989
990 // Drop callee_type metadata from calls that were remapped
991 // into a direct call from an indirect one.
992 if (auto *CB = dyn_cast<CallBase>(I)) {
993 if (CB->getMetadata(LLVMContext::MD_callee_type) && !CB->isIndirectCall())
994 CB->setMetadata(LLVMContext::MD_callee_type, nullptr);
995 }
996
997 // Remap phi nodes' incoming blocks.
998 if (PHINode *PN = dyn_cast<PHINode>(I)) {
999 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1000 Value *V = mapValue(PN->getIncomingBlock(i));
1001 // If we aren't ignoring missing entries, assert that something happened.
1002 if (V)
1003 PN->setIncomingBlock(i, cast<BasicBlock>(V));
1004 else
1005 assert((Flags & RF_IgnoreMissingLocals) &&
1006 "Referenced block not in value map!");
1007 }
1008 }
1009
1010 // Remap attached metadata.
1012 I->getAllMetadata(MDs);
1013 for (const auto &MI : MDs) {
1014 MDNode *Old = MI.second;
1015 MDNode *New = cast_or_null<MDNode>(mapMetadata(Old));
1016 if (New != Old)
1017 I->setMetadata(MI.first, New);
1018 }
1019
1020 // Remap source location atom instance.
1021 if (!(Flags & RF_DoNotRemapAtoms))
1022 RemapSourceAtom(I, getVM());
1023
1024 if (!TypeMapper)
1025 return;
1026
1027 // If the instruction's type is being remapped, do so now.
1028 if (auto *CB = dyn_cast<CallBase>(I)) {
1030 FunctionType *FTy = CB->getFunctionType();
1031 Tys.reserve(FTy->getNumParams());
1032 for (Type *Ty : FTy->params())
1033 Tys.push_back(TypeMapper->remapType(Ty));
1034 CB->mutateFunctionType(FunctionType::get(
1035 TypeMapper->remapType(I->getType()), Tys, FTy->isVarArg()));
1036
1037 LLVMContext &C = CB->getContext();
1038 AttributeList Attrs = CB->getAttributes();
1039 for (unsigned i = 0; i < Attrs.getNumAttrSets(); ++i) {
1040 for (int AttrIdx = Attribute::FirstTypeAttr;
1041 AttrIdx <= Attribute::LastTypeAttr; AttrIdx++) {
1042 Attribute::AttrKind TypedAttr = (Attribute::AttrKind)AttrIdx;
1043 if (Type *Ty =
1044 Attrs.getAttributeAtIndex(i, TypedAttr).getValueAsType()) {
1045 Attrs = Attrs.replaceAttributeTypeAtIndex(C, i, TypedAttr,
1046 TypeMapper->remapType(Ty));
1047 break;
1048 }
1049 }
1050 }
1051 CB->setAttributes(Attrs);
1052 return;
1053 }
1054 if (auto *AI = dyn_cast<AllocaInst>(I))
1055 AI->setAllocatedType(TypeMapper->remapType(AI->getAllocatedType()));
1056 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
1057 GEP->setSourceElementType(
1058 TypeMapper->remapType(GEP->getSourceElementType()));
1059 GEP->setResultElementType(
1060 TypeMapper->remapType(GEP->getResultElementType()));
1061 }
1062 I->mutateType(TypeMapper->remapType(I->getType()));
1063}
1064
1065void Mapper::remapGlobalObjectMetadata(GlobalObject &GO) {
1067 GO.getAllMetadata(MDs);
1068 GO.clearMetadata();
1069 for (const auto &I : MDs)
1070 GO.addMetadata(I.first, *cast<MDNode>(mapMetadata(I.second)));
1071}
1072
1073void Mapper::remapFunction(Function &F) {
1074 // Remap the operands.
1075 for (Use &Op : F.operands())
1076 if (Op)
1077 Op = mapValue(Op);
1078
1079 // Remap the metadata attachments.
1080 remapGlobalObjectMetadata(F);
1081
1082 // Remap the argument types.
1083 if (TypeMapper)
1084 for (Argument &A : F.args())
1085 A.mutateType(TypeMapper->remapType(A.getType()));
1086
1087 // Remap the instructions.
1088 for (BasicBlock &BB : F) {
1089 for (Instruction &I : BB) {
1090 remapInstruction(&I);
1091 for (DbgRecord &DR : I.getDbgRecordRange())
1092 remapDbgRecord(DR);
1093 }
1094 }
1095}
1096
1097void Mapper::mapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
1098 bool IsOldCtorDtor,
1099 ArrayRef<Constant *> NewMembers) {
1101 if (InitPrefix) {
1102 unsigned NumElements =
1103 cast<ArrayType>(InitPrefix->getType())->getNumElements();
1104 for (unsigned I = 0; I != NumElements; ++I)
1105 Elements.push_back(InitPrefix->getAggregateElement(I));
1106 }
1107
1108 PointerType *VoidPtrTy;
1109 Type *EltTy;
1110 if (IsOldCtorDtor) {
1111 // FIXME: This upgrade is done during linking to support the C API. See
1112 // also IRLinker::linkAppendingVarProto() in IRMover.cpp.
1113 VoidPtrTy = PointerType::getUnqual(GV.getContext());
1114 auto &ST = *cast<StructType>(NewMembers.front()->getType());
1115 Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
1116 EltTy = StructType::get(GV.getContext(), Tys, false);
1117 }
1118
1119 for (auto *V : NewMembers) {
1120 Constant *NewV;
1121 if (IsOldCtorDtor) {
1122 auto *S = cast<ConstantStruct>(V);
1123 auto *E1 = cast<Constant>(mapValue(S->getOperand(0)));
1124 auto *E2 = cast<Constant>(mapValue(S->getOperand(1)));
1125 Constant *Null = Constant::getNullValue(VoidPtrTy);
1126 NewV = ConstantStruct::get(cast<StructType>(EltTy), E1, E2, Null);
1127 } else {
1128 NewV = cast_or_null<Constant>(mapValue(V));
1129 }
1130 Elements.push_back(NewV);
1131 }
1132
1133 GV.setInitializer(
1134 ConstantArray::get(cast<ArrayType>(GV.getValueType()), Elements));
1135}
1136
1137void Mapper::scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init,
1138 unsigned MCID) {
1139 assert(AlreadyScheduled.insert(&GV).second && "Should not reschedule");
1140 assert(MCID < MCs.size() && "Invalid mapping context");
1141
1142 WorklistEntry WE;
1143 WE.Kind = WorklistEntry::MapGlobalInit;
1144 WE.MCID = MCID;
1145 WE.Data.GVInit.GV = &GV;
1146 WE.Data.GVInit.Init = &Init;
1147 Worklist.push_back(WE);
1148}
1149
1150void Mapper::scheduleMapAppendingVariable(GlobalVariable &GV,
1151 Constant *InitPrefix,
1152 bool IsOldCtorDtor,
1153 ArrayRef<Constant *> NewMembers,
1154 unsigned MCID) {
1155 assert(AlreadyScheduled.insert(&GV).second && "Should not reschedule");
1156 assert(MCID < MCs.size() && "Invalid mapping context");
1157
1158 WorklistEntry WE;
1159 WE.Kind = WorklistEntry::MapAppendingVar;
1160 WE.MCID = MCID;
1161 WE.Data.AppendingGV.GV = &GV;
1162 WE.Data.AppendingGV.InitPrefix = InitPrefix;
1163 WE.AppendingGVIsOldCtorDtor = IsOldCtorDtor;
1164 WE.AppendingGVNumNewMembers = NewMembers.size();
1165 Worklist.push_back(WE);
1166 AppendingInits.append(NewMembers.begin(), NewMembers.end());
1167}
1168
1169void Mapper::scheduleMapAliasOrIFunc(GlobalValue &GV, Constant &Target,
1170 unsigned MCID) {
1171 assert(AlreadyScheduled.insert(&GV).second && "Should not reschedule");
1172 assert((isa<GlobalAlias>(GV) || isa<GlobalIFunc>(GV)) &&
1173 "Should be alias or ifunc");
1174 assert(MCID < MCs.size() && "Invalid mapping context");
1175
1176 WorklistEntry WE;
1177 WE.Kind = WorklistEntry::MapAliasOrIFunc;
1178 WE.MCID = MCID;
1179 WE.Data.AliasOrIFunc.GV = &GV;
1180 WE.Data.AliasOrIFunc.Target = &Target;
1181 Worklist.push_back(WE);
1182}
1183
1184void Mapper::scheduleRemapFunction(Function &F, unsigned MCID) {
1185 assert(AlreadyScheduled.insert(&F).second && "Should not reschedule");
1186 assert(MCID < MCs.size() && "Invalid mapping context");
1187
1188 WorklistEntry WE;
1189 WE.Kind = WorklistEntry::RemapFunction;
1190 WE.MCID = MCID;
1191 WE.Data.RemapF = &F;
1192 Worklist.push_back(WE);
1193}
1194
1195void Mapper::addFlags(RemapFlags Flags) {
1196 assert(!hasWorkToDo() && "Expected to have flushed the worklist");
1197 this->Flags = this->Flags | Flags;
1198}
1199
1200static Mapper *getAsMapper(void *pImpl) {
1201 return reinterpret_cast<Mapper *>(pImpl);
1202}
1203
1204namespace {
1205
1206class FlushingMapper {
1207 Mapper &M;
1208
1209public:
1210 explicit FlushingMapper(void *pImpl) : M(*getAsMapper(pImpl)) {
1211 assert(!M.hasWorkToDo() && "Expected to be flushed");
1212 }
1213
1214 ~FlushingMapper() { M.flush(); }
1215
1216 Mapper *operator->() const { return &M; }
1217};
1218
1219} // end anonymous namespace
1220
1222 ValueMapTypeRemapper *TypeMapper,
1223 ValueMaterializer *Materializer,
1224 const MetadataPredicate *IdentityMD)
1225 : pImpl(new Mapper(VM, Flags, TypeMapper, Materializer, IdentityMD)) {}
1226
1228
1229unsigned
1231 ValueMaterializer *Materializer) {
1232 return getAsMapper(pImpl)->registerAlternateMappingContext(VM, Materializer);
1233}
1234
1236 FlushingMapper(pImpl)->addFlags(Flags);
1237}
1238
1240 return FlushingMapper(pImpl)->mapValue(&V);
1241}
1242
1244 return cast_or_null<Constant>(mapValue(C));
1245}
1246
1248 return FlushingMapper(pImpl)->mapMetadata(&MD);
1249}
1250
1252 return cast_or_null<MDNode>(mapMetadata(N));
1253}
1254
1256 FlushingMapper(pImpl)->remapInstruction(&I);
1257}
1258
1260 FlushingMapper(pImpl)->remapDbgRecord(DR);
1261}
1262
1265 for (DbgRecord &DR : Range) {
1266 remapDbgRecord(M, DR);
1267 }
1268}
1269
1271 FlushingMapper(pImpl)->remapFunction(F);
1272}
1273
1275 FlushingMapper(pImpl)->remapGlobalObjectMetadata(GO);
1276}
1277
1279 Constant &Init,
1280 unsigned MCID) {
1281 getAsMapper(pImpl)->scheduleMapGlobalInitializer(GV, Init, MCID);
1282}
1283
1285 Constant *InitPrefix,
1286 bool IsOldCtorDtor,
1287 ArrayRef<Constant *> NewMembers,
1288 unsigned MCID) {
1289 getAsMapper(pImpl)->scheduleMapAppendingVariable(
1290 GV, InitPrefix, IsOldCtorDtor, NewMembers, MCID);
1291}
1292
1294 unsigned MCID) {
1295 getAsMapper(pImpl)->scheduleMapAliasOrIFunc(GA, Aliasee, MCID);
1296}
1297
1299 unsigned MCID) {
1300 getAsMapper(pImpl)->scheduleMapAliasOrIFunc(GI, Resolver, MCID);
1301}
1302
1304 getAsMapper(pImpl)->scheduleRemapFunction(F, MCID);
1305}
1306
1308 const DebugLoc &DL = I->getDebugLoc();
1309 if (!DL)
1310 return;
1311
1312 auto AtomGroup = DL->getAtomGroup();
1313 if (!AtomGroup)
1314 return;
1315
1316 auto R = VM.AtomMap.find({DL->getInlinedAt(), AtomGroup});
1317 if (R == VM.AtomMap.end())
1318 return;
1319 AtomGroup = R->second;
1320
1321 // Remap the atom group and copy all other fields.
1323 I->getContext(), DL.getLine(), DL.getCol(), DL.getScope(),
1324 DL.getInlinedAt(), DL.isImplicitCode(), AtomGroup, DL->getAtomRank());
1325 I->setDebugLoc(New);
1326}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static unsigned getMappedOp(unsigned PseudoOp)
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
Hexagon Common GEP
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
#define G(x, y, z)
Definition: MD5.cpp:56
This file contains the declarations for metadata subclasses.
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
LoopAnalysisManager LAM
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition: Debug.h:119
static void remapOperands(VPBlockBase *Entry, VPBlockBase *NewEntry, DenseMap< VPValue *, VPValue * > &Old2NewVPValues)
Definition: VPlan.cpp:1141
static Mapper * getAsMapper(void *pImpl)
static ConstantAsMetadata * wrapConstantAsMetadata(const ConstantAsMetadata &CMD, Value *MappedV)
This class represents an incoming formal argument to a Function.
Definition: Argument.h:32
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
const T & front() const
front - Get the first element.
Definition: ArrayRef.h:150
iterator end() const
Definition: ArrayRef.h:136
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:147
iterator begin() const
Definition: ArrayRef.h:135
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition: Attributes.h:88
LLVM Basic Block Representation.
Definition: BasicBlock.h:62
The address of a basic block.
Definition: Constants.h:899
Function * getFunction() const
Definition: Constants.h:935
BasicBlock * getBasicBlock() const
Definition: Constants.h:934
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
Definition: Constants.cpp:1911
static LLVM_ABI ConstantAggregateZero * get(Type *Ty)
Definition: Constants.cpp:1677
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1314
Constant * getValue() const
Definition: Metadata.h:543
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:1120
static LLVM_ABI Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2328
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1833
static LLVM_ABI ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc)
Return a pointer signed with the specified parameters.
Definition: Constants.cpp:2063
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1380
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
Definition: Constants.cpp:1423
This is an important base class in LLVM.
Definition: Constant.h:43
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:373
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
Definition: Constants.cpp:435
static LLVM_ABI DIArgList * get(LLVMContext &Context, ArrayRef< ValueAsMetadata * > Args)
Debug location.
static LLVM_ABI DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
Definition: Constants.cpp:1961
This class represents an Operation in the Expression.
Records a position in IR for a source label (DILabel).
Base class for non-instruction debug metadata records that have positions within IR.
DebugLoc getDebugLoc() const
void setDebugLoc(DebugLoc Loc)
Record of a variable value-assignment, aka a non instruction representation of the dbg....
A debug info location.
Definition: DebugLoc.h:124
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:177
iterator end()
Definition: DenseMap.h:87
Implements a dense probed hash-table based set.
Definition: DenseSet.h:263
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
LLVM_ABI void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * > > &MDs) const
Appends all metadata attached to this value to MDs, sorting by KindID.
Definition: Metadata.cpp:1561
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
Definition: Metadata.cpp:1605
LLVM_ABI void clearMetadata()
Erase all metadata attached to this Value.
Definition: Metadata.cpp:1643
Type * getValueType() const
Definition: GlobalValue.h:298
LLVM_ABI void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition: Globals.cpp:511
static LLVM_ABI InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
Definition: InlineAsm.cpp:43
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
Metadata node.
Definition: Metadata.h:1077
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1565
static std::enable_if_t< std::is_base_of< MDNode, T >::value, T * > replaceWithDistinct(std::unique_ptr< T, TempMDNodeDeleter > N)
Replace a temporary node with a distinct one.
Definition: Metadata.h:1326
bool isUniqued() const
Definition: Metadata.h:1259
static std::enable_if_t< std::is_base_of< MDNode, T >::value, T * > replaceWithUniqued(std::unique_ptr< T, TempMDNodeDeleter > N)
Replace a temporary node with a uniqued one.
Definition: Metadata.h:1316
Tracking metadata reference owned by Metadata.
Definition: Metadata.h:899
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1522
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition: Metadata.cpp:103
Root of the metadata hierarchy.
Definition: Metadata.h:63
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:67
static LLVM_ABI NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
Definition: Constants.cpp:2019
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
Definition: DerivedTypes.h:720
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1885
Interface for looking up the initializer for a variable name, used by Init::resolveReferences.
Definition: Record.h:2196
bool empty() const
Definition: SmallVector.h:82
size_t size() const
Definition: SmallVector.h:79
void reserve(size_type N)
Definition: SmallVector.h:664
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:684
void resize(size_type N)
Definition: SmallVector.h:639
void push_back(const T &Elt)
Definition: SmallVector.h:414
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition: Type.cpp:414
Target - Wrapper for Target specific information.
Tracking metadata reference.
Definition: TrackingMDRef.h:25
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Definition: Constants.cpp:1866
A Use represents the edge between a Value definition and its users.
Definition: Use.h:35
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition: Metadata.cpp:502
static ConstantAsMetadata * getConstant(Value *C)
Definition: Metadata.h:479
This is a class that can be implemented by clients to remap types when cloning constants and instruct...
Definition: ValueMapper.h:45
virtual Type * remapType(Type *SrcTy)=0
The client should implement this method if they want to remap types while mapping values.
DMAtomT AtomMap
Map {(InlinedAt, old atom number) -> new atom number}.
Definition: ValueMap.h:123
LLVM_ABI void remapDbgRecord(Module *M, DbgRecord &V)
LLVM_ABI ~ValueMapper()
LLVM_ABI void remapDbgRecordRange(Module *M, iterator_range< DbgRecordIterator > Range)
LLVM_ABI MDNode * mapMDNode(const MDNode &N)
LLVM_ABI Metadata * mapMetadata(const Metadata &MD)
LLVM_ABI void remapInstruction(Instruction &I)
LLVM_ABI void scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init, unsigned MappingContextID=0)
LLVM_ABI void scheduleRemapFunction(Function &F, unsigned MappingContextID=0)
LLVM_ABI ValueMapper(ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
LLVM_ABI void scheduleMapGlobalIFunc(GlobalIFunc &GI, Constant &Resolver, unsigned MappingContextID=0)
LLVM_ABI unsigned registerAlternateMappingContext(ValueToValueMapTy &VM, ValueMaterializer *Materializer=nullptr)
Register an alternate mapping context.
LLVM_ABI void remapFunction(Function &F)
LLVM_ABI Constant * mapConstant(const Constant &C)
LLVM_ABI void scheduleMapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix, bool IsOldCtorDtor, ArrayRef< Constant * > NewMembers, unsigned MappingContextID=0)
LLVM_ABI void scheduleMapGlobalAlias(GlobalAlias &GA, Constant &Aliasee, unsigned MappingContextID=0)
LLVM_ABI void remapGlobalObjectMetadata(GlobalObject &GO)
LLVM_ABI Value * mapValue(const Value &V)
LLVM_ABI void addFlags(RemapFlags Flags)
Add to the current RemapFlags.
This is a class that can be implemented by clients to materialize Values on demand.
Definition: ValueMapper.h:58
LLVM Value Representation.
Definition: Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:256
LLVM_ABI LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1098
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:194
A range adaptor for a pair of iterators.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
Key
PAL metadata keys.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
@ CE
Windows NT (Windows on ARM)
NodeAddr< FuncNode * > Func
Definition: RDFGraph.h:393
LLVM_ABI const_iterator end(StringRef path LLVM_LIFETIME_BOUND)
Get end iterator over path.
Definition: Path.cpp:235
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition: STLExtras.h:338
RemapFlags
These are flags that the value mapping APIs allow.
Definition: ValueMapper.h:74
@ RF_IgnoreMissingLocals
If this flag is set, the remapper ignores missing function-local entries (Argument,...
Definition: ValueMapper.h:98
@ RF_NullMapMissingGlobalValues
Any global values not in value map are mapped to null instead of mapping to self.
Definition: ValueMapper.h:108
@ RF_NoModuleLevelChanges
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
Definition: ValueMapper.h:80
@ RF_DoNotRemapAtoms
Do not remap source location atoms.
Definition: ValueMapper.h:115
@ RF_ReuseAndMutateDistinctMDs
Instruct the remapper to reuse and mutate distinct metadata (remapping them in place) instead of clon...
Definition: ValueMapper.h:104
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:207
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1758
std::function< bool(const Metadata *)> MetadataPredicate
Definition: ValueMapper.h:41
DWARFExpression::Operation Op
void RemapFunction(Function &F, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Remap the operands, metadata, arguments, and instructions of a function.
Definition: ValueMapper.h:334
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition: STLExtras.h:1916
LLVM_ABI void RemapSourceAtom(Instruction *I, ValueToValueMapTy &VM)
Remap source location atom.
#define N
#define NC
Definition: regutils.h:42