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