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