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