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