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