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