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