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