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