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