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