xref: /llvm-project/llvm/lib/Transforms/Utils/Local.cpp (revision 3c9022c965b85951f30af140da591f819acef8a0)
1 //===- Local.cpp - Functions to perform local transformations -------------===//
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 family of functions perform various local transformations to the
10 // program.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/Utils/Local.h"
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/DenseMapInfo.h"
18 #include "llvm/ADT/DenseSet.h"
19 #include "llvm/ADT/Hashing.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Analysis/AssumeBundleQueries.h"
26 #include "llvm/Analysis/ConstantFolding.h"
27 #include "llvm/Analysis/DomTreeUpdater.h"
28 #include "llvm/Analysis/InstructionSimplify.h"
29 #include "llvm/Analysis/MemoryBuiltins.h"
30 #include "llvm/Analysis/MemorySSAUpdater.h"
31 #include "llvm/Analysis/TargetLibraryInfo.h"
32 #include "llvm/Analysis/ValueTracking.h"
33 #include "llvm/Analysis/VectorUtils.h"
34 #include "llvm/BinaryFormat/Dwarf.h"
35 #include "llvm/IR/Argument.h"
36 #include "llvm/IR/Attributes.h"
37 #include "llvm/IR/BasicBlock.h"
38 #include "llvm/IR/CFG.h"
39 #include "llvm/IR/Constant.h"
40 #include "llvm/IR/ConstantRange.h"
41 #include "llvm/IR/Constants.h"
42 #include "llvm/IR/DIBuilder.h"
43 #include "llvm/IR/DataLayout.h"
44 #include "llvm/IR/DebugInfo.h"
45 #include "llvm/IR/DebugInfoMetadata.h"
46 #include "llvm/IR/DebugLoc.h"
47 #include "llvm/IR/DerivedTypes.h"
48 #include "llvm/IR/Dominators.h"
49 #include "llvm/IR/EHPersonalities.h"
50 #include "llvm/IR/Function.h"
51 #include "llvm/IR/GetElementPtrTypeIterator.h"
52 #include "llvm/IR/GlobalObject.h"
53 #include "llvm/IR/IRBuilder.h"
54 #include "llvm/IR/InstrTypes.h"
55 #include "llvm/IR/Instruction.h"
56 #include "llvm/IR/Instructions.h"
57 #include "llvm/IR/IntrinsicInst.h"
58 #include "llvm/IR/Intrinsics.h"
59 #include "llvm/IR/IntrinsicsWebAssembly.h"
60 #include "llvm/IR/LLVMContext.h"
61 #include "llvm/IR/MDBuilder.h"
62 #include "llvm/IR/MemoryModelRelaxationAnnotations.h"
63 #include "llvm/IR/Metadata.h"
64 #include "llvm/IR/Module.h"
65 #include "llvm/IR/PatternMatch.h"
66 #include "llvm/IR/ProfDataUtils.h"
67 #include "llvm/IR/Type.h"
68 #include "llvm/IR/Use.h"
69 #include "llvm/IR/User.h"
70 #include "llvm/IR/Value.h"
71 #include "llvm/IR/ValueHandle.h"
72 #include "llvm/Support/Casting.h"
73 #include "llvm/Support/CommandLine.h"
74 #include "llvm/Support/Debug.h"
75 #include "llvm/Support/ErrorHandling.h"
76 #include "llvm/Support/KnownBits.h"
77 #include "llvm/Support/raw_ostream.h"
78 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
79 #include "llvm/Transforms/Utils/ValueMapper.h"
80 #include <algorithm>
81 #include <cassert>
82 #include <cstdint>
83 #include <iterator>
84 #include <map>
85 #include <optional>
86 #include <utility>
87 
88 using namespace llvm;
89 using namespace llvm::PatternMatch;
90 
91 extern cl::opt<bool> UseNewDbgInfoFormat;
92 
93 #define DEBUG_TYPE "local"
94 
95 STATISTIC(NumRemoved, "Number of unreachable basic blocks removed");
96 STATISTIC(NumPHICSEs, "Number of PHI's that got CSE'd");
97 
98 static cl::opt<bool> PHICSEDebugHash(
99     "phicse-debug-hash",
100 #ifdef EXPENSIVE_CHECKS
101     cl::init(true),
102 #else
103     cl::init(false),
104 #endif
105     cl::Hidden,
106     cl::desc("Perform extra assertion checking to verify that PHINodes's hash "
107              "function is well-behaved w.r.t. its isEqual predicate"));
108 
109 static cl::opt<unsigned> PHICSENumPHISmallSize(
110     "phicse-num-phi-smallsize", cl::init(32), cl::Hidden,
111     cl::desc(
112         "When the basic block contains not more than this number of PHI nodes, "
113         "perform a (faster!) exhaustive search instead of set-driven one."));
114 
115 // Max recursion depth for collectBitParts used when detecting bswap and
116 // bitreverse idioms.
117 static const unsigned BitPartRecursionMaxDepth = 48;
118 
119 //===----------------------------------------------------------------------===//
120 //  Local constant propagation.
121 //
122 
123 /// ConstantFoldTerminator - If a terminator instruction is predicated on a
124 /// constant value, convert it into an unconditional branch to the constant
125 /// destination.  This is a nontrivial operation because the successors of this
126 /// basic block must have their PHI nodes updated.
127 /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
128 /// conditions and indirectbr addresses this might make dead if
129 /// DeleteDeadConditions is true.
130 bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
131                                   const TargetLibraryInfo *TLI,
132                                   DomTreeUpdater *DTU) {
133   Instruction *T = BB->getTerminator();
134   IRBuilder<> Builder(T);
135 
136   // Branch - See if we are conditional jumping on constant
137   if (auto *BI = dyn_cast<BranchInst>(T)) {
138     if (BI->isUnconditional()) return false;  // Can't optimize uncond branch
139 
140     BasicBlock *Dest1 = BI->getSuccessor(0);
141     BasicBlock *Dest2 = BI->getSuccessor(1);
142 
143     if (Dest2 == Dest1) {       // Conditional branch to same location?
144       // This branch matches something like this:
145       //     br bool %cond, label %Dest, label %Dest
146       // and changes it into:  br label %Dest
147 
148       // Let the basic block know that we are letting go of one copy of it.
149       assert(BI->getParent() && "Terminator not inserted in block!");
150       Dest1->removePredecessor(BI->getParent());
151 
152       // Replace the conditional branch with an unconditional one.
153       BranchInst *NewBI = Builder.CreateBr(Dest1);
154 
155       // Transfer the metadata to the new branch instruction.
156       NewBI->copyMetadata(*BI, {LLVMContext::MD_loop, LLVMContext::MD_dbg,
157                                 LLVMContext::MD_annotation});
158 
159       Value *Cond = BI->getCondition();
160       BI->eraseFromParent();
161       if (DeleteDeadConditions)
162         RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
163       return true;
164     }
165 
166     if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
167       // Are we branching on constant?
168       // YES.  Change to unconditional branch...
169       BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
170       BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
171 
172       // Let the basic block know that we are letting go of it.  Based on this,
173       // it will adjust it's PHI nodes.
174       OldDest->removePredecessor(BB);
175 
176       // Replace the conditional branch with an unconditional one.
177       BranchInst *NewBI = Builder.CreateBr(Destination);
178 
179       // Transfer the metadata to the new branch instruction.
180       NewBI->copyMetadata(*BI, {LLVMContext::MD_loop, LLVMContext::MD_dbg,
181                                 LLVMContext::MD_annotation});
182 
183       BI->eraseFromParent();
184       if (DTU)
185         DTU->applyUpdates({{DominatorTree::Delete, BB, OldDest}});
186       return true;
187     }
188 
189     return false;
190   }
191 
192   if (auto *SI = dyn_cast<SwitchInst>(T)) {
193     // If we are switching on a constant, we can convert the switch to an
194     // unconditional branch.
195     auto *CI = dyn_cast<ConstantInt>(SI->getCondition());
196     BasicBlock *DefaultDest = SI->getDefaultDest();
197     BasicBlock *TheOnlyDest = DefaultDest;
198 
199     // If the default is unreachable, ignore it when searching for TheOnlyDest.
200     if (isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()) &&
201         SI->getNumCases() > 0) {
202       TheOnlyDest = SI->case_begin()->getCaseSuccessor();
203     }
204 
205     bool Changed = false;
206 
207     // Figure out which case it goes to.
208     for (auto It = SI->case_begin(), End = SI->case_end(); It != End;) {
209       // Found case matching a constant operand?
210       if (It->getCaseValue() == CI) {
211         TheOnlyDest = It->getCaseSuccessor();
212         break;
213       }
214 
215       // Check to see if this branch is going to the same place as the default
216       // dest.  If so, eliminate it as an explicit compare.
217       if (It->getCaseSuccessor() == DefaultDest) {
218         MDNode *MD = getValidBranchWeightMDNode(*SI);
219         unsigned NCases = SI->getNumCases();
220         // Fold the case metadata into the default if there will be any branches
221         // left, unless the metadata doesn't match the switch.
222         if (NCases > 1 && MD) {
223           // Collect branch weights into a vector.
224           SmallVector<uint32_t, 8> Weights;
225           extractBranchWeights(MD, Weights);
226 
227           // Merge weight of this case to the default weight.
228           unsigned Idx = It->getCaseIndex();
229           // TODO: Add overflow check.
230           Weights[0] += Weights[Idx + 1];
231           // Remove weight for this case.
232           std::swap(Weights[Idx + 1], Weights.back());
233           Weights.pop_back();
234           setBranchWeights(*SI, Weights, hasBranchWeightOrigin(MD));
235         }
236         // Remove this entry.
237         BasicBlock *ParentBB = SI->getParent();
238         DefaultDest->removePredecessor(ParentBB);
239         It = SI->removeCase(It);
240         End = SI->case_end();
241 
242         // Removing this case may have made the condition constant. In that
243         // case, update CI and restart iteration through the cases.
244         if (auto *NewCI = dyn_cast<ConstantInt>(SI->getCondition())) {
245           CI = NewCI;
246           It = SI->case_begin();
247         }
248 
249         Changed = true;
250         continue;
251       }
252 
253       // Otherwise, check to see if the switch only branches to one destination.
254       // We do this by reseting "TheOnlyDest" to null when we find two non-equal
255       // destinations.
256       if (It->getCaseSuccessor() != TheOnlyDest)
257         TheOnlyDest = nullptr;
258 
259       // Increment this iterator as we haven't removed the case.
260       ++It;
261     }
262 
263     if (CI && !TheOnlyDest) {
264       // Branching on a constant, but not any of the cases, go to the default
265       // successor.
266       TheOnlyDest = SI->getDefaultDest();
267     }
268 
269     // If we found a single destination that we can fold the switch into, do so
270     // now.
271     if (TheOnlyDest) {
272       // Insert the new branch.
273       Builder.CreateBr(TheOnlyDest);
274       BasicBlock *BB = SI->getParent();
275 
276       SmallSet<BasicBlock *, 8> RemovedSuccessors;
277 
278       // Remove entries from PHI nodes which we no longer branch to...
279       BasicBlock *SuccToKeep = TheOnlyDest;
280       for (BasicBlock *Succ : successors(SI)) {
281         if (DTU && Succ != TheOnlyDest)
282           RemovedSuccessors.insert(Succ);
283         // Found case matching a constant operand?
284         if (Succ == SuccToKeep) {
285           SuccToKeep = nullptr; // Don't modify the first branch to TheOnlyDest
286         } else {
287           Succ->removePredecessor(BB);
288         }
289       }
290 
291       // Delete the old switch.
292       Value *Cond = SI->getCondition();
293       SI->eraseFromParent();
294       if (DeleteDeadConditions)
295         RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
296       if (DTU) {
297         std::vector<DominatorTree::UpdateType> Updates;
298         Updates.reserve(RemovedSuccessors.size());
299         for (auto *RemovedSuccessor : RemovedSuccessors)
300           Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});
301         DTU->applyUpdates(Updates);
302       }
303       return true;
304     }
305 
306     if (SI->getNumCases() == 1) {
307       // Otherwise, we can fold this switch into a conditional branch
308       // instruction if it has only one non-default destination.
309       auto FirstCase = *SI->case_begin();
310       Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
311           FirstCase.getCaseValue(), "cond");
312 
313       // Insert the new branch.
314       BranchInst *NewBr = Builder.CreateCondBr(Cond,
315                                                FirstCase.getCaseSuccessor(),
316                                                SI->getDefaultDest());
317       SmallVector<uint32_t> Weights;
318       if (extractBranchWeights(*SI, Weights) && Weights.size() == 2) {
319         uint32_t DefWeight = Weights[0];
320         uint32_t CaseWeight = Weights[1];
321         // The TrueWeight should be the weight for the single case of SI.
322         NewBr->setMetadata(LLVMContext::MD_prof,
323                            MDBuilder(BB->getContext())
324                                .createBranchWeights(CaseWeight, DefWeight));
325       }
326 
327       // Update make.implicit metadata to the newly-created conditional branch.
328       MDNode *MakeImplicitMD = SI->getMetadata(LLVMContext::MD_make_implicit);
329       if (MakeImplicitMD)
330         NewBr->setMetadata(LLVMContext::MD_make_implicit, MakeImplicitMD);
331 
332       // Delete the old switch.
333       SI->eraseFromParent();
334       return true;
335     }
336     return Changed;
337   }
338 
339   if (auto *IBI = dyn_cast<IndirectBrInst>(T)) {
340     // indirectbr blockaddress(@F, @BB) -> br label @BB
341     if (auto *BA =
342           dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
343       BasicBlock *TheOnlyDest = BA->getBasicBlock();
344       SmallSet<BasicBlock *, 8> RemovedSuccessors;
345 
346       // Insert the new branch.
347       Builder.CreateBr(TheOnlyDest);
348 
349       BasicBlock *SuccToKeep = TheOnlyDest;
350       for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
351         BasicBlock *DestBB = IBI->getDestination(i);
352         if (DTU && DestBB != TheOnlyDest)
353           RemovedSuccessors.insert(DestBB);
354         if (IBI->getDestination(i) == SuccToKeep) {
355           SuccToKeep = nullptr;
356         } else {
357           DestBB->removePredecessor(BB);
358         }
359       }
360       Value *Address = IBI->getAddress();
361       IBI->eraseFromParent();
362       if (DeleteDeadConditions)
363         // Delete pointer cast instructions.
364         RecursivelyDeleteTriviallyDeadInstructions(Address, TLI);
365 
366       // Also zap the blockaddress constant if there are no users remaining,
367       // otherwise the destination is still marked as having its address taken.
368       if (BA->use_empty())
369         BA->destroyConstant();
370 
371       // If we didn't find our destination in the IBI successor list, then we
372       // have undefined behavior.  Replace the unconditional branch with an
373       // 'unreachable' instruction.
374       if (SuccToKeep) {
375         BB->getTerminator()->eraseFromParent();
376         new UnreachableInst(BB->getContext(), BB);
377       }
378 
379       if (DTU) {
380         std::vector<DominatorTree::UpdateType> Updates;
381         Updates.reserve(RemovedSuccessors.size());
382         for (auto *RemovedSuccessor : RemovedSuccessors)
383           Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});
384         DTU->applyUpdates(Updates);
385       }
386       return true;
387     }
388   }
389 
390   return false;
391 }
392 
393 //===----------------------------------------------------------------------===//
394 //  Local dead code elimination.
395 //
396 
397 /// isInstructionTriviallyDead - Return true if the result produced by the
398 /// instruction is not used, and the instruction has no side effects.
399 ///
400 bool llvm::isInstructionTriviallyDead(Instruction *I,
401                                       const TargetLibraryInfo *TLI) {
402   if (!I->use_empty())
403     return false;
404   return wouldInstructionBeTriviallyDead(I, TLI);
405 }
406 
407 bool llvm::wouldInstructionBeTriviallyDeadOnUnusedPaths(
408     Instruction *I, const TargetLibraryInfo *TLI) {
409   // Instructions that are "markers" and have implied meaning on code around
410   // them (without explicit uses), are not dead on unused paths.
411   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
412     if (II->getIntrinsicID() == Intrinsic::stacksave ||
413         II->getIntrinsicID() == Intrinsic::launder_invariant_group ||
414         II->isLifetimeStartOrEnd())
415       return false;
416   return wouldInstructionBeTriviallyDead(I, TLI);
417 }
418 
419 bool llvm::wouldInstructionBeTriviallyDead(const Instruction *I,
420                                            const TargetLibraryInfo *TLI) {
421   if (I->isTerminator())
422     return false;
423 
424   // We don't want the landingpad-like instructions removed by anything this
425   // general.
426   if (I->isEHPad())
427     return false;
428 
429   // We don't want debug info removed by anything this general.
430   if (isa<DbgVariableIntrinsic>(I))
431     return false;
432 
433   if (const DbgLabelInst *DLI = dyn_cast<DbgLabelInst>(I)) {
434     if (DLI->getLabel())
435       return false;
436     return true;
437   }
438 
439   if (auto *CB = dyn_cast<CallBase>(I))
440     if (isRemovableAlloc(CB, TLI))
441       return true;
442 
443   if (!I->willReturn()) {
444     auto *II = dyn_cast<IntrinsicInst>(I);
445     if (!II)
446       return false;
447 
448     switch (II->getIntrinsicID()) {
449     case Intrinsic::experimental_guard: {
450       // Guards on true are operationally no-ops.  In the future we can
451       // consider more sophisticated tradeoffs for guards considering potential
452       // for check widening, but for now we keep things simple.
453       auto *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0));
454       return Cond && Cond->isOne();
455     }
456     // TODO: These intrinsics are not safe to remove, because this may remove
457     // a well-defined trap.
458     case Intrinsic::wasm_trunc_signed:
459     case Intrinsic::wasm_trunc_unsigned:
460     case Intrinsic::ptrauth_auth:
461     case Intrinsic::ptrauth_resign:
462       return true;
463     default:
464       return false;
465     }
466   }
467 
468   if (!I->mayHaveSideEffects())
469     return true;
470 
471   // Special case intrinsics that "may have side effects" but can be deleted
472   // when dead.
473   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
474     // Safe to delete llvm.stacksave and launder.invariant.group if dead.
475     if (II->getIntrinsicID() == Intrinsic::stacksave ||
476         II->getIntrinsicID() == Intrinsic::launder_invariant_group)
477       return true;
478 
479     // Intrinsics declare sideeffects to prevent them from moving, but they are
480     // nops without users.
481     if (II->getIntrinsicID() == Intrinsic::allow_runtime_check ||
482         II->getIntrinsicID() == Intrinsic::allow_ubsan_check)
483       return true;
484 
485     if (II->isLifetimeStartOrEnd()) {
486       auto *Arg = II->getArgOperand(1);
487       // Lifetime intrinsics are dead when their right-hand is undef.
488       if (isa<UndefValue>(Arg))
489         return true;
490       // If the right-hand is an alloc, global, or argument and the only uses
491       // are lifetime intrinsics then the intrinsics are dead.
492       if (isa<AllocaInst>(Arg) || isa<GlobalValue>(Arg) || isa<Argument>(Arg))
493         return llvm::all_of(Arg->uses(), [](Use &Use) {
494           if (IntrinsicInst *IntrinsicUse =
495                   dyn_cast<IntrinsicInst>(Use.getUser()))
496             return IntrinsicUse->isLifetimeStartOrEnd();
497           return false;
498         });
499       return false;
500     }
501 
502     // Assumptions are dead if their condition is trivially true.
503     if (II->getIntrinsicID() == Intrinsic::assume &&
504         isAssumeWithEmptyBundle(cast<AssumeInst>(*II))) {
505       if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0)))
506         return !Cond->isZero();
507 
508       return false;
509     }
510 
511     if (auto *FPI = dyn_cast<ConstrainedFPIntrinsic>(I)) {
512       std::optional<fp::ExceptionBehavior> ExBehavior =
513           FPI->getExceptionBehavior();
514       return *ExBehavior != fp::ebStrict;
515     }
516   }
517 
518   if (auto *Call = dyn_cast<CallBase>(I)) {
519     if (Value *FreedOp = getFreedOperand(Call, TLI))
520       if (Constant *C = dyn_cast<Constant>(FreedOp))
521         return C->isNullValue() || isa<UndefValue>(C);
522     if (isMathLibCallNoop(Call, TLI))
523       return true;
524   }
525 
526   // Non-volatile atomic loads from constants can be removed.
527   if (auto *LI = dyn_cast<LoadInst>(I))
528     if (auto *GV = dyn_cast<GlobalVariable>(
529             LI->getPointerOperand()->stripPointerCasts()))
530       if (!LI->isVolatile() && GV->isConstant())
531         return true;
532 
533   return false;
534 }
535 
536 /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
537 /// trivially dead instruction, delete it.  If that makes any of its operands
538 /// trivially dead, delete them too, recursively.  Return true if any
539 /// instructions were deleted.
540 bool llvm::RecursivelyDeleteTriviallyDeadInstructions(
541     Value *V, const TargetLibraryInfo *TLI, MemorySSAUpdater *MSSAU,
542     std::function<void(Value *)> AboutToDeleteCallback) {
543   Instruction *I = dyn_cast<Instruction>(V);
544   if (!I || !isInstructionTriviallyDead(I, TLI))
545     return false;
546 
547   SmallVector<WeakTrackingVH, 16> DeadInsts;
548   DeadInsts.push_back(I);
549   RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI, MSSAU,
550                                              AboutToDeleteCallback);
551 
552   return true;
553 }
554 
555 bool llvm::RecursivelyDeleteTriviallyDeadInstructionsPermissive(
556     SmallVectorImpl<WeakTrackingVH> &DeadInsts, const TargetLibraryInfo *TLI,
557     MemorySSAUpdater *MSSAU,
558     std::function<void(Value *)> AboutToDeleteCallback) {
559   unsigned S = 0, E = DeadInsts.size(), Alive = 0;
560   for (; S != E; ++S) {
561     auto *I = dyn_cast_or_null<Instruction>(DeadInsts[S]);
562     if (!I || !isInstructionTriviallyDead(I)) {
563       DeadInsts[S] = nullptr;
564       ++Alive;
565     }
566   }
567   if (Alive == E)
568     return false;
569   RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI, MSSAU,
570                                              AboutToDeleteCallback);
571   return true;
572 }
573 
574 void llvm::RecursivelyDeleteTriviallyDeadInstructions(
575     SmallVectorImpl<WeakTrackingVH> &DeadInsts, const TargetLibraryInfo *TLI,
576     MemorySSAUpdater *MSSAU,
577     std::function<void(Value *)> AboutToDeleteCallback) {
578   // Process the dead instruction list until empty.
579   while (!DeadInsts.empty()) {
580     Value *V = DeadInsts.pop_back_val();
581     Instruction *I = cast_or_null<Instruction>(V);
582     if (!I)
583       continue;
584     assert(isInstructionTriviallyDead(I, TLI) &&
585            "Live instruction found in dead worklist!");
586     assert(I->use_empty() && "Instructions with uses are not dead.");
587 
588     // Don't lose the debug info while deleting the instructions.
589     salvageDebugInfo(*I);
590 
591     if (AboutToDeleteCallback)
592       AboutToDeleteCallback(I);
593 
594     // Null out all of the instruction's operands to see if any operand becomes
595     // dead as we go.
596     for (Use &OpU : I->operands()) {
597       Value *OpV = OpU.get();
598       OpU.set(nullptr);
599 
600       if (!OpV->use_empty())
601         continue;
602 
603       // If the operand is an instruction that became dead as we nulled out the
604       // operand, and if it is 'trivially' dead, delete it in a future loop
605       // iteration.
606       if (Instruction *OpI = dyn_cast<Instruction>(OpV))
607         if (isInstructionTriviallyDead(OpI, TLI))
608           DeadInsts.push_back(OpI);
609     }
610     if (MSSAU)
611       MSSAU->removeMemoryAccess(I);
612 
613     I->eraseFromParent();
614   }
615 }
616 
617 bool llvm::replaceDbgUsesWithUndef(Instruction *I) {
618   SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
619   SmallVector<DbgVariableRecord *, 1> DPUsers;
620   findDbgUsers(DbgUsers, I, &DPUsers);
621   for (auto *DII : DbgUsers)
622     DII->setKillLocation();
623   for (auto *DVR : DPUsers)
624     DVR->setKillLocation();
625   return !DbgUsers.empty() || !DPUsers.empty();
626 }
627 
628 /// areAllUsesEqual - Check whether the uses of a value are all the same.
629 /// This is similar to Instruction::hasOneUse() except this will also return
630 /// true when there are no uses or multiple uses that all refer to the same
631 /// value.
632 static bool areAllUsesEqual(Instruction *I) {
633   Value::user_iterator UI = I->user_begin();
634   Value::user_iterator UE = I->user_end();
635   if (UI == UE)
636     return true;
637 
638   User *TheUse = *UI;
639   for (++UI; UI != UE; ++UI) {
640     if (*UI != TheUse)
641       return false;
642   }
643   return true;
644 }
645 
646 /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
647 /// dead PHI node, due to being a def-use chain of single-use nodes that
648 /// either forms a cycle or is terminated by a trivially dead instruction,
649 /// delete it.  If that makes any of its operands trivially dead, delete them
650 /// too, recursively.  Return true if a change was made.
651 bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN,
652                                         const TargetLibraryInfo *TLI,
653                                         llvm::MemorySSAUpdater *MSSAU) {
654   SmallPtrSet<Instruction*, 4> Visited;
655   for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
656        I = cast<Instruction>(*I->user_begin())) {
657     if (I->use_empty())
658       return RecursivelyDeleteTriviallyDeadInstructions(I, TLI, MSSAU);
659 
660     // If we find an instruction more than once, we're on a cycle that
661     // won't prove fruitful.
662     if (!Visited.insert(I).second) {
663       // Break the cycle and delete the instruction and its operands.
664       I->replaceAllUsesWith(PoisonValue::get(I->getType()));
665       (void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI, MSSAU);
666       return true;
667     }
668   }
669   return false;
670 }
671 
672 static bool
673 simplifyAndDCEInstruction(Instruction *I,
674                           SmallSetVector<Instruction *, 16> &WorkList,
675                           const DataLayout &DL,
676                           const TargetLibraryInfo *TLI) {
677   if (isInstructionTriviallyDead(I, TLI)) {
678     salvageDebugInfo(*I);
679 
680     // Null out all of the instruction's operands to see if any operand becomes
681     // dead as we go.
682     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
683       Value *OpV = I->getOperand(i);
684       I->setOperand(i, nullptr);
685 
686       if (!OpV->use_empty() || I == OpV)
687         continue;
688 
689       // If the operand is an instruction that became dead as we nulled out the
690       // operand, and if it is 'trivially' dead, delete it in a future loop
691       // iteration.
692       if (Instruction *OpI = dyn_cast<Instruction>(OpV))
693         if (isInstructionTriviallyDead(OpI, TLI))
694           WorkList.insert(OpI);
695     }
696 
697     I->eraseFromParent();
698 
699     return true;
700   }
701 
702   if (Value *SimpleV = simplifyInstruction(I, DL)) {
703     // Add the users to the worklist. CAREFUL: an instruction can use itself,
704     // in the case of a phi node.
705     for (User *U : I->users()) {
706       if (U != I) {
707         WorkList.insert(cast<Instruction>(U));
708       }
709     }
710 
711     // Replace the instruction with its simplified value.
712     bool Changed = false;
713     if (!I->use_empty()) {
714       I->replaceAllUsesWith(SimpleV);
715       Changed = true;
716     }
717     if (isInstructionTriviallyDead(I, TLI)) {
718       I->eraseFromParent();
719       Changed = true;
720     }
721     return Changed;
722   }
723   return false;
724 }
725 
726 /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
727 /// simplify any instructions in it and recursively delete dead instructions.
728 ///
729 /// This returns true if it changed the code, note that it can delete
730 /// instructions in other blocks as well in this block.
731 bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB,
732                                        const TargetLibraryInfo *TLI) {
733   bool MadeChange = false;
734   const DataLayout &DL = BB->getDataLayout();
735 
736 #ifndef NDEBUG
737   // In debug builds, ensure that the terminator of the block is never replaced
738   // or deleted by these simplifications. The idea of simplification is that it
739   // cannot introduce new instructions, and there is no way to replace the
740   // terminator of a block without introducing a new instruction.
741   AssertingVH<Instruction> TerminatorVH(&BB->back());
742 #endif
743 
744   SmallSetVector<Instruction *, 16> WorkList;
745   // Iterate over the original function, only adding insts to the worklist
746   // if they actually need to be revisited. This avoids having to pre-init
747   // the worklist with the entire function's worth of instructions.
748   for (BasicBlock::iterator BI = BB->begin(), E = std::prev(BB->end());
749        BI != E;) {
750     assert(!BI->isTerminator());
751     Instruction *I = &*BI;
752     ++BI;
753 
754     // We're visiting this instruction now, so make sure it's not in the
755     // worklist from an earlier visit.
756     if (!WorkList.count(I))
757       MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
758   }
759 
760   while (!WorkList.empty()) {
761     Instruction *I = WorkList.pop_back_val();
762     MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
763   }
764   return MadeChange;
765 }
766 
767 //===----------------------------------------------------------------------===//
768 //  Control Flow Graph Restructuring.
769 //
770 
771 void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB,
772                                        DomTreeUpdater *DTU) {
773 
774   // If BB has single-entry PHI nodes, fold them.
775   while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
776     Value *NewVal = PN->getIncomingValue(0);
777     // Replace self referencing PHI with poison, it must be dead.
778     if (NewVal == PN) NewVal = PoisonValue::get(PN->getType());
779     PN->replaceAllUsesWith(NewVal);
780     PN->eraseFromParent();
781   }
782 
783   BasicBlock *PredBB = DestBB->getSinglePredecessor();
784   assert(PredBB && "Block doesn't have a single predecessor!");
785 
786   bool ReplaceEntryBB = PredBB->isEntryBlock();
787 
788   // DTU updates: Collect all the edges that enter
789   // PredBB. These dominator edges will be redirected to DestBB.
790   SmallVector<DominatorTree::UpdateType, 32> Updates;
791 
792   if (DTU) {
793     // To avoid processing the same predecessor more than once.
794     SmallPtrSet<BasicBlock *, 2> SeenPreds;
795     Updates.reserve(Updates.size() + 2 * pred_size(PredBB) + 1);
796     for (BasicBlock *PredOfPredBB : predecessors(PredBB))
797       // This predecessor of PredBB may already have DestBB as a successor.
798       if (PredOfPredBB != PredBB)
799         if (SeenPreds.insert(PredOfPredBB).second)
800           Updates.push_back({DominatorTree::Insert, PredOfPredBB, DestBB});
801     SeenPreds.clear();
802     for (BasicBlock *PredOfPredBB : predecessors(PredBB))
803       if (SeenPreds.insert(PredOfPredBB).second)
804         Updates.push_back({DominatorTree::Delete, PredOfPredBB, PredBB});
805     Updates.push_back({DominatorTree::Delete, PredBB, DestBB});
806   }
807 
808   // Zap anything that took the address of DestBB.  Not doing this will give the
809   // address an invalid value.
810   if (DestBB->hasAddressTaken()) {
811     BlockAddress *BA = BlockAddress::get(DestBB);
812     Constant *Replacement =
813       ConstantInt::get(Type::getInt32Ty(BA->getContext()), 1);
814     BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
815                                                      BA->getType()));
816     BA->destroyConstant();
817   }
818 
819   // Anything that branched to PredBB now branches to DestBB.
820   PredBB->replaceAllUsesWith(DestBB);
821 
822   // Splice all the instructions from PredBB to DestBB.
823   PredBB->getTerminator()->eraseFromParent();
824   DestBB->splice(DestBB->begin(), PredBB);
825   new UnreachableInst(PredBB->getContext(), PredBB);
826 
827   // If the PredBB is the entry block of the function, move DestBB up to
828   // become the entry block after we erase PredBB.
829   if (ReplaceEntryBB)
830     DestBB->moveAfter(PredBB);
831 
832   if (DTU) {
833     assert(PredBB->size() == 1 &&
834            isa<UnreachableInst>(PredBB->getTerminator()) &&
835            "The successor list of PredBB isn't empty before "
836            "applying corresponding DTU updates.");
837     DTU->applyUpdatesPermissive(Updates);
838     DTU->deleteBB(PredBB);
839     // Recalculation of DomTree is needed when updating a forward DomTree and
840     // the Entry BB is replaced.
841     if (ReplaceEntryBB && DTU->hasDomTree()) {
842       // The entry block was removed and there is no external interface for
843       // the dominator tree to be notified of this change. In this corner-case
844       // we recalculate the entire tree.
845       DTU->recalculate(*(DestBB->getParent()));
846     }
847   }
848 
849   else {
850     PredBB->eraseFromParent(); // Nuke BB if DTU is nullptr.
851   }
852 }
853 
854 /// Return true if we can choose one of these values to use in place of the
855 /// other. Note that we will always choose the non-undef value to keep.
856 static bool CanMergeValues(Value *First, Value *Second) {
857   return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
858 }
859 
860 /// Return true if we can fold BB, an almost-empty BB ending in an unconditional
861 /// branch to Succ, into Succ.
862 ///
863 /// Assumption: Succ is the single successor for BB.
864 static bool
865 CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ,
866                                 const SmallPtrSetImpl<BasicBlock *> &BBPreds) {
867   assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
868 
869   LLVM_DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
870                     << Succ->getName() << "\n");
871   // Shortcut, if there is only a single predecessor it must be BB and merging
872   // is always safe
873   if (Succ->getSinglePredecessor())
874     return true;
875 
876   // Look at all the phi nodes in Succ, to see if they present a conflict when
877   // merging these blocks
878   for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
879     PHINode *PN = cast<PHINode>(I);
880 
881     // If the incoming value from BB is again a PHINode in
882     // BB which has the same incoming value for *PI as PN does, we can
883     // merge the phi nodes and then the blocks can still be merged
884     PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
885     if (BBPN && BBPN->getParent() == BB) {
886       for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
887         BasicBlock *IBB = PN->getIncomingBlock(PI);
888         if (BBPreds.count(IBB) &&
889             !CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
890                             PN->getIncomingValue(PI))) {
891           LLVM_DEBUG(dbgs()
892                      << "Can't fold, phi node " << PN->getName() << " in "
893                      << Succ->getName() << " is conflicting with "
894                      << BBPN->getName() << " with regard to common predecessor "
895                      << IBB->getName() << "\n");
896           return false;
897         }
898       }
899     } else {
900       Value* Val = PN->getIncomingValueForBlock(BB);
901       for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
902         // See if the incoming value for the common predecessor is equal to the
903         // one for BB, in which case this phi node will not prevent the merging
904         // of the block.
905         BasicBlock *IBB = PN->getIncomingBlock(PI);
906         if (BBPreds.count(IBB) &&
907             !CanMergeValues(Val, PN->getIncomingValue(PI))) {
908           LLVM_DEBUG(dbgs() << "Can't fold, phi node " << PN->getName()
909                             << " in " << Succ->getName()
910                             << " is conflicting with regard to common "
911                             << "predecessor " << IBB->getName() << "\n");
912           return false;
913         }
914       }
915     }
916   }
917 
918   return true;
919 }
920 
921 using PredBlockVector = SmallVector<BasicBlock *, 16>;
922 using IncomingValueMap = DenseMap<BasicBlock *, Value *>;
923 
924 /// Determines the value to use as the phi node input for a block.
925 ///
926 /// Select between \p OldVal any value that we know flows from \p BB
927 /// to a particular phi on the basis of which one (if either) is not
928 /// undef. Update IncomingValues based on the selected value.
929 ///
930 /// \param OldVal The value we are considering selecting.
931 /// \param BB The block that the value flows in from.
932 /// \param IncomingValues A map from block-to-value for other phi inputs
933 /// that we have examined.
934 ///
935 /// \returns the selected value.
936 static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
937                                           IncomingValueMap &IncomingValues) {
938   if (!isa<UndefValue>(OldVal)) {
939     assert((!IncomingValues.count(BB) ||
940             IncomingValues.find(BB)->second == OldVal) &&
941            "Expected OldVal to match incoming value from BB!");
942 
943     IncomingValues.insert(std::make_pair(BB, OldVal));
944     return OldVal;
945   }
946 
947   IncomingValueMap::const_iterator It = IncomingValues.find(BB);
948   if (It != IncomingValues.end()) return It->second;
949 
950   return OldVal;
951 }
952 
953 /// Create a map from block to value for the operands of a
954 /// given phi.
955 ///
956 /// Create a map from block to value for each non-undef value flowing
957 /// into \p PN.
958 ///
959 /// \param PN The phi we are collecting the map for.
960 /// \param IncomingValues [out] The map from block to value for this phi.
961 static void gatherIncomingValuesToPhi(PHINode *PN,
962                                       IncomingValueMap &IncomingValues) {
963   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
964     BasicBlock *BB = PN->getIncomingBlock(i);
965     Value *V = PN->getIncomingValue(i);
966 
967     if (!isa<UndefValue>(V))
968       IncomingValues.insert(std::make_pair(BB, V));
969   }
970 }
971 
972 /// Replace the incoming undef values to a phi with the values
973 /// from a block-to-value map.
974 ///
975 /// \param PN The phi we are replacing the undefs in.
976 /// \param IncomingValues A map from block to value.
977 static void replaceUndefValuesInPhi(PHINode *PN,
978                                     const IncomingValueMap &IncomingValues) {
979   SmallVector<unsigned> TrueUndefOps;
980   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
981     Value *V = PN->getIncomingValue(i);
982 
983     if (!isa<UndefValue>(V)) continue;
984 
985     BasicBlock *BB = PN->getIncomingBlock(i);
986     IncomingValueMap::const_iterator It = IncomingValues.find(BB);
987 
988     // Keep track of undef/poison incoming values. Those must match, so we fix
989     // them up below if needed.
990     // Note: this is conservatively correct, but we could try harder and group
991     // the undef values per incoming basic block.
992     if (It == IncomingValues.end()) {
993       TrueUndefOps.push_back(i);
994       continue;
995     }
996 
997     // There is a defined value for this incoming block, so map this undef
998     // incoming value to the defined value.
999     PN->setIncomingValue(i, It->second);
1000   }
1001 
1002   // If there are both undef and poison values incoming, then convert those
1003   // values to undef. It is invalid to have different values for the same
1004   // incoming block.
1005   unsigned PoisonCount = count_if(TrueUndefOps, [&](unsigned i) {
1006     return isa<PoisonValue>(PN->getIncomingValue(i));
1007   });
1008   if (PoisonCount != 0 && PoisonCount != TrueUndefOps.size()) {
1009     for (unsigned i : TrueUndefOps)
1010       PN->setIncomingValue(i, UndefValue::get(PN->getType()));
1011   }
1012 }
1013 
1014 // Only when they shares a single common predecessor, return true.
1015 // Only handles cases when BB can't be merged while its predecessors can be
1016 // redirected.
1017 static bool
1018 CanRedirectPredsOfEmptyBBToSucc(BasicBlock *BB, BasicBlock *Succ,
1019                                 const SmallPtrSetImpl<BasicBlock *> &BBPreds,
1020                                 const SmallPtrSetImpl<BasicBlock *> &SuccPreds,
1021                                 BasicBlock *&CommonPred) {
1022 
1023   // There must be phis in BB, otherwise BB will be merged into Succ directly
1024   if (BB->phis().empty() || Succ->phis().empty())
1025     return false;
1026 
1027   // BB must have predecessors not shared that can be redirected to Succ
1028   if (!BB->hasNPredecessorsOrMore(2))
1029     return false;
1030 
1031   if (any_of(BBPreds, [](const BasicBlock *Pred) {
1032         return isa<PHINode>(Pred->begin()) &&
1033                isa<IndirectBrInst>(Pred->getTerminator());
1034       }))
1035     return false;
1036 
1037   // Get the single common predecessor of both BB and Succ. Return false
1038   // when there are more than one common predecessors.
1039   for (BasicBlock *SuccPred : SuccPreds) {
1040     if (BBPreds.count(SuccPred)) {
1041       if (CommonPred)
1042         return false;
1043       CommonPred = SuccPred;
1044     }
1045   }
1046 
1047   return true;
1048 }
1049 
1050 /// Replace a value flowing from a block to a phi with
1051 /// potentially multiple instances of that value flowing from the
1052 /// block's predecessors to the phi.
1053 ///
1054 /// \param BB The block with the value flowing into the phi.
1055 /// \param BBPreds The predecessors of BB.
1056 /// \param PN The phi that we are updating.
1057 /// \param CommonPred The common predecessor of BB and PN's BasicBlock
1058 static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
1059                                                 const PredBlockVector &BBPreds,
1060                                                 PHINode *PN,
1061                                                 BasicBlock *CommonPred) {
1062   Value *OldVal = PN->removeIncomingValue(BB, false);
1063   assert(OldVal && "No entry in PHI for Pred BB!");
1064 
1065   IncomingValueMap IncomingValues;
1066 
1067   // We are merging two blocks - BB, and the block containing PN - and
1068   // as a result we need to redirect edges from the predecessors of BB
1069   // to go to the block containing PN, and update PN
1070   // accordingly. Since we allow merging blocks in the case where the
1071   // predecessor and successor blocks both share some predecessors,
1072   // and where some of those common predecessors might have undef
1073   // values flowing into PN, we want to rewrite those values to be
1074   // consistent with the non-undef values.
1075 
1076   gatherIncomingValuesToPhi(PN, IncomingValues);
1077 
1078   // If this incoming value is one of the PHI nodes in BB, the new entries
1079   // in the PHI node are the entries from the old PHI.
1080   if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
1081     PHINode *OldValPN = cast<PHINode>(OldVal);
1082     for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
1083       // Note that, since we are merging phi nodes and BB and Succ might
1084       // have common predecessors, we could end up with a phi node with
1085       // identical incoming branches. This will be cleaned up later (and
1086       // will trigger asserts if we try to clean it up now, without also
1087       // simplifying the corresponding conditional branch).
1088       BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
1089 
1090       if (PredBB == CommonPred)
1091         continue;
1092 
1093       Value *PredVal = OldValPN->getIncomingValue(i);
1094       Value *Selected =
1095           selectIncomingValueForBlock(PredVal, PredBB, IncomingValues);
1096 
1097       // And add a new incoming value for this predecessor for the
1098       // newly retargeted branch.
1099       PN->addIncoming(Selected, PredBB);
1100     }
1101     if (CommonPred)
1102       PN->addIncoming(OldValPN->getIncomingValueForBlock(CommonPred), BB);
1103 
1104   } else {
1105     for (BasicBlock *PredBB : BBPreds) {
1106       // Update existing incoming values in PN for this
1107       // predecessor of BB.
1108       if (PredBB == CommonPred)
1109         continue;
1110 
1111       Value *Selected =
1112           selectIncomingValueForBlock(OldVal, PredBB, IncomingValues);
1113 
1114       // And add a new incoming value for this predecessor for the
1115       // newly retargeted branch.
1116       PN->addIncoming(Selected, PredBB);
1117     }
1118     if (CommonPred)
1119       PN->addIncoming(OldVal, BB);
1120   }
1121 
1122   replaceUndefValuesInPhi(PN, IncomingValues);
1123 }
1124 
1125 bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
1126                                                    DomTreeUpdater *DTU) {
1127   assert(BB != &BB->getParent()->getEntryBlock() &&
1128          "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
1129 
1130   // We can't simplify infinite loops.
1131   BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
1132   if (BB == Succ)
1133     return false;
1134 
1135   SmallPtrSet<BasicBlock *, 16> BBPreds(pred_begin(BB), pred_end(BB));
1136   SmallPtrSet<BasicBlock *, 16> SuccPreds(pred_begin(Succ), pred_end(Succ));
1137 
1138   // The single common predecessor of BB and Succ when BB cannot be killed
1139   BasicBlock *CommonPred = nullptr;
1140 
1141   bool BBKillable = CanPropagatePredecessorsForPHIs(BB, Succ, BBPreds);
1142 
1143   // Even if we can not fold BB into Succ, we may be able to redirect the
1144   // predecessors of BB to Succ.
1145   bool BBPhisMergeable =
1146       BBKillable ||
1147       CanRedirectPredsOfEmptyBBToSucc(BB, Succ, BBPreds, SuccPreds, CommonPred);
1148 
1149   if (!BBKillable && !BBPhisMergeable)
1150     return false;
1151 
1152   // Check to see if merging these blocks/phis would cause conflicts for any of
1153   // the phi nodes in BB or Succ. If not, we can safely merge.
1154 
1155   // Check for cases where Succ has multiple predecessors and a PHI node in BB
1156   // has uses which will not disappear when the PHI nodes are merged.  It is
1157   // possible to handle such cases, but difficult: it requires checking whether
1158   // BB dominates Succ, which is non-trivial to calculate in the case where
1159   // Succ has multiple predecessors.  Also, it requires checking whether
1160   // constructing the necessary self-referential PHI node doesn't introduce any
1161   // conflicts; this isn't too difficult, but the previous code for doing this
1162   // was incorrect.
1163   //
1164   // Note that if this check finds a live use, BB dominates Succ, so BB is
1165   // something like a loop pre-header (or rarely, a part of an irreducible CFG);
1166   // folding the branch isn't profitable in that case anyway.
1167   if (!Succ->getSinglePredecessor()) {
1168     BasicBlock::iterator BBI = BB->begin();
1169     while (isa<PHINode>(*BBI)) {
1170       for (Use &U : BBI->uses()) {
1171         if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
1172           if (PN->getIncomingBlock(U) != BB)
1173             return false;
1174         } else {
1175           return false;
1176         }
1177       }
1178       ++BBI;
1179     }
1180   }
1181 
1182   if (BBPhisMergeable && CommonPred)
1183     LLVM_DEBUG(dbgs() << "Found Common Predecessor between: " << BB->getName()
1184                       << " and " << Succ->getName() << " : "
1185                       << CommonPred->getName() << "\n");
1186 
1187   // 'BB' and 'BB->Pred' are loop latches, bail out to presrve inner loop
1188   // metadata.
1189   //
1190   // FIXME: This is a stop-gap solution to preserve inner-loop metadata given
1191   // current status (that loop metadata is implemented as metadata attached to
1192   // the branch instruction in the loop latch block). To quote from review
1193   // comments, "the current representation of loop metadata (using a loop latch
1194   // terminator attachment) is known to be fundamentally broken. Loop latches
1195   // are not uniquely associated with loops (both in that a latch can be part of
1196   // multiple loops and a loop may have multiple latches). Loop headers are. The
1197   // solution to this problem is also known: Add support for basic block
1198   // metadata, and attach loop metadata to the loop header."
1199   //
1200   // Why bail out:
1201   // In this case, we expect 'BB' is the latch for outer-loop and 'BB->Pred' is
1202   // the latch for inner-loop (see reason below), so bail out to prerserve
1203   // inner-loop metadata rather than eliminating 'BB' and attaching its metadata
1204   // to this inner-loop.
1205   // - The reason we believe 'BB' and 'BB->Pred' have different inner-most
1206   // loops: assuming 'BB' and 'BB->Pred' are from the same inner-most loop L,
1207   // then 'BB' is the header and latch of 'L' and thereby 'L' must consist of
1208   // one self-looping basic block, which is contradictory with the assumption.
1209   //
1210   // To illustrate how inner-loop metadata is dropped:
1211   //
1212   // CFG Before
1213   //
1214   // BB is while.cond.exit, attached with loop metdata md2.
1215   // BB->Pred is for.body, attached with loop metadata md1.
1216   //
1217   //      entry
1218   //        |
1219   //        v
1220   // ---> while.cond   ------------->  while.end
1221   // |       |
1222   // |       v
1223   // |   while.body
1224   // |       |
1225   // |       v
1226   // |    for.body <---- (md1)
1227   // |       |  |______|
1228   // |       v
1229   // |    while.cond.exit (md2)
1230   // |       |
1231   // |_______|
1232   //
1233   // CFG After
1234   //
1235   // while.cond1 is the merge of while.cond.exit and while.cond above.
1236   // for.body is attached with md2, and md1 is dropped.
1237   // If LoopSimplify runs later (as a part of loop pass), it could create
1238   // dedicated exits for inner-loop (essentially adding `while.cond.exit`
1239   // back), but won't it won't see 'md1' nor restore it for the inner-loop.
1240   //
1241   //       entry
1242   //         |
1243   //         v
1244   // ---> while.cond1  ------------->  while.end
1245   // |       |
1246   // |       v
1247   // |   while.body
1248   // |       |
1249   // |       v
1250   // |    for.body <---- (md2)
1251   // |_______|  |______|
1252   if (Instruction *TI = BB->getTerminator())
1253     if (TI->hasMetadata(LLVMContext::MD_loop))
1254       for (BasicBlock *Pred : predecessors(BB))
1255         if (Instruction *PredTI = Pred->getTerminator())
1256           if (PredTI->hasMetadata(LLVMContext::MD_loop))
1257             return false;
1258 
1259   if (BBKillable)
1260     LLVM_DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
1261   else if (BBPhisMergeable)
1262     LLVM_DEBUG(dbgs() << "Merge Phis in Trivial BB: \n" << *BB);
1263 
1264   SmallVector<DominatorTree::UpdateType, 32> Updates;
1265 
1266   if (DTU) {
1267     // To avoid processing the same predecessor more than once.
1268     SmallPtrSet<BasicBlock *, 8> SeenPreds;
1269     // All predecessors of BB (except the common predecessor) will be moved to
1270     // Succ.
1271     Updates.reserve(Updates.size() + 2 * pred_size(BB) + 1);
1272 
1273     for (auto *PredOfBB : predecessors(BB)) {
1274       // Do not modify those common predecessors of BB and Succ
1275       if (!SuccPreds.contains(PredOfBB))
1276         if (SeenPreds.insert(PredOfBB).second)
1277           Updates.push_back({DominatorTree::Insert, PredOfBB, Succ});
1278     }
1279 
1280     SeenPreds.clear();
1281 
1282     for (auto *PredOfBB : predecessors(BB))
1283       // When BB cannot be killed, do not remove the edge between BB and
1284       // CommonPred.
1285       if (SeenPreds.insert(PredOfBB).second && PredOfBB != CommonPred)
1286         Updates.push_back({DominatorTree::Delete, PredOfBB, BB});
1287 
1288     if (BBKillable)
1289       Updates.push_back({DominatorTree::Delete, BB, Succ});
1290   }
1291 
1292   if (isa<PHINode>(Succ->begin())) {
1293     // If there is more than one pred of succ, and there are PHI nodes in
1294     // the successor, then we need to add incoming edges for the PHI nodes
1295     //
1296     const PredBlockVector BBPreds(predecessors(BB));
1297 
1298     // Loop over all of the PHI nodes in the successor of BB.
1299     for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
1300       PHINode *PN = cast<PHINode>(I);
1301       redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN, CommonPred);
1302     }
1303   }
1304 
1305   if (Succ->getSinglePredecessor()) {
1306     // BB is the only predecessor of Succ, so Succ will end up with exactly
1307     // the same predecessors BB had.
1308     // Copy over any phi, debug or lifetime instruction.
1309     BB->getTerminator()->eraseFromParent();
1310     Succ->splice(Succ->getFirstNonPHIIt(), BB);
1311   } else {
1312     while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
1313       // We explicitly check for such uses for merging phis.
1314       assert(PN->use_empty() && "There shouldn't be any uses here!");
1315       PN->eraseFromParent();
1316     }
1317   }
1318 
1319   // If the unconditional branch we replaced contains llvm.loop metadata, we
1320   // add the metadata to the branch instructions in the predecessors.
1321   if (Instruction *TI = BB->getTerminator())
1322     if (MDNode *LoopMD = TI->getMetadata(LLVMContext::MD_loop))
1323       for (BasicBlock *Pred : predecessors(BB))
1324         Pred->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopMD);
1325 
1326   if (BBKillable) {
1327     // Everything that jumped to BB now goes to Succ.
1328     BB->replaceAllUsesWith(Succ);
1329 
1330     if (!Succ->hasName())
1331       Succ->takeName(BB);
1332 
1333     // Clear the successor list of BB to match updates applying to DTU later.
1334     if (BB->getTerminator())
1335       BB->back().eraseFromParent();
1336 
1337     new UnreachableInst(BB->getContext(), BB);
1338     assert(succ_empty(BB) && "The successor list of BB isn't empty before "
1339                              "applying corresponding DTU updates.");
1340   } else if (BBPhisMergeable) {
1341     //  Everything except CommonPred that jumped to BB now goes to Succ.
1342     BB->replaceUsesWithIf(Succ, [BBPreds, CommonPred](Use &U) -> bool {
1343       if (Instruction *UseInst = dyn_cast<Instruction>(U.getUser()))
1344         return UseInst->getParent() != CommonPred &&
1345                BBPreds.contains(UseInst->getParent());
1346       return false;
1347     });
1348   }
1349 
1350   if (DTU)
1351     DTU->applyUpdates(Updates);
1352 
1353   if (BBKillable)
1354     DeleteDeadBlock(BB, DTU);
1355 
1356   return true;
1357 }
1358 
1359 static bool
1360 EliminateDuplicatePHINodesNaiveImpl(BasicBlock *BB,
1361                                     SmallPtrSetImpl<PHINode *> &ToRemove) {
1362   // This implementation doesn't currently consider undef operands
1363   // specially. Theoretically, two phis which are identical except for
1364   // one having an undef where the other doesn't could be collapsed.
1365 
1366   bool Changed = false;
1367 
1368   // Examine each PHI.
1369   // Note that increment of I must *NOT* be in the iteration_expression, since
1370   // we don't want to immediately advance when we restart from the beginning.
1371   for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I);) {
1372     ++I;
1373     // Is there an identical PHI node in this basic block?
1374     // Note that we only look in the upper square's triangle,
1375     // we already checked that the lower triangle PHI's aren't identical.
1376     for (auto J = I; PHINode *DuplicatePN = dyn_cast<PHINode>(J); ++J) {
1377       if (ToRemove.contains(DuplicatePN))
1378         continue;
1379       if (!DuplicatePN->isIdenticalToWhenDefined(PN))
1380         continue;
1381       // A duplicate. Replace this PHI with the base PHI.
1382       ++NumPHICSEs;
1383       DuplicatePN->replaceAllUsesWith(PN);
1384       ToRemove.insert(DuplicatePN);
1385       Changed = true;
1386 
1387       // The RAUW can change PHIs that we already visited.
1388       I = BB->begin();
1389       break; // Start over from the beginning.
1390     }
1391   }
1392   return Changed;
1393 }
1394 
1395 static bool
1396 EliminateDuplicatePHINodesSetBasedImpl(BasicBlock *BB,
1397                                        SmallPtrSetImpl<PHINode *> &ToRemove) {
1398   // This implementation doesn't currently consider undef operands
1399   // specially. Theoretically, two phis which are identical except for
1400   // one having an undef where the other doesn't could be collapsed.
1401 
1402   struct PHIDenseMapInfo {
1403     static PHINode *getEmptyKey() {
1404       return DenseMapInfo<PHINode *>::getEmptyKey();
1405     }
1406 
1407     static PHINode *getTombstoneKey() {
1408       return DenseMapInfo<PHINode *>::getTombstoneKey();
1409     }
1410 
1411     static bool isSentinel(PHINode *PN) {
1412       return PN == getEmptyKey() || PN == getTombstoneKey();
1413     }
1414 
1415     // WARNING: this logic must be kept in sync with
1416     //          Instruction::isIdenticalToWhenDefined()!
1417     static unsigned getHashValueImpl(PHINode *PN) {
1418       // Compute a hash value on the operands. Instcombine will likely have
1419       // sorted them, which helps expose duplicates, but we have to check all
1420       // the operands to be safe in case instcombine hasn't run.
1421       return static_cast<unsigned>(hash_combine(
1422           hash_combine_range(PN->value_op_begin(), PN->value_op_end()),
1423           hash_combine_range(PN->block_begin(), PN->block_end())));
1424     }
1425 
1426     static unsigned getHashValue(PHINode *PN) {
1427 #ifndef NDEBUG
1428       // If -phicse-debug-hash was specified, return a constant -- this
1429       // will force all hashing to collide, so we'll exhaustively search
1430       // the table for a match, and the assertion in isEqual will fire if
1431       // there's a bug causing equal keys to hash differently.
1432       if (PHICSEDebugHash)
1433         return 0;
1434 #endif
1435       return getHashValueImpl(PN);
1436     }
1437 
1438     static bool isEqualImpl(PHINode *LHS, PHINode *RHS) {
1439       if (isSentinel(LHS) || isSentinel(RHS))
1440         return LHS == RHS;
1441       return LHS->isIdenticalTo(RHS);
1442     }
1443 
1444     static bool isEqual(PHINode *LHS, PHINode *RHS) {
1445       // These comparisons are nontrivial, so assert that equality implies
1446       // hash equality (DenseMap demands this as an invariant).
1447       bool Result = isEqualImpl(LHS, RHS);
1448       assert(!Result || (isSentinel(LHS) && LHS == RHS) ||
1449              getHashValueImpl(LHS) == getHashValueImpl(RHS));
1450       return Result;
1451     }
1452   };
1453 
1454   // Set of unique PHINodes.
1455   DenseSet<PHINode *, PHIDenseMapInfo> PHISet;
1456   PHISet.reserve(4 * PHICSENumPHISmallSize);
1457 
1458   // Examine each PHI.
1459   bool Changed = false;
1460   for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I++);) {
1461     if (ToRemove.contains(PN))
1462       continue;
1463     auto Inserted = PHISet.insert(PN);
1464     if (!Inserted.second) {
1465       // A duplicate. Replace this PHI with its duplicate.
1466       ++NumPHICSEs;
1467       PN->replaceAllUsesWith(*Inserted.first);
1468       ToRemove.insert(PN);
1469       Changed = true;
1470 
1471       // The RAUW can change PHIs that we already visited. Start over from the
1472       // beginning.
1473       PHISet.clear();
1474       I = BB->begin();
1475     }
1476   }
1477 
1478   return Changed;
1479 }
1480 
1481 bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB,
1482                                       SmallPtrSetImpl<PHINode *> &ToRemove) {
1483   if (
1484 #ifndef NDEBUG
1485       !PHICSEDebugHash &&
1486 #endif
1487       hasNItemsOrLess(BB->phis(), PHICSENumPHISmallSize))
1488     return EliminateDuplicatePHINodesNaiveImpl(BB, ToRemove);
1489   return EliminateDuplicatePHINodesSetBasedImpl(BB, ToRemove);
1490 }
1491 
1492 bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
1493   SmallPtrSet<PHINode *, 8> ToRemove;
1494   bool Changed = EliminateDuplicatePHINodes(BB, ToRemove);
1495   for (PHINode *PN : ToRemove)
1496     PN->eraseFromParent();
1497   return Changed;
1498 }
1499 
1500 Align llvm::tryEnforceAlignment(Value *V, Align PrefAlign,
1501                                 const DataLayout &DL) {
1502   V = V->stripPointerCasts();
1503 
1504   if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1505     // TODO: Ideally, this function would not be called if PrefAlign is smaller
1506     // than the current alignment, as the known bits calculation should have
1507     // already taken it into account. However, this is not always the case,
1508     // as computeKnownBits() has a depth limit, while stripPointerCasts()
1509     // doesn't.
1510     Align CurrentAlign = AI->getAlign();
1511     if (PrefAlign <= CurrentAlign)
1512       return CurrentAlign;
1513 
1514     // If the preferred alignment is greater than the natural stack alignment
1515     // then don't round up. This avoids dynamic stack realignment.
1516     MaybeAlign StackAlign = DL.getStackAlignment();
1517     if (StackAlign && PrefAlign > *StackAlign)
1518       return CurrentAlign;
1519     AI->setAlignment(PrefAlign);
1520     return PrefAlign;
1521   }
1522 
1523   if (auto *GO = dyn_cast<GlobalObject>(V)) {
1524     // TODO: as above, this shouldn't be necessary.
1525     Align CurrentAlign = GO->getPointerAlignment(DL);
1526     if (PrefAlign <= CurrentAlign)
1527       return CurrentAlign;
1528 
1529     // If there is a large requested alignment and we can, bump up the alignment
1530     // of the global.  If the memory we set aside for the global may not be the
1531     // memory used by the final program then it is impossible for us to reliably
1532     // enforce the preferred alignment.
1533     if (!GO->canIncreaseAlignment())
1534       return CurrentAlign;
1535 
1536     if (GO->isThreadLocal()) {
1537       unsigned MaxTLSAlign = GO->getParent()->getMaxTLSAlignment() / CHAR_BIT;
1538       if (MaxTLSAlign && PrefAlign > Align(MaxTLSAlign))
1539         PrefAlign = Align(MaxTLSAlign);
1540     }
1541 
1542     GO->setAlignment(PrefAlign);
1543     return PrefAlign;
1544   }
1545 
1546   return Align(1);
1547 }
1548 
1549 Align llvm::getOrEnforceKnownAlignment(Value *V, MaybeAlign PrefAlign,
1550                                        const DataLayout &DL,
1551                                        const Instruction *CxtI,
1552                                        AssumptionCache *AC,
1553                                        const DominatorTree *DT) {
1554   assert(V->getType()->isPointerTy() &&
1555          "getOrEnforceKnownAlignment expects a pointer!");
1556 
1557   KnownBits Known = computeKnownBits(V, DL, 0, AC, CxtI, DT);
1558   unsigned TrailZ = Known.countMinTrailingZeros();
1559 
1560   // Avoid trouble with ridiculously large TrailZ values, such as
1561   // those computed from a null pointer.
1562   // LLVM doesn't support alignments larger than (1 << MaxAlignmentExponent).
1563   TrailZ = std::min(TrailZ, +Value::MaxAlignmentExponent);
1564 
1565   Align Alignment = Align(1ull << std::min(Known.getBitWidth() - 1, TrailZ));
1566 
1567   if (PrefAlign && *PrefAlign > Alignment)
1568     Alignment = std::max(Alignment, tryEnforceAlignment(V, *PrefAlign, DL));
1569 
1570   // We don't need to make any adjustment.
1571   return Alignment;
1572 }
1573 
1574 ///===---------------------------------------------------------------------===//
1575 ///  Dbg Intrinsic utilities
1576 ///
1577 
1578 /// See if there is a dbg.value intrinsic for DIVar for the PHI node.
1579 static bool PhiHasDebugValue(DILocalVariable *DIVar,
1580                              DIExpression *DIExpr,
1581                              PHINode *APN) {
1582   // Since we can't guarantee that the original dbg.declare intrinsic
1583   // is removed by LowerDbgDeclare(), we need to make sure that we are
1584   // not inserting the same dbg.value intrinsic over and over.
1585   SmallVector<DbgValueInst *, 1> DbgValues;
1586   SmallVector<DbgVariableRecord *, 1> DbgVariableRecords;
1587   findDbgValues(DbgValues, APN, &DbgVariableRecords);
1588   for (auto *DVI : DbgValues) {
1589     assert(is_contained(DVI->getValues(), APN));
1590     if ((DVI->getVariable() == DIVar) && (DVI->getExpression() == DIExpr))
1591       return true;
1592   }
1593   for (auto *DVR : DbgVariableRecords) {
1594     assert(is_contained(DVR->location_ops(), APN));
1595     if ((DVR->getVariable() == DIVar) && (DVR->getExpression() == DIExpr))
1596       return true;
1597   }
1598   return false;
1599 }
1600 
1601 /// Check if the alloc size of \p ValTy is large enough to cover the variable
1602 /// (or fragment of the variable) described by \p DII.
1603 ///
1604 /// This is primarily intended as a helper for the different
1605 /// ConvertDebugDeclareToDebugValue functions. The dbg.declare that is converted
1606 /// describes an alloca'd variable, so we need to use the alloc size of the
1607 /// value when doing the comparison. E.g. an i1 value will be identified as
1608 /// covering an n-bit fragment, if the store size of i1 is at least n bits.
1609 static bool valueCoversEntireFragment(Type *ValTy, DbgVariableIntrinsic *DII) {
1610   const DataLayout &DL = DII->getDataLayout();
1611   TypeSize ValueSize = DL.getTypeAllocSizeInBits(ValTy);
1612   if (std::optional<uint64_t> FragmentSize =
1613           DII->getExpression()->getActiveBits(DII->getVariable()))
1614     return TypeSize::isKnownGE(ValueSize, TypeSize::getFixed(*FragmentSize));
1615 
1616   // We can't always calculate the size of the DI variable (e.g. if it is a
1617   // VLA). Try to use the size of the alloca that the dbg intrinsic describes
1618   // intead.
1619   if (DII->isAddressOfVariable()) {
1620     // DII should have exactly 1 location when it is an address.
1621     assert(DII->getNumVariableLocationOps() == 1 &&
1622            "address of variable must have exactly 1 location operand.");
1623     if (auto *AI =
1624             dyn_cast_or_null<AllocaInst>(DII->getVariableLocationOp(0))) {
1625       if (std::optional<TypeSize> FragmentSize =
1626               AI->getAllocationSizeInBits(DL)) {
1627         return TypeSize::isKnownGE(ValueSize, *FragmentSize);
1628       }
1629     }
1630   }
1631   // Could not determine size of variable. Conservatively return false.
1632   return false;
1633 }
1634 // RemoveDIs: duplicate implementation of the above, using DbgVariableRecords,
1635 // the replacement for dbg.values.
1636 static bool valueCoversEntireFragment(Type *ValTy, DbgVariableRecord *DVR) {
1637   const DataLayout &DL = DVR->getModule()->getDataLayout();
1638   TypeSize ValueSize = DL.getTypeAllocSizeInBits(ValTy);
1639   if (std::optional<uint64_t> FragmentSize =
1640           DVR->getExpression()->getActiveBits(DVR->getVariable()))
1641     return TypeSize::isKnownGE(ValueSize, TypeSize::getFixed(*FragmentSize));
1642 
1643   // We can't always calculate the size of the DI variable (e.g. if it is a
1644   // VLA). Try to use the size of the alloca that the dbg intrinsic describes
1645   // intead.
1646   if (DVR->isAddressOfVariable()) {
1647     // DVR should have exactly 1 location when it is an address.
1648     assert(DVR->getNumVariableLocationOps() == 1 &&
1649            "address of variable must have exactly 1 location operand.");
1650     if (auto *AI =
1651             dyn_cast_or_null<AllocaInst>(DVR->getVariableLocationOp(0))) {
1652       if (std::optional<TypeSize> FragmentSize = AI->getAllocationSizeInBits(DL)) {
1653         return TypeSize::isKnownGE(ValueSize, *FragmentSize);
1654       }
1655     }
1656   }
1657   // Could not determine size of variable. Conservatively return false.
1658   return false;
1659 }
1660 
1661 static void insertDbgValueOrDbgVariableRecord(DIBuilder &Builder, Value *DV,
1662                                               DILocalVariable *DIVar,
1663                                               DIExpression *DIExpr,
1664                                               const DebugLoc &NewLoc,
1665                                               BasicBlock::iterator Instr) {
1666   if (!UseNewDbgInfoFormat) {
1667     auto DbgVal = Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, NewLoc,
1668                                                   (Instruction *)nullptr);
1669     DbgVal.get<Instruction *>()->insertBefore(Instr);
1670   } else {
1671     // RemoveDIs: if we're using the new debug-info format, allocate a
1672     // DbgVariableRecord directly instead of a dbg.value intrinsic.
1673     ValueAsMetadata *DVAM = ValueAsMetadata::get(DV);
1674     DbgVariableRecord *DV =
1675         new DbgVariableRecord(DVAM, DIVar, DIExpr, NewLoc.get());
1676     Instr->getParent()->insertDbgRecordBefore(DV, Instr);
1677   }
1678 }
1679 
1680 static void insertDbgValueOrDbgVariableRecordAfter(
1681     DIBuilder &Builder, Value *DV, DILocalVariable *DIVar, DIExpression *DIExpr,
1682     const DebugLoc &NewLoc, BasicBlock::iterator Instr) {
1683   if (!UseNewDbgInfoFormat) {
1684     auto DbgVal = Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, NewLoc,
1685                                                   (Instruction *)nullptr);
1686     DbgVal.get<Instruction *>()->insertAfter(&*Instr);
1687   } else {
1688     // RemoveDIs: if we're using the new debug-info format, allocate a
1689     // DbgVariableRecord directly instead of a dbg.value intrinsic.
1690     ValueAsMetadata *DVAM = ValueAsMetadata::get(DV);
1691     DbgVariableRecord *DV =
1692         new DbgVariableRecord(DVAM, DIVar, DIExpr, NewLoc.get());
1693     Instr->getParent()->insertDbgRecordAfter(DV, &*Instr);
1694   }
1695 }
1696 
1697 /// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
1698 /// that has an associated llvm.dbg.declare intrinsic.
1699 void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
1700                                            StoreInst *SI, DIBuilder &Builder) {
1701   assert(DII->isAddressOfVariable() || isa<DbgAssignIntrinsic>(DII));
1702   auto *DIVar = DII->getVariable();
1703   assert(DIVar && "Missing variable");
1704   auto *DIExpr = DII->getExpression();
1705   Value *DV = SI->getValueOperand();
1706 
1707   DebugLoc NewLoc = getDebugValueLoc(DII);
1708 
1709   // If the alloca describes the variable itself, i.e. the expression in the
1710   // dbg.declare doesn't start with a dereference, we can perform the
1711   // conversion if the value covers the entire fragment of DII.
1712   // If the alloca describes the *address* of DIVar, i.e. DIExpr is
1713   // *just* a DW_OP_deref, we use DV as is for the dbg.value.
1714   // We conservatively ignore other dereferences, because the following two are
1715   // not equivalent:
1716   //     dbg.declare(alloca, ..., !Expr(deref, plus_uconstant, 2))
1717   //     dbg.value(DV, ..., !Expr(deref, plus_uconstant, 2))
1718   // The former is adding 2 to the address of the variable, whereas the latter
1719   // is adding 2 to the value of the variable. As such, we insist on just a
1720   // deref expression.
1721   bool CanConvert =
1722       DIExpr->isDeref() || (!DIExpr->startsWithDeref() &&
1723                             valueCoversEntireFragment(DV->getType(), DII));
1724   if (CanConvert) {
1725     insertDbgValueOrDbgVariableRecord(Builder, DV, DIVar, DIExpr, NewLoc,
1726                                       SI->getIterator());
1727     return;
1728   }
1729 
1730   // FIXME: If storing to a part of the variable described by the dbg.declare,
1731   // then we want to insert a dbg.value for the corresponding fragment.
1732   LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: " << *DII
1733                     << '\n');
1734   // For now, when there is a store to parts of the variable (but we do not
1735   // know which part) we insert an dbg.value intrinsic to indicate that we
1736   // know nothing about the variable's content.
1737   DV = PoisonValue::get(DV->getType());
1738   insertDbgValueOrDbgVariableRecord(Builder, DV, DIVar, DIExpr, NewLoc,
1739                                     SI->getIterator());
1740 }
1741 
1742 static DIExpression *dropInitialDeref(const DIExpression *DIExpr) {
1743   int NumEltDropped = DIExpr->getElements()[0] == dwarf::DW_OP_LLVM_arg ? 3 : 1;
1744   return DIExpression::get(DIExpr->getContext(),
1745                            DIExpr->getElements().drop_front(NumEltDropped));
1746 }
1747 
1748 void llvm::InsertDebugValueAtStoreLoc(DbgVariableIntrinsic *DII, StoreInst *SI,
1749                                       DIBuilder &Builder) {
1750   auto *DIVar = DII->getVariable();
1751   assert(DIVar && "Missing variable");
1752   auto *DIExpr = DII->getExpression();
1753   DIExpr = dropInitialDeref(DIExpr);
1754   Value *DV = SI->getValueOperand();
1755 
1756   DebugLoc NewLoc = getDebugValueLoc(DII);
1757 
1758   insertDbgValueOrDbgVariableRecord(Builder, DV, DIVar, DIExpr, NewLoc,
1759                                     SI->getIterator());
1760 }
1761 
1762 /// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
1763 /// that has an associated llvm.dbg.declare intrinsic.
1764 void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
1765                                            LoadInst *LI, DIBuilder &Builder) {
1766   auto *DIVar = DII->getVariable();
1767   auto *DIExpr = DII->getExpression();
1768   assert(DIVar && "Missing variable");
1769 
1770   if (!valueCoversEntireFragment(LI->getType(), DII)) {
1771     // FIXME: If only referring to a part of the variable described by the
1772     // dbg.declare, then we want to insert a dbg.value for the corresponding
1773     // fragment.
1774     LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
1775                       << *DII << '\n');
1776     return;
1777   }
1778 
1779   DebugLoc NewLoc = getDebugValueLoc(DII);
1780 
1781   // We are now tracking the loaded value instead of the address. In the
1782   // future if multi-location support is added to the IR, it might be
1783   // preferable to keep tracking both the loaded value and the original
1784   // address in case the alloca can not be elided.
1785   insertDbgValueOrDbgVariableRecordAfter(Builder, LI, DIVar, DIExpr, NewLoc,
1786                                          LI->getIterator());
1787 }
1788 
1789 void llvm::ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR,
1790                                            StoreInst *SI, DIBuilder &Builder) {
1791   assert(DVR->isAddressOfVariable() || DVR->isDbgAssign());
1792   auto *DIVar = DVR->getVariable();
1793   assert(DIVar && "Missing variable");
1794   auto *DIExpr = DVR->getExpression();
1795   Value *DV = SI->getValueOperand();
1796 
1797   DebugLoc NewLoc = getDebugValueLoc(DVR);
1798 
1799   // If the alloca describes the variable itself, i.e. the expression in the
1800   // dbg.declare doesn't start with a dereference, we can perform the
1801   // conversion if the value covers the entire fragment of DII.
1802   // If the alloca describes the *address* of DIVar, i.e. DIExpr is
1803   // *just* a DW_OP_deref, we use DV as is for the dbg.value.
1804   // We conservatively ignore other dereferences, because the following two are
1805   // not equivalent:
1806   //     dbg.declare(alloca, ..., !Expr(deref, plus_uconstant, 2))
1807   //     dbg.value(DV, ..., !Expr(deref, plus_uconstant, 2))
1808   // The former is adding 2 to the address of the variable, whereas the latter
1809   // is adding 2 to the value of the variable. As such, we insist on just a
1810   // deref expression.
1811   bool CanConvert =
1812       DIExpr->isDeref() || (!DIExpr->startsWithDeref() &&
1813                             valueCoversEntireFragment(DV->getType(), DVR));
1814   if (CanConvert) {
1815     insertDbgValueOrDbgVariableRecord(Builder, DV, DIVar, DIExpr, NewLoc,
1816                                       SI->getIterator());
1817     return;
1818   }
1819 
1820   // FIXME: If storing to a part of the variable described by the dbg.declare,
1821   // then we want to insert a dbg.value for the corresponding fragment.
1822   LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: " << *DVR
1823                     << '\n');
1824   assert(UseNewDbgInfoFormat);
1825 
1826   // For now, when there is a store to parts of the variable (but we do not
1827   // know which part) we insert an dbg.value intrinsic to indicate that we
1828   // know nothing about the variable's content.
1829   DV = PoisonValue::get(DV->getType());
1830   ValueAsMetadata *DVAM = ValueAsMetadata::get(DV);
1831   DbgVariableRecord *NewDVR =
1832       new DbgVariableRecord(DVAM, DIVar, DIExpr, NewLoc.get());
1833   SI->getParent()->insertDbgRecordBefore(NewDVR, SI->getIterator());
1834 }
1835 
1836 void llvm::InsertDebugValueAtStoreLoc(DbgVariableRecord *DVR, StoreInst *SI,
1837                                       DIBuilder &Builder) {
1838   auto *DIVar = DVR->getVariable();
1839   assert(DIVar && "Missing variable");
1840   auto *DIExpr = DVR->getExpression();
1841   DIExpr = dropInitialDeref(DIExpr);
1842   Value *DV = SI->getValueOperand();
1843 
1844   DebugLoc NewLoc = getDebugValueLoc(DVR);
1845 
1846   insertDbgValueOrDbgVariableRecord(Builder, DV, DIVar, DIExpr, NewLoc,
1847                                     SI->getIterator());
1848 }
1849 
1850 /// Inserts a llvm.dbg.value intrinsic after a phi that has an associated
1851 /// llvm.dbg.declare intrinsic.
1852 void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
1853                                            PHINode *APN, DIBuilder &Builder) {
1854   auto *DIVar = DII->getVariable();
1855   auto *DIExpr = DII->getExpression();
1856   assert(DIVar && "Missing variable");
1857 
1858   if (PhiHasDebugValue(DIVar, DIExpr, APN))
1859     return;
1860 
1861   if (!valueCoversEntireFragment(APN->getType(), DII)) {
1862     // FIXME: If only referring to a part of the variable described by the
1863     // dbg.declare, then we want to insert a dbg.value for the corresponding
1864     // fragment.
1865     LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
1866                       << *DII << '\n');
1867     return;
1868   }
1869 
1870   BasicBlock *BB = APN->getParent();
1871   auto InsertionPt = BB->getFirstInsertionPt();
1872 
1873   DebugLoc NewLoc = getDebugValueLoc(DII);
1874 
1875   // The block may be a catchswitch block, which does not have a valid
1876   // insertion point.
1877   // FIXME: Insert dbg.value markers in the successors when appropriate.
1878   if (InsertionPt != BB->end()) {
1879     insertDbgValueOrDbgVariableRecord(Builder, APN, DIVar, DIExpr, NewLoc,
1880                                       InsertionPt);
1881   }
1882 }
1883 
1884 void llvm::ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR, LoadInst *LI,
1885                                            DIBuilder &Builder) {
1886   auto *DIVar = DVR->getVariable();
1887   auto *DIExpr = DVR->getExpression();
1888   assert(DIVar && "Missing variable");
1889 
1890   if (!valueCoversEntireFragment(LI->getType(), DVR)) {
1891     // FIXME: If only referring to a part of the variable described by the
1892     // dbg.declare, then we want to insert a DbgVariableRecord for the
1893     // corresponding fragment.
1894     LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to DbgVariableRecord: "
1895                       << *DVR << '\n');
1896     return;
1897   }
1898 
1899   DebugLoc NewLoc = getDebugValueLoc(DVR);
1900 
1901   // We are now tracking the loaded value instead of the address. In the
1902   // future if multi-location support is added to the IR, it might be
1903   // preferable to keep tracking both the loaded value and the original
1904   // address in case the alloca can not be elided.
1905   assert(UseNewDbgInfoFormat);
1906 
1907   // Create a DbgVariableRecord directly and insert.
1908   ValueAsMetadata *LIVAM = ValueAsMetadata::get(LI);
1909   DbgVariableRecord *DV =
1910       new DbgVariableRecord(LIVAM, DIVar, DIExpr, NewLoc.get());
1911   LI->getParent()->insertDbgRecordAfter(DV, LI);
1912 }
1913 
1914 /// Determine whether this alloca is either a VLA or an array.
1915 static bool isArray(AllocaInst *AI) {
1916   return AI->isArrayAllocation() ||
1917          (AI->getAllocatedType() && AI->getAllocatedType()->isArrayTy());
1918 }
1919 
1920 /// Determine whether this alloca is a structure.
1921 static bool isStructure(AllocaInst *AI) {
1922   return AI->getAllocatedType() && AI->getAllocatedType()->isStructTy();
1923 }
1924 void llvm::ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR, PHINode *APN,
1925                                            DIBuilder &Builder) {
1926   auto *DIVar = DVR->getVariable();
1927   auto *DIExpr = DVR->getExpression();
1928   assert(DIVar && "Missing variable");
1929 
1930   if (PhiHasDebugValue(DIVar, DIExpr, APN))
1931     return;
1932 
1933   if (!valueCoversEntireFragment(APN->getType(), DVR)) {
1934     // FIXME: If only referring to a part of the variable described by the
1935     // dbg.declare, then we want to insert a DbgVariableRecord for the
1936     // corresponding fragment.
1937     LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to DbgVariableRecord: "
1938                       << *DVR << '\n');
1939     return;
1940   }
1941 
1942   BasicBlock *BB = APN->getParent();
1943   auto InsertionPt = BB->getFirstInsertionPt();
1944 
1945   DebugLoc NewLoc = getDebugValueLoc(DVR);
1946 
1947   // The block may be a catchswitch block, which does not have a valid
1948   // insertion point.
1949   // FIXME: Insert DbgVariableRecord markers in the successors when appropriate.
1950   if (InsertionPt != BB->end()) {
1951     insertDbgValueOrDbgVariableRecord(Builder, APN, DIVar, DIExpr, NewLoc,
1952                                       InsertionPt);
1953   }
1954 }
1955 
1956 /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
1957 /// of llvm.dbg.value intrinsics.
1958 bool llvm::LowerDbgDeclare(Function &F) {
1959   bool Changed = false;
1960   DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
1961   SmallVector<DbgDeclareInst *, 4> Dbgs;
1962   SmallVector<DbgVariableRecord *> DVRs;
1963   for (auto &FI : F) {
1964     for (Instruction &BI : FI) {
1965       if (auto *DDI = dyn_cast<DbgDeclareInst>(&BI))
1966         Dbgs.push_back(DDI);
1967       for (DbgVariableRecord &DVR : filterDbgVars(BI.getDbgRecordRange())) {
1968         if (DVR.getType() == DbgVariableRecord::LocationType::Declare)
1969           DVRs.push_back(&DVR);
1970       }
1971     }
1972   }
1973 
1974   if (Dbgs.empty() && DVRs.empty())
1975     return Changed;
1976 
1977   auto LowerOne = [&](auto *DDI) {
1978     AllocaInst *AI =
1979         dyn_cast_or_null<AllocaInst>(DDI->getVariableLocationOp(0));
1980     // If this is an alloca for a scalar variable, insert a dbg.value
1981     // at each load and store to the alloca and erase the dbg.declare.
1982     // The dbg.values allow tracking a variable even if it is not
1983     // stored on the stack, while the dbg.declare can only describe
1984     // the stack slot (and at a lexical-scope granularity). Later
1985     // passes will attempt to elide the stack slot.
1986     if (!AI || isArray(AI) || isStructure(AI))
1987       return;
1988 
1989     // A volatile load/store means that the alloca can't be elided anyway.
1990     if (llvm::any_of(AI->users(), [](User *U) -> bool {
1991           if (LoadInst *LI = dyn_cast<LoadInst>(U))
1992             return LI->isVolatile();
1993           if (StoreInst *SI = dyn_cast<StoreInst>(U))
1994             return SI->isVolatile();
1995           return false;
1996         }))
1997       return;
1998 
1999     SmallVector<const Value *, 8> WorkList;
2000     WorkList.push_back(AI);
2001     while (!WorkList.empty()) {
2002       const Value *V = WorkList.pop_back_val();
2003       for (const auto &AIUse : V->uses()) {
2004         User *U = AIUse.getUser();
2005         if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
2006           if (AIUse.getOperandNo() == 1)
2007             ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
2008         } else if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
2009           ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
2010         } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
2011           // This is a call by-value or some other instruction that takes a
2012           // pointer to the variable. Insert a *value* intrinsic that describes
2013           // the variable by dereferencing the alloca.
2014           if (!CI->isLifetimeStartOrEnd()) {
2015             DebugLoc NewLoc = getDebugValueLoc(DDI);
2016             auto *DerefExpr =
2017                 DIExpression::append(DDI->getExpression(), dwarf::DW_OP_deref);
2018             insertDbgValueOrDbgVariableRecord(DIB, AI, DDI->getVariable(),
2019                                               DerefExpr, NewLoc,
2020                                               CI->getIterator());
2021           }
2022         } else if (BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
2023           if (BI->getType()->isPointerTy())
2024             WorkList.push_back(BI);
2025         }
2026       }
2027     }
2028     DDI->eraseFromParent();
2029     Changed = true;
2030   };
2031 
2032   for_each(Dbgs, LowerOne);
2033   for_each(DVRs, LowerOne);
2034 
2035   if (Changed)
2036     for (BasicBlock &BB : F)
2037       RemoveRedundantDbgInstrs(&BB);
2038 
2039   return Changed;
2040 }
2041 
2042 // RemoveDIs: re-implementation of insertDebugValuesForPHIs, but which pulls the
2043 // debug-info out of the block's DbgVariableRecords rather than dbg.value
2044 // intrinsics.
2045 static void
2046 insertDbgVariableRecordsForPHIs(BasicBlock *BB,
2047                                 SmallVectorImpl<PHINode *> &InsertedPHIs) {
2048   assert(BB && "No BasicBlock to clone DbgVariableRecord(s) from.");
2049   if (InsertedPHIs.size() == 0)
2050     return;
2051 
2052   // Map existing PHI nodes to their DbgVariableRecords.
2053   DenseMap<Value *, DbgVariableRecord *> DbgValueMap;
2054   for (auto &I : *BB) {
2055     for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {
2056       for (Value *V : DVR.location_ops())
2057         if (auto *Loc = dyn_cast_or_null<PHINode>(V))
2058           DbgValueMap.insert({Loc, &DVR});
2059     }
2060   }
2061   if (DbgValueMap.size() == 0)
2062     return;
2063 
2064   // Map a pair of the destination BB and old DbgVariableRecord to the new
2065   // DbgVariableRecord, so that if a DbgVariableRecord is being rewritten to use
2066   // more than one of the inserted PHIs in the same destination BB, we can
2067   // update the same DbgVariableRecord with all the new PHIs instead of creating
2068   // one copy for each.
2069   MapVector<std::pair<BasicBlock *, DbgVariableRecord *>, DbgVariableRecord *>
2070       NewDbgValueMap;
2071   // Then iterate through the new PHIs and look to see if they use one of the
2072   // previously mapped PHIs. If so, create a new DbgVariableRecord that will
2073   // propagate the info through the new PHI. If we use more than one new PHI in
2074   // a single destination BB with the same old dbg.value, merge the updates so
2075   // that we get a single new DbgVariableRecord with all the new PHIs.
2076   for (auto PHI : InsertedPHIs) {
2077     BasicBlock *Parent = PHI->getParent();
2078     // Avoid inserting a debug-info record into an EH block.
2079     if (Parent->getFirstNonPHI()->isEHPad())
2080       continue;
2081     for (auto VI : PHI->operand_values()) {
2082       auto V = DbgValueMap.find(VI);
2083       if (V != DbgValueMap.end()) {
2084         DbgVariableRecord *DbgII = cast<DbgVariableRecord>(V->second);
2085         auto NewDI = NewDbgValueMap.find({Parent, DbgII});
2086         if (NewDI == NewDbgValueMap.end()) {
2087           DbgVariableRecord *NewDbgII = DbgII->clone();
2088           NewDI = NewDbgValueMap.insert({{Parent, DbgII}, NewDbgII}).first;
2089         }
2090         DbgVariableRecord *NewDbgII = NewDI->second;
2091         // If PHI contains VI as an operand more than once, we may
2092         // replaced it in NewDbgII; confirm that it is present.
2093         if (is_contained(NewDbgII->location_ops(), VI))
2094           NewDbgII->replaceVariableLocationOp(VI, PHI);
2095       }
2096     }
2097   }
2098   // Insert the new DbgVariableRecords into their destination blocks.
2099   for (auto DI : NewDbgValueMap) {
2100     BasicBlock *Parent = DI.first.first;
2101     DbgVariableRecord *NewDbgII = DI.second;
2102     auto InsertionPt = Parent->getFirstInsertionPt();
2103     assert(InsertionPt != Parent->end() && "Ill-formed basic block");
2104 
2105     Parent->insertDbgRecordBefore(NewDbgII, InsertionPt);
2106   }
2107 }
2108 
2109 /// Propagate dbg.value intrinsics through the newly inserted PHIs.
2110 void llvm::insertDebugValuesForPHIs(BasicBlock *BB,
2111                                     SmallVectorImpl<PHINode *> &InsertedPHIs) {
2112   assert(BB && "No BasicBlock to clone dbg.value(s) from.");
2113   if (InsertedPHIs.size() == 0)
2114     return;
2115 
2116   insertDbgVariableRecordsForPHIs(BB, InsertedPHIs);
2117 
2118   // Map existing PHI nodes to their dbg.values.
2119   ValueToValueMapTy DbgValueMap;
2120   for (auto &I : *BB) {
2121     if (auto DbgII = dyn_cast<DbgVariableIntrinsic>(&I)) {
2122       for (Value *V : DbgII->location_ops())
2123         if (auto *Loc = dyn_cast_or_null<PHINode>(V))
2124           DbgValueMap.insert({Loc, DbgII});
2125     }
2126   }
2127   if (DbgValueMap.size() == 0)
2128     return;
2129 
2130   // Map a pair of the destination BB and old dbg.value to the new dbg.value,
2131   // so that if a dbg.value is being rewritten to use more than one of the
2132   // inserted PHIs in the same destination BB, we can update the same dbg.value
2133   // with all the new PHIs instead of creating one copy for each.
2134   MapVector<std::pair<BasicBlock *, DbgVariableIntrinsic *>,
2135             DbgVariableIntrinsic *>
2136       NewDbgValueMap;
2137   // Then iterate through the new PHIs and look to see if they use one of the
2138   // previously mapped PHIs. If so, create a new dbg.value intrinsic that will
2139   // propagate the info through the new PHI. If we use more than one new PHI in
2140   // a single destination BB with the same old dbg.value, merge the updates so
2141   // that we get a single new dbg.value with all the new PHIs.
2142   for (auto *PHI : InsertedPHIs) {
2143     BasicBlock *Parent = PHI->getParent();
2144     // Avoid inserting an intrinsic into an EH block.
2145     if (Parent->getFirstNonPHI()->isEHPad())
2146       continue;
2147     for (auto *VI : PHI->operand_values()) {
2148       auto V = DbgValueMap.find(VI);
2149       if (V != DbgValueMap.end()) {
2150         auto *DbgII = cast<DbgVariableIntrinsic>(V->second);
2151         auto NewDI = NewDbgValueMap.find({Parent, DbgII});
2152         if (NewDI == NewDbgValueMap.end()) {
2153           auto *NewDbgII = cast<DbgVariableIntrinsic>(DbgII->clone());
2154           NewDI = NewDbgValueMap.insert({{Parent, DbgII}, NewDbgII}).first;
2155         }
2156         DbgVariableIntrinsic *NewDbgII = NewDI->second;
2157         // If PHI contains VI as an operand more than once, we may
2158         // replaced it in NewDbgII; confirm that it is present.
2159         if (is_contained(NewDbgII->location_ops(), VI))
2160           NewDbgII->replaceVariableLocationOp(VI, PHI);
2161       }
2162     }
2163   }
2164   // Insert thew new dbg.values into their destination blocks.
2165   for (auto DI : NewDbgValueMap) {
2166     BasicBlock *Parent = DI.first.first;
2167     auto *NewDbgII = DI.second;
2168     auto InsertionPt = Parent->getFirstInsertionPt();
2169     assert(InsertionPt != Parent->end() && "Ill-formed basic block");
2170     NewDbgII->insertBefore(&*InsertionPt);
2171   }
2172 }
2173 
2174 bool llvm::replaceDbgDeclare(Value *Address, Value *NewAddress,
2175                              DIBuilder &Builder, uint8_t DIExprFlags,
2176                              int Offset) {
2177   TinyPtrVector<DbgDeclareInst *> DbgDeclares = findDbgDeclares(Address);
2178   TinyPtrVector<DbgVariableRecord *> DVRDeclares = findDVRDeclares(Address);
2179 
2180   auto ReplaceOne = [&](auto *DII) {
2181     assert(DII->getVariable() && "Missing variable");
2182     auto *DIExpr = DII->getExpression();
2183     DIExpr = DIExpression::prepend(DIExpr, DIExprFlags, Offset);
2184     DII->setExpression(DIExpr);
2185     DII->replaceVariableLocationOp(Address, NewAddress);
2186   };
2187 
2188   for_each(DbgDeclares, ReplaceOne);
2189   for_each(DVRDeclares, ReplaceOne);
2190 
2191   return !DbgDeclares.empty() || !DVRDeclares.empty();
2192 }
2193 
2194 static void updateOneDbgValueForAlloca(const DebugLoc &Loc,
2195                                        DILocalVariable *DIVar,
2196                                        DIExpression *DIExpr, Value *NewAddress,
2197                                        DbgValueInst *DVI,
2198                                        DbgVariableRecord *DVR,
2199                                        DIBuilder &Builder, int Offset) {
2200   assert(DIVar && "Missing variable");
2201 
2202   // This is an alloca-based dbg.value/DbgVariableRecord. The first thing it
2203   // should do with the alloca pointer is dereference it. Otherwise we don't
2204   // know how to handle it and give up.
2205   if (!DIExpr || DIExpr->getNumElements() < 1 ||
2206       DIExpr->getElement(0) != dwarf::DW_OP_deref)
2207     return;
2208 
2209   // Insert the offset before the first deref.
2210   if (Offset)
2211     DIExpr = DIExpression::prepend(DIExpr, 0, Offset);
2212 
2213   if (DVI) {
2214     DVI->setExpression(DIExpr);
2215     DVI->replaceVariableLocationOp(0u, NewAddress);
2216   } else {
2217     assert(DVR);
2218     DVR->setExpression(DIExpr);
2219     DVR->replaceVariableLocationOp(0u, NewAddress);
2220   }
2221 }
2222 
2223 void llvm::replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
2224                                     DIBuilder &Builder, int Offset) {
2225   SmallVector<DbgValueInst *, 1> DbgUsers;
2226   SmallVector<DbgVariableRecord *, 1> DPUsers;
2227   findDbgValues(DbgUsers, AI, &DPUsers);
2228 
2229   // Attempt to replace dbg.values that use this alloca.
2230   for (auto *DVI : DbgUsers)
2231     updateOneDbgValueForAlloca(DVI->getDebugLoc(), DVI->getVariable(),
2232                                DVI->getExpression(), NewAllocaAddress, DVI,
2233                                nullptr, Builder, Offset);
2234 
2235   // Replace any DbgVariableRecords that use this alloca.
2236   for (DbgVariableRecord *DVR : DPUsers)
2237     updateOneDbgValueForAlloca(DVR->getDebugLoc(), DVR->getVariable(),
2238                                DVR->getExpression(), NewAllocaAddress, nullptr,
2239                                DVR, Builder, Offset);
2240 }
2241 
2242 /// Where possible to salvage debug information for \p I do so.
2243 /// If not possible mark undef.
2244 void llvm::salvageDebugInfo(Instruction &I) {
2245   SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
2246   SmallVector<DbgVariableRecord *, 1> DPUsers;
2247   findDbgUsers(DbgUsers, &I, &DPUsers);
2248   salvageDebugInfoForDbgValues(I, DbgUsers, DPUsers);
2249 }
2250 
2251 template <typename T> static void salvageDbgAssignAddress(T *Assign) {
2252   Instruction *I = dyn_cast<Instruction>(Assign->getAddress());
2253   // Only instructions can be salvaged at the moment.
2254   if (!I)
2255     return;
2256 
2257   assert(!Assign->getAddressExpression()->getFragmentInfo().has_value() &&
2258          "address-expression shouldn't have fragment info");
2259 
2260   // The address component of a dbg.assign cannot be variadic.
2261   uint64_t CurrentLocOps = 0;
2262   SmallVector<Value *, 4> AdditionalValues;
2263   SmallVector<uint64_t, 16> Ops;
2264   Value *NewV = salvageDebugInfoImpl(*I, CurrentLocOps, Ops, AdditionalValues);
2265 
2266   // Check if the salvage failed.
2267   if (!NewV)
2268     return;
2269 
2270   DIExpression *SalvagedExpr = DIExpression::appendOpsToArg(
2271       Assign->getAddressExpression(), Ops, 0, /*StackValue=*/false);
2272   assert(!SalvagedExpr->getFragmentInfo().has_value() &&
2273          "address-expression shouldn't have fragment info");
2274 
2275   SalvagedExpr = SalvagedExpr->foldConstantMath();
2276 
2277   // Salvage succeeds if no additional values are required.
2278   if (AdditionalValues.empty()) {
2279     Assign->setAddress(NewV);
2280     Assign->setAddressExpression(SalvagedExpr);
2281   } else {
2282     Assign->setKillAddress();
2283   }
2284 }
2285 
2286 void llvm::salvageDebugInfoForDbgValues(
2287     Instruction &I, ArrayRef<DbgVariableIntrinsic *> DbgUsers,
2288     ArrayRef<DbgVariableRecord *> DPUsers) {
2289   // These are arbitrary chosen limits on the maximum number of values and the
2290   // maximum size of a debug expression we can salvage up to, used for
2291   // performance reasons.
2292   const unsigned MaxDebugArgs = 16;
2293   const unsigned MaxExpressionSize = 128;
2294   bool Salvaged = false;
2295 
2296   for (auto *DII : DbgUsers) {
2297     if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(DII)) {
2298       if (DAI->getAddress() == &I) {
2299         salvageDbgAssignAddress(DAI);
2300         Salvaged = true;
2301       }
2302       if (DAI->getValue() != &I)
2303         continue;
2304     }
2305 
2306     // Do not add DW_OP_stack_value for DbgDeclare, because they are implicitly
2307     // pointing out the value as a DWARF memory location description.
2308     bool StackValue = isa<DbgValueInst>(DII);
2309     auto DIILocation = DII->location_ops();
2310     assert(
2311         is_contained(DIILocation, &I) &&
2312         "DbgVariableIntrinsic must use salvaged instruction as its location");
2313     SmallVector<Value *, 4> AdditionalValues;
2314     // `I` may appear more than once in DII's location ops, and each use of `I`
2315     // must be updated in the DIExpression and potentially have additional
2316     // values added; thus we call salvageDebugInfoImpl for each `I` instance in
2317     // DIILocation.
2318     Value *Op0 = nullptr;
2319     DIExpression *SalvagedExpr = DII->getExpression();
2320     auto LocItr = find(DIILocation, &I);
2321     while (SalvagedExpr && LocItr != DIILocation.end()) {
2322       SmallVector<uint64_t, 16> Ops;
2323       unsigned LocNo = std::distance(DIILocation.begin(), LocItr);
2324       uint64_t CurrentLocOps = SalvagedExpr->getNumLocationOperands();
2325       Op0 = salvageDebugInfoImpl(I, CurrentLocOps, Ops, AdditionalValues);
2326       if (!Op0)
2327         break;
2328       SalvagedExpr =
2329           DIExpression::appendOpsToArg(SalvagedExpr, Ops, LocNo, StackValue);
2330       LocItr = std::find(++LocItr, DIILocation.end(), &I);
2331     }
2332     // salvageDebugInfoImpl should fail on examining the first element of
2333     // DbgUsers, or none of them.
2334     if (!Op0)
2335       break;
2336 
2337     SalvagedExpr = SalvagedExpr->foldConstantMath();
2338     DII->replaceVariableLocationOp(&I, Op0);
2339     bool IsValidSalvageExpr = SalvagedExpr->getNumElements() <= MaxExpressionSize;
2340     if (AdditionalValues.empty() && IsValidSalvageExpr) {
2341       DII->setExpression(SalvagedExpr);
2342     } else if (isa<DbgValueInst>(DII) && IsValidSalvageExpr &&
2343                DII->getNumVariableLocationOps() + AdditionalValues.size() <=
2344                    MaxDebugArgs) {
2345       DII->addVariableLocationOps(AdditionalValues, SalvagedExpr);
2346     } else {
2347       // Do not salvage using DIArgList for dbg.declare, as it is not currently
2348       // supported in those instructions. Also do not salvage if the resulting
2349       // DIArgList would contain an unreasonably large number of values.
2350       DII->setKillLocation();
2351     }
2352     LLVM_DEBUG(dbgs() << "SALVAGE: " << *DII << '\n');
2353     Salvaged = true;
2354   }
2355   // Duplicate of above block for DbgVariableRecords.
2356   for (auto *DVR : DPUsers) {
2357     if (DVR->isDbgAssign()) {
2358       if (DVR->getAddress() == &I) {
2359         salvageDbgAssignAddress(DVR);
2360         Salvaged = true;
2361       }
2362       if (DVR->getValue() != &I)
2363         continue;
2364     }
2365 
2366     // Do not add DW_OP_stack_value for DbgDeclare and DbgAddr, because they
2367     // are implicitly pointing out the value as a DWARF memory location
2368     // description.
2369     bool StackValue =
2370         DVR->getType() != DbgVariableRecord::LocationType::Declare;
2371     auto DVRLocation = DVR->location_ops();
2372     assert(
2373         is_contained(DVRLocation, &I) &&
2374         "DbgVariableIntrinsic must use salvaged instruction as its location");
2375     SmallVector<Value *, 4> AdditionalValues;
2376     // 'I' may appear more than once in DVR's location ops, and each use of 'I'
2377     // must be updated in the DIExpression and potentially have additional
2378     // values added; thus we call salvageDebugInfoImpl for each 'I' instance in
2379     // DVRLocation.
2380     Value *Op0 = nullptr;
2381     DIExpression *SalvagedExpr = DVR->getExpression();
2382     auto LocItr = find(DVRLocation, &I);
2383     while (SalvagedExpr && LocItr != DVRLocation.end()) {
2384       SmallVector<uint64_t, 16> Ops;
2385       unsigned LocNo = std::distance(DVRLocation.begin(), LocItr);
2386       uint64_t CurrentLocOps = SalvagedExpr->getNumLocationOperands();
2387       Op0 = salvageDebugInfoImpl(I, CurrentLocOps, Ops, AdditionalValues);
2388       if (!Op0)
2389         break;
2390       SalvagedExpr =
2391           DIExpression::appendOpsToArg(SalvagedExpr, Ops, LocNo, StackValue);
2392       LocItr = std::find(++LocItr, DVRLocation.end(), &I);
2393     }
2394     // salvageDebugInfoImpl should fail on examining the first element of
2395     // DbgUsers, or none of them.
2396     if (!Op0)
2397       break;
2398 
2399     SalvagedExpr = SalvagedExpr->foldConstantMath();
2400     DVR->replaceVariableLocationOp(&I, Op0);
2401     bool IsValidSalvageExpr =
2402         SalvagedExpr->getNumElements() <= MaxExpressionSize;
2403     if (AdditionalValues.empty() && IsValidSalvageExpr) {
2404       DVR->setExpression(SalvagedExpr);
2405     } else if (DVR->getType() != DbgVariableRecord::LocationType::Declare &&
2406                IsValidSalvageExpr &&
2407                DVR->getNumVariableLocationOps() + AdditionalValues.size() <=
2408                    MaxDebugArgs) {
2409       DVR->addVariableLocationOps(AdditionalValues, SalvagedExpr);
2410     } else {
2411       // Do not salvage using DIArgList for dbg.addr/dbg.declare, as it is
2412       // currently only valid for stack value expressions.
2413       // Also do not salvage if the resulting DIArgList would contain an
2414       // unreasonably large number of values.
2415       DVR->setKillLocation();
2416     }
2417     LLVM_DEBUG(dbgs() << "SALVAGE: " << DVR << '\n');
2418     Salvaged = true;
2419   }
2420 
2421   if (Salvaged)
2422     return;
2423 
2424   for (auto *DII : DbgUsers)
2425     DII->setKillLocation();
2426 
2427   for (auto *DVR : DPUsers)
2428     DVR->setKillLocation();
2429 }
2430 
2431 Value *getSalvageOpsForGEP(GetElementPtrInst *GEP, const DataLayout &DL,
2432                            uint64_t CurrentLocOps,
2433                            SmallVectorImpl<uint64_t> &Opcodes,
2434                            SmallVectorImpl<Value *> &AdditionalValues) {
2435   unsigned BitWidth = DL.getIndexSizeInBits(GEP->getPointerAddressSpace());
2436   // Rewrite a GEP into a DIExpression.
2437   MapVector<Value *, APInt> VariableOffsets;
2438   APInt ConstantOffset(BitWidth, 0);
2439   if (!GEP->collectOffset(DL, BitWidth, VariableOffsets, ConstantOffset))
2440     return nullptr;
2441   if (!VariableOffsets.empty() && !CurrentLocOps) {
2442     Opcodes.insert(Opcodes.begin(), {dwarf::DW_OP_LLVM_arg, 0});
2443     CurrentLocOps = 1;
2444   }
2445   for (const auto &Offset : VariableOffsets) {
2446     AdditionalValues.push_back(Offset.first);
2447     assert(Offset.second.isStrictlyPositive() &&
2448            "Expected strictly positive multiplier for offset.");
2449     Opcodes.append({dwarf::DW_OP_LLVM_arg, CurrentLocOps++, dwarf::DW_OP_constu,
2450                     Offset.second.getZExtValue(), dwarf::DW_OP_mul,
2451                     dwarf::DW_OP_plus});
2452   }
2453   DIExpression::appendOffset(Opcodes, ConstantOffset.getSExtValue());
2454   return GEP->getOperand(0);
2455 }
2456 
2457 uint64_t getDwarfOpForBinOp(Instruction::BinaryOps Opcode) {
2458   switch (Opcode) {
2459   case Instruction::Add:
2460     return dwarf::DW_OP_plus;
2461   case Instruction::Sub:
2462     return dwarf::DW_OP_minus;
2463   case Instruction::Mul:
2464     return dwarf::DW_OP_mul;
2465   case Instruction::SDiv:
2466     return dwarf::DW_OP_div;
2467   case Instruction::SRem:
2468     return dwarf::DW_OP_mod;
2469   case Instruction::Or:
2470     return dwarf::DW_OP_or;
2471   case Instruction::And:
2472     return dwarf::DW_OP_and;
2473   case Instruction::Xor:
2474     return dwarf::DW_OP_xor;
2475   case Instruction::Shl:
2476     return dwarf::DW_OP_shl;
2477   case Instruction::LShr:
2478     return dwarf::DW_OP_shr;
2479   case Instruction::AShr:
2480     return dwarf::DW_OP_shra;
2481   default:
2482     // TODO: Salvage from each kind of binop we know about.
2483     return 0;
2484   }
2485 }
2486 
2487 static void handleSSAValueOperands(uint64_t CurrentLocOps,
2488                                    SmallVectorImpl<uint64_t> &Opcodes,
2489                                    SmallVectorImpl<Value *> &AdditionalValues,
2490                                    Instruction *I) {
2491   if (!CurrentLocOps) {
2492     Opcodes.append({dwarf::DW_OP_LLVM_arg, 0});
2493     CurrentLocOps = 1;
2494   }
2495   Opcodes.append({dwarf::DW_OP_LLVM_arg, CurrentLocOps});
2496   AdditionalValues.push_back(I->getOperand(1));
2497 }
2498 
2499 Value *getSalvageOpsForBinOp(BinaryOperator *BI, uint64_t CurrentLocOps,
2500                              SmallVectorImpl<uint64_t> &Opcodes,
2501                              SmallVectorImpl<Value *> &AdditionalValues) {
2502   // Handle binary operations with constant integer operands as a special case.
2503   auto *ConstInt = dyn_cast<ConstantInt>(BI->getOperand(1));
2504   // Values wider than 64 bits cannot be represented within a DIExpression.
2505   if (ConstInt && ConstInt->getBitWidth() > 64)
2506     return nullptr;
2507 
2508   Instruction::BinaryOps BinOpcode = BI->getOpcode();
2509   // Push any Constant Int operand onto the expression stack.
2510   if (ConstInt) {
2511     uint64_t Val = ConstInt->getSExtValue();
2512     // Add or Sub Instructions with a constant operand can potentially be
2513     // simplified.
2514     if (BinOpcode == Instruction::Add || BinOpcode == Instruction::Sub) {
2515       uint64_t Offset = BinOpcode == Instruction::Add ? Val : -int64_t(Val);
2516       DIExpression::appendOffset(Opcodes, Offset);
2517       return BI->getOperand(0);
2518     }
2519     Opcodes.append({dwarf::DW_OP_constu, Val});
2520   } else {
2521     handleSSAValueOperands(CurrentLocOps, Opcodes, AdditionalValues, BI);
2522   }
2523 
2524   // Add salvaged binary operator to expression stack, if it has a valid
2525   // representation in a DIExpression.
2526   uint64_t DwarfBinOp = getDwarfOpForBinOp(BinOpcode);
2527   if (!DwarfBinOp)
2528     return nullptr;
2529   Opcodes.push_back(DwarfBinOp);
2530   return BI->getOperand(0);
2531 }
2532 
2533 uint64_t getDwarfOpForIcmpPred(CmpInst::Predicate Pred) {
2534   // The signedness of the operation is implicit in the typed stack, signed and
2535   // unsigned instructions map to the same DWARF opcode.
2536   switch (Pred) {
2537   case CmpInst::ICMP_EQ:
2538     return dwarf::DW_OP_eq;
2539   case CmpInst::ICMP_NE:
2540     return dwarf::DW_OP_ne;
2541   case CmpInst::ICMP_UGT:
2542   case CmpInst::ICMP_SGT:
2543     return dwarf::DW_OP_gt;
2544   case CmpInst::ICMP_UGE:
2545   case CmpInst::ICMP_SGE:
2546     return dwarf::DW_OP_ge;
2547   case CmpInst::ICMP_ULT:
2548   case CmpInst::ICMP_SLT:
2549     return dwarf::DW_OP_lt;
2550   case CmpInst::ICMP_ULE:
2551   case CmpInst::ICMP_SLE:
2552     return dwarf::DW_OP_le;
2553   default:
2554     return 0;
2555   }
2556 }
2557 
2558 Value *getSalvageOpsForIcmpOp(ICmpInst *Icmp, uint64_t CurrentLocOps,
2559                               SmallVectorImpl<uint64_t> &Opcodes,
2560                               SmallVectorImpl<Value *> &AdditionalValues) {
2561   // Handle icmp operations with constant integer operands as a special case.
2562   auto *ConstInt = dyn_cast<ConstantInt>(Icmp->getOperand(1));
2563   // Values wider than 64 bits cannot be represented within a DIExpression.
2564   if (ConstInt && ConstInt->getBitWidth() > 64)
2565     return nullptr;
2566   // Push any Constant Int operand onto the expression stack.
2567   if (ConstInt) {
2568     if (Icmp->isSigned())
2569       Opcodes.push_back(dwarf::DW_OP_consts);
2570     else
2571       Opcodes.push_back(dwarf::DW_OP_constu);
2572     uint64_t Val = ConstInt->getSExtValue();
2573     Opcodes.push_back(Val);
2574   } else {
2575     handleSSAValueOperands(CurrentLocOps, Opcodes, AdditionalValues, Icmp);
2576   }
2577 
2578   // Add salvaged binary operator to expression stack, if it has a valid
2579   // representation in a DIExpression.
2580   uint64_t DwarfIcmpOp = getDwarfOpForIcmpPred(Icmp->getPredicate());
2581   if (!DwarfIcmpOp)
2582     return nullptr;
2583   Opcodes.push_back(DwarfIcmpOp);
2584   return Icmp->getOperand(0);
2585 }
2586 
2587 Value *llvm::salvageDebugInfoImpl(Instruction &I, uint64_t CurrentLocOps,
2588                                   SmallVectorImpl<uint64_t> &Ops,
2589                                   SmallVectorImpl<Value *> &AdditionalValues) {
2590   auto &M = *I.getModule();
2591   auto &DL = M.getDataLayout();
2592 
2593   if (auto *CI = dyn_cast<CastInst>(&I)) {
2594     Value *FromValue = CI->getOperand(0);
2595     // No-op casts are irrelevant for debug info.
2596     if (CI->isNoopCast(DL)) {
2597       return FromValue;
2598     }
2599 
2600     Type *Type = CI->getType();
2601     if (Type->isPointerTy())
2602       Type = DL.getIntPtrType(Type);
2603     // Casts other than Trunc, SExt, or ZExt to scalar types cannot be salvaged.
2604     if (Type->isVectorTy() ||
2605         !(isa<TruncInst>(&I) || isa<SExtInst>(&I) || isa<ZExtInst>(&I) ||
2606           isa<IntToPtrInst>(&I) || isa<PtrToIntInst>(&I)))
2607       return nullptr;
2608 
2609     llvm::Type *FromType = FromValue->getType();
2610     if (FromType->isPointerTy())
2611       FromType = DL.getIntPtrType(FromType);
2612 
2613     unsigned FromTypeBitSize = FromType->getScalarSizeInBits();
2614     unsigned ToTypeBitSize = Type->getScalarSizeInBits();
2615 
2616     auto ExtOps = DIExpression::getExtOps(FromTypeBitSize, ToTypeBitSize,
2617                                           isa<SExtInst>(&I));
2618     Ops.append(ExtOps.begin(), ExtOps.end());
2619     return FromValue;
2620   }
2621 
2622   if (auto *GEP = dyn_cast<GetElementPtrInst>(&I))
2623     return getSalvageOpsForGEP(GEP, DL, CurrentLocOps, Ops, AdditionalValues);
2624   if (auto *BI = dyn_cast<BinaryOperator>(&I))
2625     return getSalvageOpsForBinOp(BI, CurrentLocOps, Ops, AdditionalValues);
2626   if (auto *IC = dyn_cast<ICmpInst>(&I))
2627     return getSalvageOpsForIcmpOp(IC, CurrentLocOps, Ops, AdditionalValues);
2628 
2629   // *Not* to do: we should not attempt to salvage load instructions,
2630   // because the validity and lifetime of a dbg.value containing
2631   // DW_OP_deref becomes difficult to analyze. See PR40628 for examples.
2632   return nullptr;
2633 }
2634 
2635 /// A replacement for a dbg.value expression.
2636 using DbgValReplacement = std::optional<DIExpression *>;
2637 
2638 /// Point debug users of \p From to \p To using exprs given by \p RewriteExpr,
2639 /// possibly moving/undefing users to prevent use-before-def. Returns true if
2640 /// changes are made.
2641 static bool rewriteDebugUsers(
2642     Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT,
2643     function_ref<DbgValReplacement(DbgVariableIntrinsic &DII)> RewriteExpr,
2644     function_ref<DbgValReplacement(DbgVariableRecord &DVR)> RewriteDVRExpr) {
2645   // Find debug users of From.
2646   SmallVector<DbgVariableIntrinsic *, 1> Users;
2647   SmallVector<DbgVariableRecord *, 1> DPUsers;
2648   findDbgUsers(Users, &From, &DPUsers);
2649   if (Users.empty() && DPUsers.empty())
2650     return false;
2651 
2652   // Prevent use-before-def of To.
2653   bool Changed = false;
2654 
2655   SmallPtrSet<DbgVariableIntrinsic *, 1> UndefOrSalvage;
2656   SmallPtrSet<DbgVariableRecord *, 1> UndefOrSalvageDVR;
2657   if (isa<Instruction>(&To)) {
2658     bool DomPointAfterFrom = From.getNextNonDebugInstruction() == &DomPoint;
2659 
2660     for (auto *DII : Users) {
2661       // It's common to see a debug user between From and DomPoint. Move it
2662       // after DomPoint to preserve the variable update without any reordering.
2663       if (DomPointAfterFrom && DII->getNextNonDebugInstruction() == &DomPoint) {
2664         LLVM_DEBUG(dbgs() << "MOVE:  " << *DII << '\n');
2665         DII->moveAfter(&DomPoint);
2666         Changed = true;
2667 
2668       // Users which otherwise aren't dominated by the replacement value must
2669       // be salvaged or deleted.
2670       } else if (!DT.dominates(&DomPoint, DII)) {
2671         UndefOrSalvage.insert(DII);
2672       }
2673     }
2674 
2675     // DbgVariableRecord implementation of the above.
2676     for (auto *DVR : DPUsers) {
2677       Instruction *MarkedInstr = DVR->getMarker()->MarkedInstr;
2678       Instruction *NextNonDebug = MarkedInstr;
2679       // The next instruction might still be a dbg.declare, skip over it.
2680       if (isa<DbgVariableIntrinsic>(NextNonDebug))
2681         NextNonDebug = NextNonDebug->getNextNonDebugInstruction();
2682 
2683       if (DomPointAfterFrom && NextNonDebug == &DomPoint) {
2684         LLVM_DEBUG(dbgs() << "MOVE:  " << *DVR << '\n');
2685         DVR->removeFromParent();
2686         // Ensure there's a marker.
2687         DomPoint.getParent()->insertDbgRecordAfter(DVR, &DomPoint);
2688         Changed = true;
2689       } else if (!DT.dominates(&DomPoint, MarkedInstr)) {
2690         UndefOrSalvageDVR.insert(DVR);
2691       }
2692     }
2693   }
2694 
2695   // Update debug users without use-before-def risk.
2696   for (auto *DII : Users) {
2697     if (UndefOrSalvage.count(DII))
2698       continue;
2699 
2700     DbgValReplacement DVRepl = RewriteExpr(*DII);
2701     if (!DVRepl)
2702       continue;
2703 
2704     DII->replaceVariableLocationOp(&From, &To);
2705     DII->setExpression(*DVRepl);
2706     LLVM_DEBUG(dbgs() << "REWRITE:  " << *DII << '\n');
2707     Changed = true;
2708   }
2709   for (auto *DVR : DPUsers) {
2710     if (UndefOrSalvageDVR.count(DVR))
2711       continue;
2712 
2713     DbgValReplacement DVRepl = RewriteDVRExpr(*DVR);
2714     if (!DVRepl)
2715       continue;
2716 
2717     DVR->replaceVariableLocationOp(&From, &To);
2718     DVR->setExpression(*DVRepl);
2719     LLVM_DEBUG(dbgs() << "REWRITE:  " << DVR << '\n');
2720     Changed = true;
2721   }
2722 
2723   if (!UndefOrSalvage.empty() || !UndefOrSalvageDVR.empty()) {
2724     // Try to salvage the remaining debug users.
2725     salvageDebugInfo(From);
2726     Changed = true;
2727   }
2728 
2729   return Changed;
2730 }
2731 
2732 /// Check if a bitcast between a value of type \p FromTy to type \p ToTy would
2733 /// losslessly preserve the bits and semantics of the value. This predicate is
2734 /// symmetric, i.e swapping \p FromTy and \p ToTy should give the same result.
2735 ///
2736 /// Note that Type::canLosslesslyBitCastTo is not suitable here because it
2737 /// allows semantically unequivalent bitcasts, such as <2 x i64> -> <4 x i32>,
2738 /// and also does not allow lossless pointer <-> integer conversions.
2739 static bool isBitCastSemanticsPreserving(const DataLayout &DL, Type *FromTy,
2740                                          Type *ToTy) {
2741   // Trivially compatible types.
2742   if (FromTy == ToTy)
2743     return true;
2744 
2745   // Handle compatible pointer <-> integer conversions.
2746   if (FromTy->isIntOrPtrTy() && ToTy->isIntOrPtrTy()) {
2747     bool SameSize = DL.getTypeSizeInBits(FromTy) == DL.getTypeSizeInBits(ToTy);
2748     bool LosslessConversion = !DL.isNonIntegralPointerType(FromTy) &&
2749                               !DL.isNonIntegralPointerType(ToTy);
2750     return SameSize && LosslessConversion;
2751   }
2752 
2753   // TODO: This is not exhaustive.
2754   return false;
2755 }
2756 
2757 bool llvm::replaceAllDbgUsesWith(Instruction &From, Value &To,
2758                                  Instruction &DomPoint, DominatorTree &DT) {
2759   // Exit early if From has no debug users.
2760   if (!From.isUsedByMetadata())
2761     return false;
2762 
2763   assert(&From != &To && "Can't replace something with itself");
2764 
2765   Type *FromTy = From.getType();
2766   Type *ToTy = To.getType();
2767 
2768   auto Identity = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {
2769     return DII.getExpression();
2770   };
2771   auto IdentityDVR = [&](DbgVariableRecord &DVR) -> DbgValReplacement {
2772     return DVR.getExpression();
2773   };
2774 
2775   // Handle no-op conversions.
2776   Module &M = *From.getModule();
2777   const DataLayout &DL = M.getDataLayout();
2778   if (isBitCastSemanticsPreserving(DL, FromTy, ToTy))
2779     return rewriteDebugUsers(From, To, DomPoint, DT, Identity, IdentityDVR);
2780 
2781   // Handle integer-to-integer widening and narrowing.
2782   // FIXME: Use DW_OP_convert when it's available everywhere.
2783   if (FromTy->isIntegerTy() && ToTy->isIntegerTy()) {
2784     uint64_t FromBits = FromTy->getPrimitiveSizeInBits();
2785     uint64_t ToBits = ToTy->getPrimitiveSizeInBits();
2786     assert(FromBits != ToBits && "Unexpected no-op conversion");
2787 
2788     // When the width of the result grows, assume that a debugger will only
2789     // access the low `FromBits` bits when inspecting the source variable.
2790     if (FromBits < ToBits)
2791       return rewriteDebugUsers(From, To, DomPoint, DT, Identity, IdentityDVR);
2792 
2793     // The width of the result has shrunk. Use sign/zero extension to describe
2794     // the source variable's high bits.
2795     auto SignOrZeroExt = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {
2796       DILocalVariable *Var = DII.getVariable();
2797 
2798       // Without knowing signedness, sign/zero extension isn't possible.
2799       auto Signedness = Var->getSignedness();
2800       if (!Signedness)
2801         return std::nullopt;
2802 
2803       bool Signed = *Signedness == DIBasicType::Signedness::Signed;
2804       return DIExpression::appendExt(DII.getExpression(), ToBits, FromBits,
2805                                      Signed);
2806     };
2807     // RemoveDIs: duplicate implementation working on DbgVariableRecords rather
2808     // than on dbg.value intrinsics.
2809     auto SignOrZeroExtDVR = [&](DbgVariableRecord &DVR) -> DbgValReplacement {
2810       DILocalVariable *Var = DVR.getVariable();
2811 
2812       // Without knowing signedness, sign/zero extension isn't possible.
2813       auto Signedness = Var->getSignedness();
2814       if (!Signedness)
2815         return std::nullopt;
2816 
2817       bool Signed = *Signedness == DIBasicType::Signedness::Signed;
2818       return DIExpression::appendExt(DVR.getExpression(), ToBits, FromBits,
2819                                      Signed);
2820     };
2821     return rewriteDebugUsers(From, To, DomPoint, DT, SignOrZeroExt,
2822                              SignOrZeroExtDVR);
2823   }
2824 
2825   // TODO: Floating-point conversions, vectors.
2826   return false;
2827 }
2828 
2829 bool llvm::handleUnreachableTerminator(
2830     Instruction *I, SmallVectorImpl<Value *> &PoisonedValues) {
2831   bool Changed = false;
2832   // RemoveDIs: erase debug-info on this instruction manually.
2833   I->dropDbgRecords();
2834   for (Use &U : I->operands()) {
2835     Value *Op = U.get();
2836     if (isa<Instruction>(Op) && !Op->getType()->isTokenTy()) {
2837       U.set(PoisonValue::get(Op->getType()));
2838       PoisonedValues.push_back(Op);
2839       Changed = true;
2840     }
2841   }
2842 
2843   return Changed;
2844 }
2845 
2846 std::pair<unsigned, unsigned>
2847 llvm::removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB) {
2848   unsigned NumDeadInst = 0;
2849   unsigned NumDeadDbgInst = 0;
2850   // Delete the instructions backwards, as it has a reduced likelihood of
2851   // having to update as many def-use and use-def chains.
2852   Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
2853   SmallVector<Value *> Uses;
2854   handleUnreachableTerminator(EndInst, Uses);
2855 
2856   while (EndInst != &BB->front()) {
2857     // Delete the next to last instruction.
2858     Instruction *Inst = &*--EndInst->getIterator();
2859     if (!Inst->use_empty() && !Inst->getType()->isTokenTy())
2860       Inst->replaceAllUsesWith(PoisonValue::get(Inst->getType()));
2861     if (Inst->isEHPad() || Inst->getType()->isTokenTy()) {
2862       // EHPads can't have DbgVariableRecords attached to them, but it might be
2863       // possible for things with token type.
2864       Inst->dropDbgRecords();
2865       EndInst = Inst;
2866       continue;
2867     }
2868     if (isa<DbgInfoIntrinsic>(Inst))
2869       ++NumDeadDbgInst;
2870     else
2871       ++NumDeadInst;
2872     // RemoveDIs: erasing debug-info must be done manually.
2873     Inst->dropDbgRecords();
2874     Inst->eraseFromParent();
2875   }
2876   return {NumDeadInst, NumDeadDbgInst};
2877 }
2878 
2879 unsigned llvm::changeToUnreachable(Instruction *I, bool PreserveLCSSA,
2880                                    DomTreeUpdater *DTU,
2881                                    MemorySSAUpdater *MSSAU) {
2882   BasicBlock *BB = I->getParent();
2883 
2884   if (MSSAU)
2885     MSSAU->changeToUnreachable(I);
2886 
2887   SmallSet<BasicBlock *, 8> UniqueSuccessors;
2888 
2889   // Loop over all of the successors, removing BB's entry from any PHI
2890   // nodes.
2891   for (BasicBlock *Successor : successors(BB)) {
2892     Successor->removePredecessor(BB, PreserveLCSSA);
2893     if (DTU)
2894       UniqueSuccessors.insert(Successor);
2895   }
2896   auto *UI = new UnreachableInst(I->getContext(), I->getIterator());
2897   UI->setDebugLoc(I->getDebugLoc());
2898 
2899   // All instructions after this are dead.
2900   unsigned NumInstrsRemoved = 0;
2901   BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end();
2902   while (BBI != BBE) {
2903     if (!BBI->use_empty())
2904       BBI->replaceAllUsesWith(PoisonValue::get(BBI->getType()));
2905     BBI++->eraseFromParent();
2906     ++NumInstrsRemoved;
2907   }
2908   if (DTU) {
2909     SmallVector<DominatorTree::UpdateType, 8> Updates;
2910     Updates.reserve(UniqueSuccessors.size());
2911     for (BasicBlock *UniqueSuccessor : UniqueSuccessors)
2912       Updates.push_back({DominatorTree::Delete, BB, UniqueSuccessor});
2913     DTU->applyUpdates(Updates);
2914   }
2915   BB->flushTerminatorDbgRecords();
2916   return NumInstrsRemoved;
2917 }
2918 
2919 CallInst *llvm::createCallMatchingInvoke(InvokeInst *II) {
2920   SmallVector<Value *, 8> Args(II->args());
2921   SmallVector<OperandBundleDef, 1> OpBundles;
2922   II->getOperandBundlesAsDefs(OpBundles);
2923   CallInst *NewCall = CallInst::Create(II->getFunctionType(),
2924                                        II->getCalledOperand(), Args, OpBundles);
2925   NewCall->setCallingConv(II->getCallingConv());
2926   NewCall->setAttributes(II->getAttributes());
2927   NewCall->setDebugLoc(II->getDebugLoc());
2928   NewCall->copyMetadata(*II);
2929 
2930   // If the invoke had profile metadata, try converting them for CallInst.
2931   uint64_t TotalWeight;
2932   if (NewCall->extractProfTotalWeight(TotalWeight)) {
2933     // Set the total weight if it fits into i32, otherwise reset.
2934     MDBuilder MDB(NewCall->getContext());
2935     auto NewWeights = uint32_t(TotalWeight) != TotalWeight
2936                           ? nullptr
2937                           : MDB.createBranchWeights({uint32_t(TotalWeight)});
2938     NewCall->setMetadata(LLVMContext::MD_prof, NewWeights);
2939   }
2940 
2941   return NewCall;
2942 }
2943 
2944 // changeToCall - Convert the specified invoke into a normal call.
2945 CallInst *llvm::changeToCall(InvokeInst *II, DomTreeUpdater *DTU) {
2946   CallInst *NewCall = createCallMatchingInvoke(II);
2947   NewCall->takeName(II);
2948   NewCall->insertBefore(II);
2949   II->replaceAllUsesWith(NewCall);
2950 
2951   // Follow the call by a branch to the normal destination.
2952   BasicBlock *NormalDestBB = II->getNormalDest();
2953   BranchInst::Create(NormalDestBB, II->getIterator());
2954 
2955   // Update PHI nodes in the unwind destination
2956   BasicBlock *BB = II->getParent();
2957   BasicBlock *UnwindDestBB = II->getUnwindDest();
2958   UnwindDestBB->removePredecessor(BB);
2959   II->eraseFromParent();
2960   if (DTU)
2961     DTU->applyUpdates({{DominatorTree::Delete, BB, UnwindDestBB}});
2962   return NewCall;
2963 }
2964 
2965 BasicBlock *llvm::changeToInvokeAndSplitBasicBlock(CallInst *CI,
2966                                                    BasicBlock *UnwindEdge,
2967                                                    DomTreeUpdater *DTU) {
2968   BasicBlock *BB = CI->getParent();
2969 
2970   // Convert this function call into an invoke instruction.  First, split the
2971   // basic block.
2972   BasicBlock *Split = SplitBlock(BB, CI, DTU, /*LI=*/nullptr, /*MSSAU*/ nullptr,
2973                                  CI->getName() + ".noexc");
2974 
2975   // Delete the unconditional branch inserted by SplitBlock
2976   BB->back().eraseFromParent();
2977 
2978   // Create the new invoke instruction.
2979   SmallVector<Value *, 8> InvokeArgs(CI->args());
2980   SmallVector<OperandBundleDef, 1> OpBundles;
2981 
2982   CI->getOperandBundlesAsDefs(OpBundles);
2983 
2984   // Note: we're round tripping operand bundles through memory here, and that
2985   // can potentially be avoided with a cleverer API design that we do not have
2986   // as of this time.
2987 
2988   InvokeInst *II =
2989       InvokeInst::Create(CI->getFunctionType(), CI->getCalledOperand(), Split,
2990                          UnwindEdge, InvokeArgs, OpBundles, CI->getName(), BB);
2991   II->setDebugLoc(CI->getDebugLoc());
2992   II->setCallingConv(CI->getCallingConv());
2993   II->setAttributes(CI->getAttributes());
2994   II->setMetadata(LLVMContext::MD_prof, CI->getMetadata(LLVMContext::MD_prof));
2995 
2996   if (DTU)
2997     DTU->applyUpdates({{DominatorTree::Insert, BB, UnwindEdge}});
2998 
2999   // Make sure that anything using the call now uses the invoke!  This also
3000   // updates the CallGraph if present, because it uses a WeakTrackingVH.
3001   CI->replaceAllUsesWith(II);
3002 
3003   // Delete the original call
3004   Split->front().eraseFromParent();
3005   return Split;
3006 }
3007 
3008 static bool markAliveBlocks(Function &F,
3009                             SmallPtrSetImpl<BasicBlock *> &Reachable,
3010                             DomTreeUpdater *DTU = nullptr) {
3011   SmallVector<BasicBlock*, 128> Worklist;
3012   BasicBlock *BB = &F.front();
3013   Worklist.push_back(BB);
3014   Reachable.insert(BB);
3015   bool Changed = false;
3016   do {
3017     BB = Worklist.pop_back_val();
3018 
3019     // Do a quick scan of the basic block, turning any obviously unreachable
3020     // instructions into LLVM unreachable insts.  The instruction combining pass
3021     // canonicalizes unreachable insts into stores to null or undef.
3022     for (Instruction &I : *BB) {
3023       if (auto *CI = dyn_cast<CallInst>(&I)) {
3024         Value *Callee = CI->getCalledOperand();
3025         // Handle intrinsic calls.
3026         if (Function *F = dyn_cast<Function>(Callee)) {
3027           auto IntrinsicID = F->getIntrinsicID();
3028           // Assumptions that are known to be false are equivalent to
3029           // unreachable. Also, if the condition is undefined, then we make the
3030           // choice most beneficial to the optimizer, and choose that to also be
3031           // unreachable.
3032           if (IntrinsicID == Intrinsic::assume) {
3033             if (match(CI->getArgOperand(0), m_CombineOr(m_Zero(), m_Undef()))) {
3034               // Don't insert a call to llvm.trap right before the unreachable.
3035               changeToUnreachable(CI, false, DTU);
3036               Changed = true;
3037               break;
3038             }
3039           } else if (IntrinsicID == Intrinsic::experimental_guard) {
3040             // A call to the guard intrinsic bails out of the current
3041             // compilation unit if the predicate passed to it is false. If the
3042             // predicate is a constant false, then we know the guard will bail
3043             // out of the current compile unconditionally, so all code following
3044             // it is dead.
3045             //
3046             // Note: unlike in llvm.assume, it is not "obviously profitable" for
3047             // guards to treat `undef` as `false` since a guard on `undef` can
3048             // still be useful for widening.
3049             if (match(CI->getArgOperand(0), m_Zero()))
3050               if (!isa<UnreachableInst>(CI->getNextNode())) {
3051                 changeToUnreachable(CI->getNextNode(), false, DTU);
3052                 Changed = true;
3053                 break;
3054               }
3055           }
3056         } else if ((isa<ConstantPointerNull>(Callee) &&
3057                     !NullPointerIsDefined(CI->getFunction(),
3058                                           cast<PointerType>(Callee->getType())
3059                                               ->getAddressSpace())) ||
3060                    isa<UndefValue>(Callee)) {
3061           changeToUnreachable(CI, false, DTU);
3062           Changed = true;
3063           break;
3064         }
3065         if (CI->doesNotReturn() && !CI->isMustTailCall()) {
3066           // If we found a call to a no-return function, insert an unreachable
3067           // instruction after it.  Make sure there isn't *already* one there
3068           // though.
3069           if (!isa<UnreachableInst>(CI->getNextNonDebugInstruction())) {
3070             // Don't insert a call to llvm.trap right before the unreachable.
3071             changeToUnreachable(CI->getNextNonDebugInstruction(), false, DTU);
3072             Changed = true;
3073           }
3074           break;
3075         }
3076       } else if (auto *SI = dyn_cast<StoreInst>(&I)) {
3077         // Store to undef and store to null are undefined and used to signal
3078         // that they should be changed to unreachable by passes that can't
3079         // modify the CFG.
3080 
3081         // Don't touch volatile stores.
3082         if (SI->isVolatile()) continue;
3083 
3084         Value *Ptr = SI->getOperand(1);
3085 
3086         if (isa<UndefValue>(Ptr) ||
3087             (isa<ConstantPointerNull>(Ptr) &&
3088              !NullPointerIsDefined(SI->getFunction(),
3089                                    SI->getPointerAddressSpace()))) {
3090           changeToUnreachable(SI, false, DTU);
3091           Changed = true;
3092           break;
3093         }
3094       }
3095     }
3096 
3097     Instruction *Terminator = BB->getTerminator();
3098     if (auto *II = dyn_cast<InvokeInst>(Terminator)) {
3099       // Turn invokes that call 'nounwind' functions into ordinary calls.
3100       Value *Callee = II->getCalledOperand();
3101       if ((isa<ConstantPointerNull>(Callee) &&
3102            !NullPointerIsDefined(BB->getParent())) ||
3103           isa<UndefValue>(Callee)) {
3104         changeToUnreachable(II, false, DTU);
3105         Changed = true;
3106       } else {
3107         if (II->doesNotReturn() &&
3108             !isa<UnreachableInst>(II->getNormalDest()->front())) {
3109           // If we found an invoke of a no-return function,
3110           // create a new empty basic block with an `unreachable` terminator,
3111           // and set it as the normal destination for the invoke,
3112           // unless that is already the case.
3113           // Note that the original normal destination could have other uses.
3114           BasicBlock *OrigNormalDest = II->getNormalDest();
3115           OrigNormalDest->removePredecessor(II->getParent());
3116           LLVMContext &Ctx = II->getContext();
3117           BasicBlock *UnreachableNormalDest = BasicBlock::Create(
3118               Ctx, OrigNormalDest->getName() + ".unreachable",
3119               II->getFunction(), OrigNormalDest);
3120           new UnreachableInst(Ctx, UnreachableNormalDest);
3121           II->setNormalDest(UnreachableNormalDest);
3122           if (DTU)
3123             DTU->applyUpdates(
3124                 {{DominatorTree::Delete, BB, OrigNormalDest},
3125                  {DominatorTree::Insert, BB, UnreachableNormalDest}});
3126           Changed = true;
3127         }
3128         if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(&F)) {
3129           if (II->use_empty() && !II->mayHaveSideEffects()) {
3130             // jump to the normal destination branch.
3131             BasicBlock *NormalDestBB = II->getNormalDest();
3132             BasicBlock *UnwindDestBB = II->getUnwindDest();
3133             BranchInst::Create(NormalDestBB, II->getIterator());
3134             UnwindDestBB->removePredecessor(II->getParent());
3135             II->eraseFromParent();
3136             if (DTU)
3137               DTU->applyUpdates({{DominatorTree::Delete, BB, UnwindDestBB}});
3138           } else
3139             changeToCall(II, DTU);
3140           Changed = true;
3141         }
3142       }
3143     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) {
3144       // Remove catchpads which cannot be reached.
3145       struct CatchPadDenseMapInfo {
3146         static CatchPadInst *getEmptyKey() {
3147           return DenseMapInfo<CatchPadInst *>::getEmptyKey();
3148         }
3149 
3150         static CatchPadInst *getTombstoneKey() {
3151           return DenseMapInfo<CatchPadInst *>::getTombstoneKey();
3152         }
3153 
3154         static unsigned getHashValue(CatchPadInst *CatchPad) {
3155           return static_cast<unsigned>(hash_combine_range(
3156               CatchPad->value_op_begin(), CatchPad->value_op_end()));
3157         }
3158 
3159         static bool isEqual(CatchPadInst *LHS, CatchPadInst *RHS) {
3160           if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
3161               RHS == getEmptyKey() || RHS == getTombstoneKey())
3162             return LHS == RHS;
3163           return LHS->isIdenticalTo(RHS);
3164         }
3165       };
3166 
3167       SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases;
3168       // Set of unique CatchPads.
3169       SmallDenseMap<CatchPadInst *, detail::DenseSetEmpty, 4,
3170                     CatchPadDenseMapInfo, detail::DenseSetPair<CatchPadInst *>>
3171           HandlerSet;
3172       detail::DenseSetEmpty Empty;
3173       for (CatchSwitchInst::handler_iterator I = CatchSwitch->handler_begin(),
3174                                              E = CatchSwitch->handler_end();
3175            I != E; ++I) {
3176         BasicBlock *HandlerBB = *I;
3177         if (DTU)
3178           ++NumPerSuccessorCases[HandlerBB];
3179         auto *CatchPad = cast<CatchPadInst>(HandlerBB->getFirstNonPHI());
3180         if (!HandlerSet.insert({CatchPad, Empty}).second) {
3181           if (DTU)
3182             --NumPerSuccessorCases[HandlerBB];
3183           CatchSwitch->removeHandler(I);
3184           --I;
3185           --E;
3186           Changed = true;
3187         }
3188       }
3189       if (DTU) {
3190         std::vector<DominatorTree::UpdateType> Updates;
3191         for (const std::pair<BasicBlock *, int> &I : NumPerSuccessorCases)
3192           if (I.second == 0)
3193             Updates.push_back({DominatorTree::Delete, BB, I.first});
3194         DTU->applyUpdates(Updates);
3195       }
3196     }
3197 
3198     Changed |= ConstantFoldTerminator(BB, true, nullptr, DTU);
3199     for (BasicBlock *Successor : successors(BB))
3200       if (Reachable.insert(Successor).second)
3201         Worklist.push_back(Successor);
3202   } while (!Worklist.empty());
3203   return Changed;
3204 }
3205 
3206 Instruction *llvm::removeUnwindEdge(BasicBlock *BB, DomTreeUpdater *DTU) {
3207   Instruction *TI = BB->getTerminator();
3208 
3209   if (auto *II = dyn_cast<InvokeInst>(TI))
3210     return changeToCall(II, DTU);
3211 
3212   Instruction *NewTI;
3213   BasicBlock *UnwindDest;
3214 
3215   if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
3216     NewTI = CleanupReturnInst::Create(CRI->getCleanupPad(), nullptr, CRI->getIterator());
3217     UnwindDest = CRI->getUnwindDest();
3218   } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
3219     auto *NewCatchSwitch = CatchSwitchInst::Create(
3220         CatchSwitch->getParentPad(), nullptr, CatchSwitch->getNumHandlers(),
3221         CatchSwitch->getName(), CatchSwitch->getIterator());
3222     for (BasicBlock *PadBB : CatchSwitch->handlers())
3223       NewCatchSwitch->addHandler(PadBB);
3224 
3225     NewTI = NewCatchSwitch;
3226     UnwindDest = CatchSwitch->getUnwindDest();
3227   } else {
3228     llvm_unreachable("Could not find unwind successor");
3229   }
3230 
3231   NewTI->takeName(TI);
3232   NewTI->setDebugLoc(TI->getDebugLoc());
3233   UnwindDest->removePredecessor(BB);
3234   TI->replaceAllUsesWith(NewTI);
3235   TI->eraseFromParent();
3236   if (DTU)
3237     DTU->applyUpdates({{DominatorTree::Delete, BB, UnwindDest}});
3238   return NewTI;
3239 }
3240 
3241 /// removeUnreachableBlocks - Remove blocks that are not reachable, even
3242 /// if they are in a dead cycle.  Return true if a change was made, false
3243 /// otherwise.
3244 bool llvm::removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU,
3245                                    MemorySSAUpdater *MSSAU) {
3246   SmallPtrSet<BasicBlock *, 16> Reachable;
3247   bool Changed = markAliveBlocks(F, Reachable, DTU);
3248 
3249   // If there are unreachable blocks in the CFG...
3250   if (Reachable.size() == F.size())
3251     return Changed;
3252 
3253   assert(Reachable.size() < F.size());
3254 
3255   // Are there any blocks left to actually delete?
3256   SmallSetVector<BasicBlock *, 8> BlocksToRemove;
3257   for (BasicBlock &BB : F) {
3258     // Skip reachable basic blocks
3259     if (Reachable.count(&BB))
3260       continue;
3261     // Skip already-deleted blocks
3262     if (DTU && DTU->isBBPendingDeletion(&BB))
3263       continue;
3264     BlocksToRemove.insert(&BB);
3265   }
3266 
3267   if (BlocksToRemove.empty())
3268     return Changed;
3269 
3270   Changed = true;
3271   NumRemoved += BlocksToRemove.size();
3272 
3273   if (MSSAU)
3274     MSSAU->removeBlocks(BlocksToRemove);
3275 
3276   DeleteDeadBlocks(BlocksToRemove.takeVector(), DTU);
3277 
3278   return Changed;
3279 }
3280 
3281 void llvm::combineMetadata(Instruction *K, const Instruction *J,
3282                            ArrayRef<unsigned> KnownIDs, bool DoesKMove) {
3283   SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
3284   K->dropUnknownNonDebugMetadata(KnownIDs);
3285   K->getAllMetadataOtherThanDebugLoc(Metadata);
3286   for (const auto &MD : Metadata) {
3287     unsigned Kind = MD.first;
3288     MDNode *JMD = J->getMetadata(Kind);
3289     MDNode *KMD = MD.second;
3290 
3291     switch (Kind) {
3292       default:
3293         K->setMetadata(Kind, nullptr); // Remove unknown metadata
3294         break;
3295       case LLVMContext::MD_dbg:
3296         llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
3297       case LLVMContext::MD_DIAssignID:
3298         K->mergeDIAssignID(J);
3299         break;
3300       case LLVMContext::MD_tbaa:
3301         K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
3302         break;
3303       case LLVMContext::MD_alias_scope:
3304         K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD));
3305         break;
3306       case LLVMContext::MD_noalias:
3307       case LLVMContext::MD_mem_parallel_loop_access:
3308         K->setMetadata(Kind, MDNode::intersect(JMD, KMD));
3309         break;
3310       case LLVMContext::MD_access_group:
3311         K->setMetadata(LLVMContext::MD_access_group,
3312                        intersectAccessGroups(K, J));
3313         break;
3314       case LLVMContext::MD_range:
3315         if (DoesKMove || !K->hasMetadata(LLVMContext::MD_noundef))
3316           K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD));
3317         break;
3318       case LLVMContext::MD_fpmath:
3319         K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
3320         break;
3321       case LLVMContext::MD_invariant_load:
3322         // If K moves, only set the !invariant.load if it is present in both
3323         // instructions.
3324         if (DoesKMove)
3325           K->setMetadata(Kind, JMD);
3326         break;
3327       case LLVMContext::MD_nonnull:
3328         if (DoesKMove || !K->hasMetadata(LLVMContext::MD_noundef))
3329           K->setMetadata(Kind, JMD);
3330         break;
3331       case LLVMContext::MD_invariant_group:
3332         // Preserve !invariant.group in K.
3333         break;
3334       case LLVMContext::MD_mmra:
3335         // Combine MMRAs
3336         break;
3337       case LLVMContext::MD_align:
3338         if (DoesKMove || !K->hasMetadata(LLVMContext::MD_noundef))
3339           K->setMetadata(
3340               Kind, MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
3341         break;
3342       case LLVMContext::MD_dereferenceable:
3343       case LLVMContext::MD_dereferenceable_or_null:
3344         if (DoesKMove)
3345           K->setMetadata(Kind,
3346             MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
3347         break;
3348       case LLVMContext::MD_preserve_access_index:
3349         // Preserve !preserve.access.index in K.
3350         break;
3351       case LLVMContext::MD_noundef:
3352         // If K does move, keep noundef if it is present in both instructions.
3353         if (DoesKMove)
3354           K->setMetadata(Kind, JMD);
3355         break;
3356       case LLVMContext::MD_nontemporal:
3357         // Preserve !nontemporal if it is present on both instructions.
3358         K->setMetadata(Kind, JMD);
3359         break;
3360       case LLVMContext::MD_prof:
3361         if (DoesKMove)
3362           K->setMetadata(Kind, MDNode::getMergedProfMetadata(KMD, JMD, K, J));
3363         break;
3364     }
3365   }
3366   // Set !invariant.group from J if J has it. If both instructions have it
3367   // then we will just pick it from J - even when they are different.
3368   // Also make sure that K is load or store - f.e. combining bitcast with load
3369   // could produce bitcast with invariant.group metadata, which is invalid.
3370   // FIXME: we should try to preserve both invariant.group md if they are
3371   // different, but right now instruction can only have one invariant.group.
3372   if (auto *JMD = J->getMetadata(LLVMContext::MD_invariant_group))
3373     if (isa<LoadInst>(K) || isa<StoreInst>(K))
3374       K->setMetadata(LLVMContext::MD_invariant_group, JMD);
3375 
3376   // Merge MMRAs.
3377   // This is handled separately because we also want to handle cases where K
3378   // doesn't have tags but J does.
3379   auto JMMRA = J->getMetadata(LLVMContext::MD_mmra);
3380   auto KMMRA = K->getMetadata(LLVMContext::MD_mmra);
3381   if (JMMRA || KMMRA) {
3382     K->setMetadata(LLVMContext::MD_mmra,
3383                    MMRAMetadata::combine(K->getContext(), JMMRA, KMMRA));
3384   }
3385 }
3386 
3387 void llvm::combineMetadataForCSE(Instruction *K, const Instruction *J,
3388                                  bool KDominatesJ) {
3389   unsigned KnownIDs[] = {LLVMContext::MD_tbaa,
3390                          LLVMContext::MD_alias_scope,
3391                          LLVMContext::MD_noalias,
3392                          LLVMContext::MD_range,
3393                          LLVMContext::MD_fpmath,
3394                          LLVMContext::MD_invariant_load,
3395                          LLVMContext::MD_nonnull,
3396                          LLVMContext::MD_invariant_group,
3397                          LLVMContext::MD_align,
3398                          LLVMContext::MD_dereferenceable,
3399                          LLVMContext::MD_dereferenceable_or_null,
3400                          LLVMContext::MD_access_group,
3401                          LLVMContext::MD_preserve_access_index,
3402                          LLVMContext::MD_prof,
3403                          LLVMContext::MD_nontemporal,
3404                          LLVMContext::MD_noundef,
3405                          LLVMContext::MD_mmra};
3406   combineMetadata(K, J, KnownIDs, KDominatesJ);
3407 }
3408 
3409 void llvm::copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source) {
3410   SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
3411   Source.getAllMetadata(MD);
3412   MDBuilder MDB(Dest.getContext());
3413   Type *NewType = Dest.getType();
3414   const DataLayout &DL = Source.getDataLayout();
3415   for (const auto &MDPair : MD) {
3416     unsigned ID = MDPair.first;
3417     MDNode *N = MDPair.second;
3418     // Note, essentially every kind of metadata should be preserved here! This
3419     // routine is supposed to clone a load instruction changing *only its type*.
3420     // The only metadata it makes sense to drop is metadata which is invalidated
3421     // when the pointer type changes. This should essentially never be the case
3422     // in LLVM, but we explicitly switch over only known metadata to be
3423     // conservatively correct. If you are adding metadata to LLVM which pertains
3424     // to loads, you almost certainly want to add it here.
3425     switch (ID) {
3426     case LLVMContext::MD_dbg:
3427     case LLVMContext::MD_tbaa:
3428     case LLVMContext::MD_prof:
3429     case LLVMContext::MD_fpmath:
3430     case LLVMContext::MD_tbaa_struct:
3431     case LLVMContext::MD_invariant_load:
3432     case LLVMContext::MD_alias_scope:
3433     case LLVMContext::MD_noalias:
3434     case LLVMContext::MD_nontemporal:
3435     case LLVMContext::MD_mem_parallel_loop_access:
3436     case LLVMContext::MD_access_group:
3437     case LLVMContext::MD_noundef:
3438       // All of these directly apply.
3439       Dest.setMetadata(ID, N);
3440       break;
3441 
3442     case LLVMContext::MD_nonnull:
3443       copyNonnullMetadata(Source, N, Dest);
3444       break;
3445 
3446     case LLVMContext::MD_align:
3447     case LLVMContext::MD_dereferenceable:
3448     case LLVMContext::MD_dereferenceable_or_null:
3449       // These only directly apply if the new type is also a pointer.
3450       if (NewType->isPointerTy())
3451         Dest.setMetadata(ID, N);
3452       break;
3453 
3454     case LLVMContext::MD_range:
3455       copyRangeMetadata(DL, Source, N, Dest);
3456       break;
3457     }
3458   }
3459 }
3460 
3461 void llvm::patchReplacementInstruction(Instruction *I, Value *Repl) {
3462   auto *ReplInst = dyn_cast<Instruction>(Repl);
3463   if (!ReplInst)
3464     return;
3465 
3466   // Patch the replacement so that it is not more restrictive than the value
3467   // being replaced.
3468   WithOverflowInst *UnusedWO;
3469   // When replacing the result of a llvm.*.with.overflow intrinsic with a
3470   // overflowing binary operator, nuw/nsw flags may no longer hold.
3471   if (isa<OverflowingBinaryOperator>(ReplInst) &&
3472       match(I, m_ExtractValue<0>(m_WithOverflowInst(UnusedWO))))
3473     ReplInst->dropPoisonGeneratingFlags();
3474   // Note that if 'I' is a load being replaced by some operation,
3475   // for example, by an arithmetic operation, then andIRFlags()
3476   // would just erase all math flags from the original arithmetic
3477   // operation, which is clearly not wanted and not needed.
3478   else if (!isa<LoadInst>(I))
3479     ReplInst->andIRFlags(I);
3480 
3481   // FIXME: If both the original and replacement value are part of the
3482   // same control-flow region (meaning that the execution of one
3483   // guarantees the execution of the other), then we can combine the
3484   // noalias scopes here and do better than the general conservative
3485   // answer used in combineMetadata().
3486 
3487   // In general, GVN unifies expressions over different control-flow
3488   // regions, and so we need a conservative combination of the noalias
3489   // scopes.
3490   combineMetadataForCSE(ReplInst, I, false);
3491 }
3492 
3493 template <typename RootType, typename ShouldReplaceFn>
3494 static unsigned replaceDominatedUsesWith(Value *From, Value *To,
3495                                          const RootType &Root,
3496                                          const ShouldReplaceFn &ShouldReplace) {
3497   assert(From->getType() == To->getType());
3498 
3499   unsigned Count = 0;
3500   for (Use &U : llvm::make_early_inc_range(From->uses())) {
3501     auto *II = dyn_cast<IntrinsicInst>(U.getUser());
3502     if (II && II->getIntrinsicID() == Intrinsic::fake_use)
3503       continue;
3504     if (!ShouldReplace(Root, U))
3505       continue;
3506     LLVM_DEBUG(dbgs() << "Replace dominated use of '";
3507                From->printAsOperand(dbgs());
3508                dbgs() << "' with " << *To << " in " << *U.getUser() << "\n");
3509     U.set(To);
3510     ++Count;
3511   }
3512   return Count;
3513 }
3514 
3515 unsigned llvm::replaceNonLocalUsesWith(Instruction *From, Value *To) {
3516    assert(From->getType() == To->getType());
3517    auto *BB = From->getParent();
3518    unsigned Count = 0;
3519 
3520    for (Use &U : llvm::make_early_inc_range(From->uses())) {
3521     auto *I = cast<Instruction>(U.getUser());
3522     if (I->getParent() == BB)
3523       continue;
3524     U.set(To);
3525     ++Count;
3526   }
3527   return Count;
3528 }
3529 
3530 unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
3531                                         DominatorTree &DT,
3532                                         const BasicBlockEdge &Root) {
3533   auto Dominates = [&DT](const BasicBlockEdge &Root, const Use &U) {
3534     return DT.dominates(Root, U);
3535   };
3536   return ::replaceDominatedUsesWith(From, To, Root, Dominates);
3537 }
3538 
3539 unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
3540                                         DominatorTree &DT,
3541                                         const BasicBlock *BB) {
3542   auto Dominates = [&DT](const BasicBlock *BB, const Use &U) {
3543     return DT.dominates(BB, U);
3544   };
3545   return ::replaceDominatedUsesWith(From, To, BB, Dominates);
3546 }
3547 
3548 unsigned llvm::replaceDominatedUsesWithIf(
3549     Value *From, Value *To, DominatorTree &DT, const BasicBlockEdge &Root,
3550     function_ref<bool(const Use &U, const Value *To)> ShouldReplace) {
3551   auto DominatesAndShouldReplace =
3552       [&DT, &ShouldReplace, To](const BasicBlockEdge &Root, const Use &U) {
3553         return DT.dominates(Root, U) && ShouldReplace(U, To);
3554       };
3555   return ::replaceDominatedUsesWith(From, To, Root, DominatesAndShouldReplace);
3556 }
3557 
3558 unsigned llvm::replaceDominatedUsesWithIf(
3559     Value *From, Value *To, DominatorTree &DT, const BasicBlock *BB,
3560     function_ref<bool(const Use &U, const Value *To)> ShouldReplace) {
3561   auto DominatesAndShouldReplace = [&DT, &ShouldReplace,
3562                                     To](const BasicBlock *BB, const Use &U) {
3563     return DT.dominates(BB, U) && ShouldReplace(U, To);
3564   };
3565   return ::replaceDominatedUsesWith(From, To, BB, DominatesAndShouldReplace);
3566 }
3567 
3568 bool llvm::callsGCLeafFunction(const CallBase *Call,
3569                                const TargetLibraryInfo &TLI) {
3570   // Check if the function is specifically marked as a gc leaf function.
3571   if (Call->hasFnAttr("gc-leaf-function"))
3572     return true;
3573   if (const Function *F = Call->getCalledFunction()) {
3574     if (F->hasFnAttribute("gc-leaf-function"))
3575       return true;
3576 
3577     if (auto IID = F->getIntrinsicID()) {
3578       // Most LLVM intrinsics do not take safepoints.
3579       return IID != Intrinsic::experimental_gc_statepoint &&
3580              IID != Intrinsic::experimental_deoptimize &&
3581              IID != Intrinsic::memcpy_element_unordered_atomic &&
3582              IID != Intrinsic::memmove_element_unordered_atomic;
3583     }
3584   }
3585 
3586   // Lib calls can be materialized by some passes, and won't be
3587   // marked as 'gc-leaf-function.' All available Libcalls are
3588   // GC-leaf.
3589   LibFunc LF;
3590   if (TLI.getLibFunc(*Call, LF)) {
3591     return TLI.has(LF);
3592   }
3593 
3594   return false;
3595 }
3596 
3597 void llvm::copyNonnullMetadata(const LoadInst &OldLI, MDNode *N,
3598                                LoadInst &NewLI) {
3599   auto *NewTy = NewLI.getType();
3600 
3601   // This only directly applies if the new type is also a pointer.
3602   if (NewTy->isPointerTy()) {
3603     NewLI.setMetadata(LLVMContext::MD_nonnull, N);
3604     return;
3605   }
3606 
3607   // The only other translation we can do is to integral loads with !range
3608   // metadata.
3609   if (!NewTy->isIntegerTy())
3610     return;
3611 
3612   MDBuilder MDB(NewLI.getContext());
3613   const Value *Ptr = OldLI.getPointerOperand();
3614   auto *ITy = cast<IntegerType>(NewTy);
3615   auto *NullInt = ConstantExpr::getPtrToInt(
3616       ConstantPointerNull::get(cast<PointerType>(Ptr->getType())), ITy);
3617   auto *NonNullInt = ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1));
3618   NewLI.setMetadata(LLVMContext::MD_range,
3619                     MDB.createRange(NonNullInt, NullInt));
3620 }
3621 
3622 void llvm::copyRangeMetadata(const DataLayout &DL, const LoadInst &OldLI,
3623                              MDNode *N, LoadInst &NewLI) {
3624   auto *NewTy = NewLI.getType();
3625   // Simply copy the metadata if the type did not change.
3626   if (NewTy == OldLI.getType()) {
3627     NewLI.setMetadata(LLVMContext::MD_range, N);
3628     return;
3629   }
3630 
3631   // Give up unless it is converted to a pointer where there is a single very
3632   // valuable mapping we can do reliably.
3633   // FIXME: It would be nice to propagate this in more ways, but the type
3634   // conversions make it hard.
3635   if (!NewTy->isPointerTy())
3636     return;
3637 
3638   unsigned BitWidth = DL.getPointerTypeSizeInBits(NewTy);
3639   if (BitWidth == OldLI.getType()->getScalarSizeInBits() &&
3640       !getConstantRangeFromMetadata(*N).contains(APInt(BitWidth, 0))) {
3641     MDNode *NN = MDNode::get(OldLI.getContext(), std::nullopt);
3642     NewLI.setMetadata(LLVMContext::MD_nonnull, NN);
3643   }
3644 }
3645 
3646 void llvm::dropDebugUsers(Instruction &I) {
3647   SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
3648   SmallVector<DbgVariableRecord *, 1> DPUsers;
3649   findDbgUsers(DbgUsers, &I, &DPUsers);
3650   for (auto *DII : DbgUsers)
3651     DII->eraseFromParent();
3652   for (auto *DVR : DPUsers)
3653     DVR->eraseFromParent();
3654 }
3655 
3656 void llvm::hoistAllInstructionsInto(BasicBlock *DomBlock, Instruction *InsertPt,
3657                                     BasicBlock *BB) {
3658   // Since we are moving the instructions out of its basic block, we do not
3659   // retain their original debug locations (DILocations) and debug intrinsic
3660   // instructions.
3661   //
3662   // Doing so would degrade the debugging experience and adversely affect the
3663   // accuracy of profiling information.
3664   //
3665   // Currently, when hoisting the instructions, we take the following actions:
3666   // - Remove their debug intrinsic instructions.
3667   // - Set their debug locations to the values from the insertion point.
3668   //
3669   // As per PR39141 (comment #8), the more fundamental reason why the dbg.values
3670   // need to be deleted, is because there will not be any instructions with a
3671   // DILocation in either branch left after performing the transformation. We
3672   // can only insert a dbg.value after the two branches are joined again.
3673   //
3674   // See PR38762, PR39243 for more details.
3675   //
3676   // TODO: Extend llvm.dbg.value to take more than one SSA Value (PR39141) to
3677   // encode predicated DIExpressions that yield different results on different
3678   // code paths.
3679 
3680   for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) {
3681     Instruction *I = &*II;
3682     I->dropUBImplyingAttrsAndMetadata();
3683     if (I->isUsedByMetadata())
3684       dropDebugUsers(*I);
3685     // RemoveDIs: drop debug-info too as the following code does.
3686     I->dropDbgRecords();
3687     if (I->isDebugOrPseudoInst()) {
3688       // Remove DbgInfo and pseudo probe Intrinsics.
3689       II = I->eraseFromParent();
3690       continue;
3691     }
3692     I->setDebugLoc(InsertPt->getDebugLoc());
3693     ++II;
3694   }
3695   DomBlock->splice(InsertPt->getIterator(), BB, BB->begin(),
3696                    BB->getTerminator()->getIterator());
3697 }
3698 
3699 DIExpression *llvm::getExpressionForConstant(DIBuilder &DIB, const Constant &C,
3700                                              Type &Ty) {
3701   // Create integer constant expression.
3702   auto createIntegerExpression = [&DIB](const Constant &CV) -> DIExpression * {
3703     const APInt &API = cast<ConstantInt>(&CV)->getValue();
3704     std::optional<int64_t> InitIntOpt = API.trySExtValue();
3705     return InitIntOpt ? DIB.createConstantValueExpression(
3706                             static_cast<uint64_t>(*InitIntOpt))
3707                       : nullptr;
3708   };
3709 
3710   if (isa<ConstantInt>(C))
3711     return createIntegerExpression(C);
3712 
3713   auto *FP = dyn_cast<ConstantFP>(&C);
3714   if (FP && Ty.isFloatingPointTy() && Ty.getScalarSizeInBits() <= 64) {
3715     const APFloat &APF = FP->getValueAPF();
3716     APInt const &API = APF.bitcastToAPInt();
3717     if (auto Temp = API.getZExtValue())
3718       return DIB.createConstantValueExpression(static_cast<uint64_t>(Temp));
3719     return DIB.createConstantValueExpression(*API.getRawData());
3720   }
3721 
3722   if (!Ty.isPointerTy())
3723     return nullptr;
3724 
3725   if (isa<ConstantPointerNull>(C))
3726     return DIB.createConstantValueExpression(0);
3727 
3728   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(&C))
3729     if (CE->getOpcode() == Instruction::IntToPtr) {
3730       const Value *V = CE->getOperand(0);
3731       if (auto CI = dyn_cast_or_null<ConstantInt>(V))
3732         return createIntegerExpression(*CI);
3733     }
3734   return nullptr;
3735 }
3736 
3737 void llvm::remapDebugVariable(ValueToValueMapTy &Mapping, Instruction *Inst) {
3738   auto RemapDebugOperands = [&Mapping](auto *DV, auto Set) {
3739     for (auto *Op : Set) {
3740       auto I = Mapping.find(Op);
3741       if (I != Mapping.end())
3742         DV->replaceVariableLocationOp(Op, I->second, /*AllowEmpty=*/true);
3743     }
3744   };
3745   auto RemapAssignAddress = [&Mapping](auto *DA) {
3746     auto I = Mapping.find(DA->getAddress());
3747     if (I != Mapping.end())
3748       DA->setAddress(I->second);
3749   };
3750   if (auto DVI = dyn_cast<DbgVariableIntrinsic>(Inst))
3751     RemapDebugOperands(DVI, DVI->location_ops());
3752   if (auto DAI = dyn_cast<DbgAssignIntrinsic>(Inst))
3753     RemapAssignAddress(DAI);
3754   for (DbgVariableRecord &DVR : filterDbgVars(Inst->getDbgRecordRange())) {
3755     RemapDebugOperands(&DVR, DVR.location_ops());
3756     if (DVR.isDbgAssign())
3757       RemapAssignAddress(&DVR);
3758   }
3759 }
3760 
3761 namespace {
3762 
3763 /// A potential constituent of a bitreverse or bswap expression. See
3764 /// collectBitParts for a fuller explanation.
3765 struct BitPart {
3766   BitPart(Value *P, unsigned BW) : Provider(P) {
3767     Provenance.resize(BW);
3768   }
3769 
3770   /// The Value that this is a bitreverse/bswap of.
3771   Value *Provider;
3772 
3773   /// The "provenance" of each bit. Provenance[A] = B means that bit A
3774   /// in Provider becomes bit B in the result of this expression.
3775   SmallVector<int8_t, 32> Provenance; // int8_t means max size is i128.
3776 
3777   enum { Unset = -1 };
3778 };
3779 
3780 } // end anonymous namespace
3781 
3782 /// Analyze the specified subexpression and see if it is capable of providing
3783 /// pieces of a bswap or bitreverse. The subexpression provides a potential
3784 /// piece of a bswap or bitreverse if it can be proved that each non-zero bit in
3785 /// the output of the expression came from a corresponding bit in some other
3786 /// value. This function is recursive, and the end result is a mapping of
3787 /// bitnumber to bitnumber. It is the caller's responsibility to validate that
3788 /// the bitnumber to bitnumber mapping is correct for a bswap or bitreverse.
3789 ///
3790 /// For example, if the current subexpression if "(shl i32 %X, 24)" then we know
3791 /// that the expression deposits the low byte of %X into the high byte of the
3792 /// result and that all other bits are zero. This expression is accepted and a
3793 /// BitPart is returned with Provider set to %X and Provenance[24-31] set to
3794 /// [0-7].
3795 ///
3796 /// For vector types, all analysis is performed at the per-element level. No
3797 /// cross-element analysis is supported (shuffle/insertion/reduction), and all
3798 /// constant masks must be splatted across all elements.
3799 ///
3800 /// To avoid revisiting values, the BitPart results are memoized into the
3801 /// provided map. To avoid unnecessary copying of BitParts, BitParts are
3802 /// constructed in-place in the \c BPS map. Because of this \c BPS needs to
3803 /// store BitParts objects, not pointers. As we need the concept of a nullptr
3804 /// BitParts (Value has been analyzed and the analysis failed), we an Optional
3805 /// type instead to provide the same functionality.
3806 ///
3807 /// Because we pass around references into \c BPS, we must use a container that
3808 /// does not invalidate internal references (std::map instead of DenseMap).
3809 static const std::optional<BitPart> &
3810 collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals,
3811                 std::map<Value *, std::optional<BitPart>> &BPS, int Depth,
3812                 bool &FoundRoot) {
3813   auto I = BPS.find(V);
3814   if (I != BPS.end())
3815     return I->second;
3816 
3817   auto &Result = BPS[V] = std::nullopt;
3818   auto BitWidth = V->getType()->getScalarSizeInBits();
3819 
3820   // Can't do integer/elements > 128 bits.
3821   if (BitWidth > 128)
3822     return Result;
3823 
3824   // Prevent stack overflow by limiting the recursion depth
3825   if (Depth == BitPartRecursionMaxDepth) {
3826     LLVM_DEBUG(dbgs() << "collectBitParts max recursion depth reached.\n");
3827     return Result;
3828   }
3829 
3830   if (auto *I = dyn_cast<Instruction>(V)) {
3831     Value *X, *Y;
3832     const APInt *C;
3833 
3834     // If this is an or instruction, it may be an inner node of the bswap.
3835     if (match(V, m_Or(m_Value(X), m_Value(Y)))) {
3836       // Check we have both sources and they are from the same provider.
3837       const auto &A = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3838                                       Depth + 1, FoundRoot);
3839       if (!A || !A->Provider)
3840         return Result;
3841 
3842       const auto &B = collectBitParts(Y, MatchBSwaps, MatchBitReversals, BPS,
3843                                       Depth + 1, FoundRoot);
3844       if (!B || A->Provider != B->Provider)
3845         return Result;
3846 
3847       // Try and merge the two together.
3848       Result = BitPart(A->Provider, BitWidth);
3849       for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx) {
3850         if (A->Provenance[BitIdx] != BitPart::Unset &&
3851             B->Provenance[BitIdx] != BitPart::Unset &&
3852             A->Provenance[BitIdx] != B->Provenance[BitIdx])
3853           return Result = std::nullopt;
3854 
3855         if (A->Provenance[BitIdx] == BitPart::Unset)
3856           Result->Provenance[BitIdx] = B->Provenance[BitIdx];
3857         else
3858           Result->Provenance[BitIdx] = A->Provenance[BitIdx];
3859       }
3860 
3861       return Result;
3862     }
3863 
3864     // If this is a logical shift by a constant, recurse then shift the result.
3865     if (match(V, m_LogicalShift(m_Value(X), m_APInt(C)))) {
3866       const APInt &BitShift = *C;
3867 
3868       // Ensure the shift amount is defined.
3869       if (BitShift.uge(BitWidth))
3870         return Result;
3871 
3872       // For bswap-only, limit shift amounts to whole bytes, for an early exit.
3873       if (!MatchBitReversals && (BitShift.getZExtValue() % 8) != 0)
3874         return Result;
3875 
3876       const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3877                                         Depth + 1, FoundRoot);
3878       if (!Res)
3879         return Result;
3880       Result = Res;
3881 
3882       // Perform the "shift" on BitProvenance.
3883       auto &P = Result->Provenance;
3884       if (I->getOpcode() == Instruction::Shl) {
3885         P.erase(std::prev(P.end(), BitShift.getZExtValue()), P.end());
3886         P.insert(P.begin(), BitShift.getZExtValue(), BitPart::Unset);
3887       } else {
3888         P.erase(P.begin(), std::next(P.begin(), BitShift.getZExtValue()));
3889         P.insert(P.end(), BitShift.getZExtValue(), BitPart::Unset);
3890       }
3891 
3892       return Result;
3893     }
3894 
3895     // If this is a logical 'and' with a mask that clears bits, recurse then
3896     // unset the appropriate bits.
3897     if (match(V, m_And(m_Value(X), m_APInt(C)))) {
3898       const APInt &AndMask = *C;
3899 
3900       // Check that the mask allows a multiple of 8 bits for a bswap, for an
3901       // early exit.
3902       unsigned NumMaskedBits = AndMask.popcount();
3903       if (!MatchBitReversals && (NumMaskedBits % 8) != 0)
3904         return Result;
3905 
3906       const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3907                                         Depth + 1, FoundRoot);
3908       if (!Res)
3909         return Result;
3910       Result = Res;
3911 
3912       for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)
3913         // If the AndMask is zero for this bit, clear the bit.
3914         if (AndMask[BitIdx] == 0)
3915           Result->Provenance[BitIdx] = BitPart::Unset;
3916       return Result;
3917     }
3918 
3919     // If this is a zext instruction zero extend the result.
3920     if (match(V, m_ZExt(m_Value(X)))) {
3921       const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3922                                         Depth + 1, FoundRoot);
3923       if (!Res)
3924         return Result;
3925 
3926       Result = BitPart(Res->Provider, BitWidth);
3927       auto NarrowBitWidth = X->getType()->getScalarSizeInBits();
3928       for (unsigned BitIdx = 0; BitIdx < NarrowBitWidth; ++BitIdx)
3929         Result->Provenance[BitIdx] = Res->Provenance[BitIdx];
3930       for (unsigned BitIdx = NarrowBitWidth; BitIdx < BitWidth; ++BitIdx)
3931         Result->Provenance[BitIdx] = BitPart::Unset;
3932       return Result;
3933     }
3934 
3935     // If this is a truncate instruction, extract the lower bits.
3936     if (match(V, m_Trunc(m_Value(X)))) {
3937       const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3938                                         Depth + 1, FoundRoot);
3939       if (!Res)
3940         return Result;
3941 
3942       Result = BitPart(Res->Provider, BitWidth);
3943       for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)
3944         Result->Provenance[BitIdx] = Res->Provenance[BitIdx];
3945       return Result;
3946     }
3947 
3948     // BITREVERSE - most likely due to us previous matching a partial
3949     // bitreverse.
3950     if (match(V, m_BitReverse(m_Value(X)))) {
3951       const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3952                                         Depth + 1, FoundRoot);
3953       if (!Res)
3954         return Result;
3955 
3956       Result = BitPart(Res->Provider, BitWidth);
3957       for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)
3958         Result->Provenance[(BitWidth - 1) - BitIdx] = Res->Provenance[BitIdx];
3959       return Result;
3960     }
3961 
3962     // BSWAP - most likely due to us previous matching a partial bswap.
3963     if (match(V, m_BSwap(m_Value(X)))) {
3964       const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3965                                         Depth + 1, FoundRoot);
3966       if (!Res)
3967         return Result;
3968 
3969       unsigned ByteWidth = BitWidth / 8;
3970       Result = BitPart(Res->Provider, BitWidth);
3971       for (unsigned ByteIdx = 0; ByteIdx < ByteWidth; ++ByteIdx) {
3972         unsigned ByteBitOfs = ByteIdx * 8;
3973         for (unsigned BitIdx = 0; BitIdx < 8; ++BitIdx)
3974           Result->Provenance[(BitWidth - 8 - ByteBitOfs) + BitIdx] =
3975               Res->Provenance[ByteBitOfs + BitIdx];
3976       }
3977       return Result;
3978     }
3979 
3980     // Funnel 'double' shifts take 3 operands, 2 inputs and the shift
3981     // amount (modulo).
3982     // fshl(X,Y,Z): (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3983     // fshr(X,Y,Z): (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3984     if (match(V, m_FShl(m_Value(X), m_Value(Y), m_APInt(C))) ||
3985         match(V, m_FShr(m_Value(X), m_Value(Y), m_APInt(C)))) {
3986       // We can treat fshr as a fshl by flipping the modulo amount.
3987       unsigned ModAmt = C->urem(BitWidth);
3988       if (cast<IntrinsicInst>(I)->getIntrinsicID() == Intrinsic::fshr)
3989         ModAmt = BitWidth - ModAmt;
3990 
3991       // For bswap-only, limit shift amounts to whole bytes, for an early exit.
3992       if (!MatchBitReversals && (ModAmt % 8) != 0)
3993         return Result;
3994 
3995       // Check we have both sources and they are from the same provider.
3996       const auto &LHS = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
3997                                         Depth + 1, FoundRoot);
3998       if (!LHS || !LHS->Provider)
3999         return Result;
4000 
4001       const auto &RHS = collectBitParts(Y, MatchBSwaps, MatchBitReversals, BPS,
4002                                         Depth + 1, FoundRoot);
4003       if (!RHS || LHS->Provider != RHS->Provider)
4004         return Result;
4005 
4006       unsigned StartBitRHS = BitWidth - ModAmt;
4007       Result = BitPart(LHS->Provider, BitWidth);
4008       for (unsigned BitIdx = 0; BitIdx < StartBitRHS; ++BitIdx)
4009         Result->Provenance[BitIdx + ModAmt] = LHS->Provenance[BitIdx];
4010       for (unsigned BitIdx = 0; BitIdx < ModAmt; ++BitIdx)
4011         Result->Provenance[BitIdx] = RHS->Provenance[BitIdx + StartBitRHS];
4012       return Result;
4013     }
4014   }
4015 
4016   // If we've already found a root input value then we're never going to merge
4017   // these back together.
4018   if (FoundRoot)
4019     return Result;
4020 
4021   // Okay, we got to something that isn't a shift, 'or', 'and', etc. This must
4022   // be the root input value to the bswap/bitreverse.
4023   FoundRoot = true;
4024   Result = BitPart(V, BitWidth);
4025   for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)
4026     Result->Provenance[BitIdx] = BitIdx;
4027   return Result;
4028 }
4029 
4030 static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To,
4031                                           unsigned BitWidth) {
4032   if (From % 8 != To % 8)
4033     return false;
4034   // Convert from bit indices to byte indices and check for a byte reversal.
4035   From >>= 3;
4036   To >>= 3;
4037   BitWidth >>= 3;
4038   return From == BitWidth - To - 1;
4039 }
4040 
4041 static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To,
4042                                                unsigned BitWidth) {
4043   return From == BitWidth - To - 1;
4044 }
4045 
4046 bool llvm::recognizeBSwapOrBitReverseIdiom(
4047     Instruction *I, bool MatchBSwaps, bool MatchBitReversals,
4048     SmallVectorImpl<Instruction *> &InsertedInsts) {
4049   if (!match(I, m_Or(m_Value(), m_Value())) &&
4050       !match(I, m_FShl(m_Value(), m_Value(), m_Value())) &&
4051       !match(I, m_FShr(m_Value(), m_Value(), m_Value())) &&
4052       !match(I, m_BSwap(m_Value())))
4053     return false;
4054   if (!MatchBSwaps && !MatchBitReversals)
4055     return false;
4056   Type *ITy = I->getType();
4057   if (!ITy->isIntOrIntVectorTy() || ITy->getScalarSizeInBits() > 128)
4058     return false;  // Can't do integer/elements > 128 bits.
4059 
4060   // Try to find all the pieces corresponding to the bswap.
4061   bool FoundRoot = false;
4062   std::map<Value *, std::optional<BitPart>> BPS;
4063   const auto &Res =
4064       collectBitParts(I, MatchBSwaps, MatchBitReversals, BPS, 0, FoundRoot);
4065   if (!Res)
4066     return false;
4067   ArrayRef<int8_t> BitProvenance = Res->Provenance;
4068   assert(all_of(BitProvenance,
4069                 [](int8_t I) { return I == BitPart::Unset || 0 <= I; }) &&
4070          "Illegal bit provenance index");
4071 
4072   // If the upper bits are zero, then attempt to perform as a truncated op.
4073   Type *DemandedTy = ITy;
4074   if (BitProvenance.back() == BitPart::Unset) {
4075     while (!BitProvenance.empty() && BitProvenance.back() == BitPart::Unset)
4076       BitProvenance = BitProvenance.drop_back();
4077     if (BitProvenance.empty())
4078       return false; // TODO - handle null value?
4079     DemandedTy = Type::getIntNTy(I->getContext(), BitProvenance.size());
4080     if (auto *IVecTy = dyn_cast<VectorType>(ITy))
4081       DemandedTy = VectorType::get(DemandedTy, IVecTy);
4082   }
4083 
4084   // Check BitProvenance hasn't found a source larger than the result type.
4085   unsigned DemandedBW = DemandedTy->getScalarSizeInBits();
4086   if (DemandedBW > ITy->getScalarSizeInBits())
4087     return false;
4088 
4089   // Now, is the bit permutation correct for a bswap or a bitreverse? We can
4090   // only byteswap values with an even number of bytes.
4091   APInt DemandedMask = APInt::getAllOnes(DemandedBW);
4092   bool OKForBSwap = MatchBSwaps && (DemandedBW % 16) == 0;
4093   bool OKForBitReverse = MatchBitReversals;
4094   for (unsigned BitIdx = 0;
4095        (BitIdx < DemandedBW) && (OKForBSwap || OKForBitReverse); ++BitIdx) {
4096     if (BitProvenance[BitIdx] == BitPart::Unset) {
4097       DemandedMask.clearBit(BitIdx);
4098       continue;
4099     }
4100     OKForBSwap &= bitTransformIsCorrectForBSwap(BitProvenance[BitIdx], BitIdx,
4101                                                 DemandedBW);
4102     OKForBitReverse &= bitTransformIsCorrectForBitReverse(BitProvenance[BitIdx],
4103                                                           BitIdx, DemandedBW);
4104   }
4105 
4106   Intrinsic::ID Intrin;
4107   if (OKForBSwap)
4108     Intrin = Intrinsic::bswap;
4109   else if (OKForBitReverse)
4110     Intrin = Intrinsic::bitreverse;
4111   else
4112     return false;
4113 
4114   Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, DemandedTy);
4115   Value *Provider = Res->Provider;
4116 
4117   // We may need to truncate the provider.
4118   if (DemandedTy != Provider->getType()) {
4119     auto *Trunc =
4120         CastInst::CreateIntegerCast(Provider, DemandedTy, false, "trunc", I->getIterator());
4121     InsertedInsts.push_back(Trunc);
4122     Provider = Trunc;
4123   }
4124 
4125   Instruction *Result = CallInst::Create(F, Provider, "rev", I->getIterator());
4126   InsertedInsts.push_back(Result);
4127 
4128   if (!DemandedMask.isAllOnes()) {
4129     auto *Mask = ConstantInt::get(DemandedTy, DemandedMask);
4130     Result = BinaryOperator::Create(Instruction::And, Result, Mask, "mask", I->getIterator());
4131     InsertedInsts.push_back(Result);
4132   }
4133 
4134   // We may need to zeroextend back to the result type.
4135   if (ITy != Result->getType()) {
4136     auto *ExtInst = CastInst::CreateIntegerCast(Result, ITy, false, "zext", I->getIterator());
4137     InsertedInsts.push_back(ExtInst);
4138   }
4139 
4140   return true;
4141 }
4142 
4143 // CodeGen has special handling for some string functions that may replace
4144 // them with target-specific intrinsics.  Since that'd skip our interceptors
4145 // in ASan/MSan/TSan/DFSan, and thus make us miss some memory accesses,
4146 // we mark affected calls as NoBuiltin, which will disable optimization
4147 // in CodeGen.
4148 void llvm::maybeMarkSanitizerLibraryCallNoBuiltin(
4149     CallInst *CI, const TargetLibraryInfo *TLI) {
4150   Function *F = CI->getCalledFunction();
4151   LibFunc Func;
4152   if (F && !F->hasLocalLinkage() && F->hasName() &&
4153       TLI->getLibFunc(F->getName(), Func) && TLI->hasOptimizedCodeGen(Func) &&
4154       !F->doesNotAccessMemory())
4155     CI->addFnAttr(Attribute::NoBuiltin);
4156 }
4157 
4158 bool llvm::canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx) {
4159   // We can't have a PHI with a metadata type.
4160   if (I->getOperand(OpIdx)->getType()->isMetadataTy())
4161     return false;
4162 
4163   // Early exit.
4164   if (!isa<Constant>(I->getOperand(OpIdx)))
4165     return true;
4166 
4167   switch (I->getOpcode()) {
4168   default:
4169     return true;
4170   case Instruction::Call:
4171   case Instruction::Invoke: {
4172     const auto &CB = cast<CallBase>(*I);
4173 
4174     // Can't handle inline asm. Skip it.
4175     if (CB.isInlineAsm())
4176       return false;
4177 
4178     // Constant bundle operands may need to retain their constant-ness for
4179     // correctness.
4180     if (CB.isBundleOperand(OpIdx))
4181       return false;
4182 
4183     if (OpIdx < CB.arg_size()) {
4184       // Some variadic intrinsics require constants in the variadic arguments,
4185       // which currently aren't markable as immarg.
4186       if (isa<IntrinsicInst>(CB) &&
4187           OpIdx >= CB.getFunctionType()->getNumParams()) {
4188         // This is known to be OK for stackmap.
4189         return CB.getIntrinsicID() == Intrinsic::experimental_stackmap;
4190       }
4191 
4192       // gcroot is a special case, since it requires a constant argument which
4193       // isn't also required to be a simple ConstantInt.
4194       if (CB.getIntrinsicID() == Intrinsic::gcroot)
4195         return false;
4196 
4197       // Some intrinsic operands are required to be immediates.
4198       return !CB.paramHasAttr(OpIdx, Attribute::ImmArg);
4199     }
4200 
4201     // It is never allowed to replace the call argument to an intrinsic, but it
4202     // may be possible for a call.
4203     return !isa<IntrinsicInst>(CB);
4204   }
4205   case Instruction::ShuffleVector:
4206     // Shufflevector masks are constant.
4207     return OpIdx != 2;
4208   case Instruction::Switch:
4209   case Instruction::ExtractValue:
4210     // All operands apart from the first are constant.
4211     return OpIdx == 0;
4212   case Instruction::InsertValue:
4213     // All operands apart from the first and the second are constant.
4214     return OpIdx < 2;
4215   case Instruction::Alloca:
4216     // Static allocas (constant size in the entry block) are handled by
4217     // prologue/epilogue insertion so they're free anyway. We definitely don't
4218     // want to make them non-constant.
4219     return !cast<AllocaInst>(I)->isStaticAlloca();
4220   case Instruction::GetElementPtr:
4221     if (OpIdx == 0)
4222       return true;
4223     gep_type_iterator It = gep_type_begin(I);
4224     for (auto E = std::next(It, OpIdx); It != E; ++It)
4225       if (It.isStruct())
4226         return false;
4227     return true;
4228   }
4229 }
4230 
4231 Value *llvm::invertCondition(Value *Condition) {
4232   // First: Check if it's a constant
4233   if (Constant *C = dyn_cast<Constant>(Condition))
4234     return ConstantExpr::getNot(C);
4235 
4236   // Second: If the condition is already inverted, return the original value
4237   Value *NotCondition;
4238   if (match(Condition, m_Not(m_Value(NotCondition))))
4239     return NotCondition;
4240 
4241   BasicBlock *Parent = nullptr;
4242   Instruction *Inst = dyn_cast<Instruction>(Condition);
4243   if (Inst)
4244     Parent = Inst->getParent();
4245   else if (Argument *Arg = dyn_cast<Argument>(Condition))
4246     Parent = &Arg->getParent()->getEntryBlock();
4247   assert(Parent && "Unsupported condition to invert");
4248 
4249   // Third: Check all the users for an invert
4250   for (User *U : Condition->users())
4251     if (Instruction *I = dyn_cast<Instruction>(U))
4252       if (I->getParent() == Parent && match(I, m_Not(m_Specific(Condition))))
4253         return I;
4254 
4255   // Last option: Create a new instruction
4256   auto *Inverted =
4257       BinaryOperator::CreateNot(Condition, Condition->getName() + ".inv");
4258   if (Inst && !isa<PHINode>(Inst))
4259     Inverted->insertAfter(Inst);
4260   else
4261     Inverted->insertBefore(&*Parent->getFirstInsertionPt());
4262   return Inverted;
4263 }
4264 
4265 bool llvm::inferAttributesFromOthers(Function &F) {
4266   // Note: We explicitly check for attributes rather than using cover functions
4267   // because some of the cover functions include the logic being implemented.
4268 
4269   bool Changed = false;
4270   // readnone + not convergent implies nosync
4271   if (!F.hasFnAttribute(Attribute::NoSync) &&
4272       F.doesNotAccessMemory() && !F.isConvergent()) {
4273     F.setNoSync();
4274     Changed = true;
4275   }
4276 
4277   // readonly implies nofree
4278   if (!F.hasFnAttribute(Attribute::NoFree) && F.onlyReadsMemory()) {
4279     F.setDoesNotFreeMemory();
4280     Changed = true;
4281   }
4282 
4283   // willreturn implies mustprogress
4284   if (!F.hasFnAttribute(Attribute::MustProgress) && F.willReturn()) {
4285     F.setMustProgress();
4286     Changed = true;
4287   }
4288 
4289   // TODO: There are a bunch of cases of restrictive memory effects we
4290   // can infer by inspecting arguments of argmemonly-ish functions.
4291 
4292   return Changed;
4293 }
4294