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 = 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 and zexts are irrelevant for debug info.
1702     if (CI->isNoopCast(DL) || isa<ZExtInst>(&I))
1703       return SrcDIExpr;
1704 
1705     Type *Type = CI->getType();
1706     // Casts other than Trunc or SExt to scalar types cannot be salvaged.
1707     if (Type->isVectorTy() || (!isa<TruncInst>(&I) && !isa<SExtInst>(&I)))
1708       return nullptr;
1709 
1710     Value *FromValue = CI->getOperand(0);
1711     unsigned FromTypeBitSize = FromValue->getType()->getScalarSizeInBits();
1712     unsigned ToTypeBitSize = Type->getScalarSizeInBits();
1713 
1714     return applyOps(DIExpression::getExtOps(FromTypeBitSize, ToTypeBitSize,
1715                                             isa<SExtInst>(&I)));
1716   }
1717 
1718   if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1719     unsigned BitWidth =
1720         M.getDataLayout().getIndexSizeInBits(GEP->getPointerAddressSpace());
1721     // Rewrite a constant GEP into a DIExpression.
1722     APInt Offset(BitWidth, 0);
1723     if (GEP->accumulateConstantOffset(M.getDataLayout(), Offset)) {
1724       return applyOffset(Offset.getSExtValue());
1725     } else {
1726       return nullptr;
1727     }
1728   } else if (auto *BI = dyn_cast<BinaryOperator>(&I)) {
1729     // Rewrite binary operations with constant integer operands.
1730     auto *ConstInt = dyn_cast<ConstantInt>(I.getOperand(1));
1731     if (!ConstInt || ConstInt->getBitWidth() > 64)
1732       return nullptr;
1733 
1734     uint64_t Val = ConstInt->getSExtValue();
1735     switch (BI->getOpcode()) {
1736     case Instruction::Add:
1737       return applyOffset(Val);
1738     case Instruction::Sub:
1739       return applyOffset(-int64_t(Val));
1740     case Instruction::Mul:
1741       return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_mul});
1742     case Instruction::SDiv:
1743       return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_div});
1744     case Instruction::SRem:
1745       return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_mod});
1746     case Instruction::Or:
1747       return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_or});
1748     case Instruction::And:
1749       return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_and});
1750     case Instruction::Xor:
1751       return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_xor});
1752     case Instruction::Shl:
1753       return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shl});
1754     case Instruction::LShr:
1755       return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shr});
1756     case Instruction::AShr:
1757       return applyOps({dwarf::DW_OP_constu, Val, dwarf::DW_OP_shra});
1758     default:
1759       // TODO: Salvage constants from each kind of binop we know about.
1760       return nullptr;
1761     }
1762     // *Not* to do: we should not attempt to salvage load instructions,
1763     // because the validity and lifetime of a dbg.value containing
1764     // DW_OP_deref becomes difficult to analyze. See PR40628 for examples.
1765   }
1766   return nullptr;
1767 }
1768 
1769 /// A replacement for a dbg.value expression.
1770 using DbgValReplacement = Optional<DIExpression *>;
1771 
1772 /// Point debug users of \p From to \p To using exprs given by \p RewriteExpr,
1773 /// possibly moving/undefing users to prevent use-before-def. Returns true if
1774 /// changes are made.
1775 static bool rewriteDebugUsers(
1776     Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT,
1777     function_ref<DbgValReplacement(DbgVariableIntrinsic &DII)> RewriteExpr) {
1778   // Find debug users of From.
1779   SmallVector<DbgVariableIntrinsic *, 1> Users;
1780   findDbgUsers(Users, &From);
1781   if (Users.empty())
1782     return false;
1783 
1784   // Prevent use-before-def of To.
1785   bool Changed = false;
1786   SmallPtrSet<DbgVariableIntrinsic *, 1> UndefOrSalvage;
1787   if (isa<Instruction>(&To)) {
1788     bool DomPointAfterFrom = From.getNextNonDebugInstruction() == &DomPoint;
1789 
1790     for (auto *DII : Users) {
1791       // It's common to see a debug user between From and DomPoint. Move it
1792       // after DomPoint to preserve the variable update without any reordering.
1793       if (DomPointAfterFrom && DII->getNextNonDebugInstruction() == &DomPoint) {
1794         LLVM_DEBUG(dbgs() << "MOVE:  " << *DII << '\n');
1795         DII->moveAfter(&DomPoint);
1796         Changed = true;
1797 
1798       // Users which otherwise aren't dominated by the replacement value must
1799       // be salvaged or deleted.
1800       } else if (!DT.dominates(&DomPoint, DII)) {
1801         UndefOrSalvage.insert(DII);
1802       }
1803     }
1804   }
1805 
1806   // Update debug users without use-before-def risk.
1807   for (auto *DII : Users) {
1808     if (UndefOrSalvage.count(DII))
1809       continue;
1810 
1811     LLVMContext &Ctx = DII->getContext();
1812     DbgValReplacement DVR = RewriteExpr(*DII);
1813     if (!DVR)
1814       continue;
1815 
1816     DII->setOperand(0, wrapValueInMetadata(Ctx, &To));
1817     DII->setOperand(2, MetadataAsValue::get(Ctx, *DVR));
1818     LLVM_DEBUG(dbgs() << "REWRITE:  " << *DII << '\n');
1819     Changed = true;
1820   }
1821 
1822   if (!UndefOrSalvage.empty()) {
1823     // Try to salvage the remaining debug users.
1824     salvageDebugInfoOrMarkUndef(From);
1825     Changed = true;
1826   }
1827 
1828   return Changed;
1829 }
1830 
1831 /// Check if a bitcast between a value of type \p FromTy to type \p ToTy would
1832 /// losslessly preserve the bits and semantics of the value. This predicate is
1833 /// symmetric, i.e swapping \p FromTy and \p ToTy should give the same result.
1834 ///
1835 /// Note that Type::canLosslesslyBitCastTo is not suitable here because it
1836 /// allows semantically unequivalent bitcasts, such as <2 x i64> -> <4 x i32>,
1837 /// and also does not allow lossless pointer <-> integer conversions.
1838 static bool isBitCastSemanticsPreserving(const DataLayout &DL, Type *FromTy,
1839                                          Type *ToTy) {
1840   // Trivially compatible types.
1841   if (FromTy == ToTy)
1842     return true;
1843 
1844   // Handle compatible pointer <-> integer conversions.
1845   if (FromTy->isIntOrPtrTy() && ToTy->isIntOrPtrTy()) {
1846     bool SameSize = DL.getTypeSizeInBits(FromTy) == DL.getTypeSizeInBits(ToTy);
1847     bool LosslessConversion = !DL.isNonIntegralPointerType(FromTy) &&
1848                               !DL.isNonIntegralPointerType(ToTy);
1849     return SameSize && LosslessConversion;
1850   }
1851 
1852   // TODO: This is not exhaustive.
1853   return false;
1854 }
1855 
1856 bool llvm::replaceAllDbgUsesWith(Instruction &From, Value &To,
1857                                  Instruction &DomPoint, DominatorTree &DT) {
1858   // Exit early if From has no debug users.
1859   if (!From.isUsedByMetadata())
1860     return false;
1861 
1862   assert(&From != &To && "Can't replace something with itself");
1863 
1864   Type *FromTy = From.getType();
1865   Type *ToTy = To.getType();
1866 
1867   auto Identity = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {
1868     return DII.getExpression();
1869   };
1870 
1871   // Handle no-op conversions.
1872   Module &M = *From.getModule();
1873   const DataLayout &DL = M.getDataLayout();
1874   if (isBitCastSemanticsPreserving(DL, FromTy, ToTy))
1875     return rewriteDebugUsers(From, To, DomPoint, DT, Identity);
1876 
1877   // Handle integer-to-integer widening and narrowing.
1878   // FIXME: Use DW_OP_convert when it's available everywhere.
1879   if (FromTy->isIntegerTy() && ToTy->isIntegerTy()) {
1880     uint64_t FromBits = FromTy->getPrimitiveSizeInBits();
1881     uint64_t ToBits = ToTy->getPrimitiveSizeInBits();
1882     assert(FromBits != ToBits && "Unexpected no-op conversion");
1883 
1884     // When the width of the result grows, assume that a debugger will only
1885     // access the low `FromBits` bits when inspecting the source variable.
1886     if (FromBits < ToBits)
1887       return rewriteDebugUsers(From, To, DomPoint, DT, Identity);
1888 
1889     // The width of the result has shrunk. Use sign/zero extension to describe
1890     // the source variable's high bits.
1891     auto SignOrZeroExt = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {
1892       DILocalVariable *Var = DII.getVariable();
1893 
1894       // Without knowing signedness, sign/zero extension isn't possible.
1895       auto Signedness = Var->getSignedness();
1896       if (!Signedness)
1897         return None;
1898 
1899       bool Signed = *Signedness == DIBasicType::Signedness::Signed;
1900       return DIExpression::appendExt(DII.getExpression(), ToBits, FromBits,
1901                                      Signed);
1902     };
1903     return rewriteDebugUsers(From, To, DomPoint, DT, SignOrZeroExt);
1904   }
1905 
1906   // TODO: Floating-point conversions, vectors.
1907   return false;
1908 }
1909 
1910 unsigned llvm::removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB) {
1911   unsigned NumDeadInst = 0;
1912   // Delete the instructions backwards, as it has a reduced likelihood of
1913   // having to update as many def-use and use-def chains.
1914   Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
1915   while (EndInst != &BB->front()) {
1916     // Delete the next to last instruction.
1917     Instruction *Inst = &*--EndInst->getIterator();
1918     if (!Inst->use_empty() && !Inst->getType()->isTokenTy())
1919       Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
1920     if (Inst->isEHPad() || Inst->getType()->isTokenTy()) {
1921       EndInst = Inst;
1922       continue;
1923     }
1924     if (!isa<DbgInfoIntrinsic>(Inst))
1925       ++NumDeadInst;
1926     Inst->eraseFromParent();
1927   }
1928   return NumDeadInst;
1929 }
1930 
1931 unsigned llvm::changeToUnreachable(Instruction *I, bool UseLLVMTrap,
1932                                    bool PreserveLCSSA, DomTreeUpdater *DTU,
1933                                    MemorySSAUpdater *MSSAU) {
1934   BasicBlock *BB = I->getParent();
1935   std::vector <DominatorTree::UpdateType> Updates;
1936 
1937   if (MSSAU)
1938     MSSAU->changeToUnreachable(I);
1939 
1940   // Loop over all of the successors, removing BB's entry from any PHI
1941   // nodes.
1942   if (DTU)
1943     Updates.reserve(BB->getTerminator()->getNumSuccessors());
1944   for (BasicBlock *Successor : successors(BB)) {
1945     Successor->removePredecessor(BB, PreserveLCSSA);
1946     if (DTU)
1947       Updates.push_back({DominatorTree::Delete, BB, Successor});
1948   }
1949   // Insert a call to llvm.trap right before this.  This turns the undefined
1950   // behavior into a hard fail instead of falling through into random code.
1951   if (UseLLVMTrap) {
1952     Function *TrapFn =
1953       Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap);
1954     CallInst *CallTrap = CallInst::Create(TrapFn, "", I);
1955     CallTrap->setDebugLoc(I->getDebugLoc());
1956   }
1957   auto *UI = new UnreachableInst(I->getContext(), I);
1958   UI->setDebugLoc(I->getDebugLoc());
1959 
1960   // All instructions after this are dead.
1961   unsigned NumInstrsRemoved = 0;
1962   BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end();
1963   while (BBI != BBE) {
1964     if (!BBI->use_empty())
1965       BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
1966     BB->getInstList().erase(BBI++);
1967     ++NumInstrsRemoved;
1968   }
1969   if (DTU)
1970     DTU->applyUpdatesPermissive(Updates);
1971   return NumInstrsRemoved;
1972 }
1973 
1974 CallInst *llvm::createCallMatchingInvoke(InvokeInst *II) {
1975   SmallVector<Value *, 8> Args(II->arg_begin(), II->arg_end());
1976   SmallVector<OperandBundleDef, 1> OpBundles;
1977   II->getOperandBundlesAsDefs(OpBundles);
1978   CallInst *NewCall = CallInst::Create(II->getFunctionType(),
1979                                        II->getCalledOperand(), Args, OpBundles);
1980   NewCall->setCallingConv(II->getCallingConv());
1981   NewCall->setAttributes(II->getAttributes());
1982   NewCall->setDebugLoc(II->getDebugLoc());
1983   NewCall->copyMetadata(*II);
1984   return NewCall;
1985 }
1986 
1987 /// changeToCall - Convert the specified invoke into a normal call.
1988 void llvm::changeToCall(InvokeInst *II, DomTreeUpdater *DTU) {
1989   CallInst *NewCall = createCallMatchingInvoke(II);
1990   NewCall->takeName(II);
1991   NewCall->insertBefore(II);
1992   II->replaceAllUsesWith(NewCall);
1993 
1994   // Follow the call by a branch to the normal destination.
1995   BasicBlock *NormalDestBB = II->getNormalDest();
1996   BranchInst::Create(NormalDestBB, II);
1997 
1998   // Update PHI nodes in the unwind destination
1999   BasicBlock *BB = II->getParent();
2000   BasicBlock *UnwindDestBB = II->getUnwindDest();
2001   UnwindDestBB->removePredecessor(BB);
2002   II->eraseFromParent();
2003   if (DTU)
2004     DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, UnwindDestBB}});
2005 }
2006 
2007 BasicBlock *llvm::changeToInvokeAndSplitBasicBlock(CallInst *CI,
2008                                                    BasicBlock *UnwindEdge) {
2009   BasicBlock *BB = CI->getParent();
2010 
2011   // Convert this function call into an invoke instruction.  First, split the
2012   // basic block.
2013   BasicBlock *Split =
2014       BB->splitBasicBlock(CI->getIterator(), CI->getName() + ".noexc");
2015 
2016   // Delete the unconditional branch inserted by splitBasicBlock
2017   BB->getInstList().pop_back();
2018 
2019   // Create the new invoke instruction.
2020   SmallVector<Value *, 8> InvokeArgs(CI->arg_begin(), CI->arg_end());
2021   SmallVector<OperandBundleDef, 1> OpBundles;
2022 
2023   CI->getOperandBundlesAsDefs(OpBundles);
2024 
2025   // Note: we're round tripping operand bundles through memory here, and that
2026   // can potentially be avoided with a cleverer API design that we do not have
2027   // as of this time.
2028 
2029   InvokeInst *II =
2030       InvokeInst::Create(CI->getFunctionType(), CI->getCalledOperand(), Split,
2031                          UnwindEdge, InvokeArgs, OpBundles, CI->getName(), BB);
2032   II->setDebugLoc(CI->getDebugLoc());
2033   II->setCallingConv(CI->getCallingConv());
2034   II->setAttributes(CI->getAttributes());
2035 
2036   // Make sure that anything using the call now uses the invoke!  This also
2037   // updates the CallGraph if present, because it uses a WeakTrackingVH.
2038   CI->replaceAllUsesWith(II);
2039 
2040   // Delete the original call
2041   Split->getInstList().pop_front();
2042   return Split;
2043 }
2044 
2045 static bool markAliveBlocks(Function &F,
2046                             SmallPtrSetImpl<BasicBlock *> &Reachable,
2047                             DomTreeUpdater *DTU = nullptr) {
2048   SmallVector<BasicBlock*, 128> Worklist;
2049   BasicBlock *BB = &F.front();
2050   Worklist.push_back(BB);
2051   Reachable.insert(BB);
2052   bool Changed = false;
2053   do {
2054     BB = Worklist.pop_back_val();
2055 
2056     // Do a quick scan of the basic block, turning any obviously unreachable
2057     // instructions into LLVM unreachable insts.  The instruction combining pass
2058     // canonicalizes unreachable insts into stores to null or undef.
2059     for (Instruction &I : *BB) {
2060       if (auto *CI = dyn_cast<CallInst>(&I)) {
2061         Value *Callee = CI->getCalledOperand();
2062         // Handle intrinsic calls.
2063         if (Function *F = dyn_cast<Function>(Callee)) {
2064           auto IntrinsicID = F->getIntrinsicID();
2065           // Assumptions that are known to be false are equivalent to
2066           // unreachable. Also, if the condition is undefined, then we make the
2067           // choice most beneficial to the optimizer, and choose that to also be
2068           // unreachable.
2069           if (IntrinsicID == Intrinsic::assume) {
2070             if (match(CI->getArgOperand(0), m_CombineOr(m_Zero(), m_Undef()))) {
2071               // Don't insert a call to llvm.trap right before the unreachable.
2072               changeToUnreachable(CI, false, false, DTU);
2073               Changed = true;
2074               break;
2075             }
2076           } else if (IntrinsicID == Intrinsic::experimental_guard) {
2077             // A call to the guard intrinsic bails out of the current
2078             // compilation unit if the predicate passed to it is false. If the
2079             // predicate is a constant false, then we know the guard will bail
2080             // out of the current compile unconditionally, so all code following
2081             // it is dead.
2082             //
2083             // Note: unlike in llvm.assume, it is not "obviously profitable" for
2084             // guards to treat `undef` as `false` since a guard on `undef` can
2085             // still be useful for widening.
2086             if (match(CI->getArgOperand(0), m_Zero()))
2087               if (!isa<UnreachableInst>(CI->getNextNode())) {
2088                 changeToUnreachable(CI->getNextNode(), /*UseLLVMTrap=*/false,
2089                                     false, DTU);
2090                 Changed = true;
2091                 break;
2092               }
2093           }
2094         } else if ((isa<ConstantPointerNull>(Callee) &&
2095                     !NullPointerIsDefined(CI->getFunction())) ||
2096                    isa<UndefValue>(Callee)) {
2097           changeToUnreachable(CI, /*UseLLVMTrap=*/false, false, DTU);
2098           Changed = true;
2099           break;
2100         }
2101         if (CI->doesNotReturn() && !CI->isMustTailCall()) {
2102           // If we found a call to a no-return function, insert an unreachable
2103           // instruction after it.  Make sure there isn't *already* one there
2104           // though.
2105           if (!isa<UnreachableInst>(CI->getNextNode())) {
2106             // Don't insert a call to llvm.trap right before the unreachable.
2107             changeToUnreachable(CI->getNextNode(), false, false, DTU);
2108             Changed = true;
2109           }
2110           break;
2111         }
2112       } else if (auto *SI = dyn_cast<StoreInst>(&I)) {
2113         // Store to undef and store to null are undefined and used to signal
2114         // that they should be changed to unreachable by passes that can't
2115         // modify the CFG.
2116 
2117         // Don't touch volatile stores.
2118         if (SI->isVolatile()) continue;
2119 
2120         Value *Ptr = SI->getOperand(1);
2121 
2122         if (isa<UndefValue>(Ptr) ||
2123             (isa<ConstantPointerNull>(Ptr) &&
2124              !NullPointerIsDefined(SI->getFunction(),
2125                                    SI->getPointerAddressSpace()))) {
2126           changeToUnreachable(SI, true, false, DTU);
2127           Changed = true;
2128           break;
2129         }
2130       }
2131     }
2132 
2133     Instruction *Terminator = BB->getTerminator();
2134     if (auto *II = dyn_cast<InvokeInst>(Terminator)) {
2135       // Turn invokes that call 'nounwind' functions into ordinary calls.
2136       Value *Callee = II->getCalledOperand();
2137       if ((isa<ConstantPointerNull>(Callee) &&
2138            !NullPointerIsDefined(BB->getParent())) ||
2139           isa<UndefValue>(Callee)) {
2140         changeToUnreachable(II, true, false, DTU);
2141         Changed = true;
2142       } else if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(&F)) {
2143         if (II->use_empty() && II->onlyReadsMemory()) {
2144           // jump to the normal destination branch.
2145           BasicBlock *NormalDestBB = II->getNormalDest();
2146           BasicBlock *UnwindDestBB = II->getUnwindDest();
2147           BranchInst::Create(NormalDestBB, II);
2148           UnwindDestBB->removePredecessor(II->getParent());
2149           II->eraseFromParent();
2150           if (DTU)
2151             DTU->applyUpdatesPermissive(
2152                 {{DominatorTree::Delete, BB, UnwindDestBB}});
2153         } else
2154           changeToCall(II, DTU);
2155         Changed = true;
2156       }
2157     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) {
2158       // Remove catchpads which cannot be reached.
2159       struct CatchPadDenseMapInfo {
2160         static CatchPadInst *getEmptyKey() {
2161           return DenseMapInfo<CatchPadInst *>::getEmptyKey();
2162         }
2163 
2164         static CatchPadInst *getTombstoneKey() {
2165           return DenseMapInfo<CatchPadInst *>::getTombstoneKey();
2166         }
2167 
2168         static unsigned getHashValue(CatchPadInst *CatchPad) {
2169           return static_cast<unsigned>(hash_combine_range(
2170               CatchPad->value_op_begin(), CatchPad->value_op_end()));
2171         }
2172 
2173         static bool isEqual(CatchPadInst *LHS, CatchPadInst *RHS) {
2174           if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
2175               RHS == getEmptyKey() || RHS == getTombstoneKey())
2176             return LHS == RHS;
2177           return LHS->isIdenticalTo(RHS);
2178         }
2179       };
2180 
2181       // Set of unique CatchPads.
2182       SmallDenseMap<CatchPadInst *, detail::DenseSetEmpty, 4,
2183                     CatchPadDenseMapInfo, detail::DenseSetPair<CatchPadInst *>>
2184           HandlerSet;
2185       detail::DenseSetEmpty Empty;
2186       for (CatchSwitchInst::handler_iterator I = CatchSwitch->handler_begin(),
2187                                              E = CatchSwitch->handler_end();
2188            I != E; ++I) {
2189         BasicBlock *HandlerBB = *I;
2190         auto *CatchPad = cast<CatchPadInst>(HandlerBB->getFirstNonPHI());
2191         if (!HandlerSet.insert({CatchPad, Empty}).second) {
2192           CatchSwitch->removeHandler(I);
2193           --I;
2194           --E;
2195           Changed = true;
2196         }
2197       }
2198     }
2199 
2200     Changed |= ConstantFoldTerminator(BB, true, nullptr, DTU);
2201     for (BasicBlock *Successor : successors(BB))
2202       if (Reachable.insert(Successor).second)
2203         Worklist.push_back(Successor);
2204   } while (!Worklist.empty());
2205   return Changed;
2206 }
2207 
2208 void llvm::removeUnwindEdge(BasicBlock *BB, DomTreeUpdater *DTU) {
2209   Instruction *TI = BB->getTerminator();
2210 
2211   if (auto *II = dyn_cast<InvokeInst>(TI)) {
2212     changeToCall(II, DTU);
2213     return;
2214   }
2215 
2216   Instruction *NewTI;
2217   BasicBlock *UnwindDest;
2218 
2219   if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
2220     NewTI = CleanupReturnInst::Create(CRI->getCleanupPad(), nullptr, CRI);
2221     UnwindDest = CRI->getUnwindDest();
2222   } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
2223     auto *NewCatchSwitch = CatchSwitchInst::Create(
2224         CatchSwitch->getParentPad(), nullptr, CatchSwitch->getNumHandlers(),
2225         CatchSwitch->getName(), CatchSwitch);
2226     for (BasicBlock *PadBB : CatchSwitch->handlers())
2227       NewCatchSwitch->addHandler(PadBB);
2228 
2229     NewTI = NewCatchSwitch;
2230     UnwindDest = CatchSwitch->getUnwindDest();
2231   } else {
2232     llvm_unreachable("Could not find unwind successor");
2233   }
2234 
2235   NewTI->takeName(TI);
2236   NewTI->setDebugLoc(TI->getDebugLoc());
2237   UnwindDest->removePredecessor(BB);
2238   TI->replaceAllUsesWith(NewTI);
2239   TI->eraseFromParent();
2240   if (DTU)
2241     DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, UnwindDest}});
2242 }
2243 
2244 /// removeUnreachableBlocks - Remove blocks that are not reachable, even
2245 /// if they are in a dead cycle.  Return true if a change was made, false
2246 /// otherwise.
2247 bool llvm::removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU,
2248                                    MemorySSAUpdater *MSSAU) {
2249   SmallPtrSet<BasicBlock *, 16> Reachable;
2250   bool Changed = markAliveBlocks(F, Reachable, DTU);
2251 
2252   // If there are unreachable blocks in the CFG...
2253   if (Reachable.size() == F.size())
2254     return Changed;
2255 
2256   assert(Reachable.size() < F.size());
2257   NumRemoved += F.size() - Reachable.size();
2258 
2259   SmallSetVector<BasicBlock *, 8> DeadBlockSet;
2260   for (BasicBlock &BB : F) {
2261     // Skip reachable basic blocks
2262     if (Reachable.find(&BB) != Reachable.end())
2263       continue;
2264     DeadBlockSet.insert(&BB);
2265   }
2266 
2267   if (MSSAU)
2268     MSSAU->removeBlocks(DeadBlockSet);
2269 
2270   // Loop over all of the basic blocks that are not reachable, dropping all of
2271   // their internal references. Update DTU if available.
2272   std::vector<DominatorTree::UpdateType> Updates;
2273   for (auto *BB : DeadBlockSet) {
2274     for (BasicBlock *Successor : successors(BB)) {
2275       if (!DeadBlockSet.count(Successor))
2276         Successor->removePredecessor(BB);
2277       if (DTU)
2278         Updates.push_back({DominatorTree::Delete, BB, Successor});
2279     }
2280     BB->dropAllReferences();
2281     if (DTU) {
2282       Instruction *TI = BB->getTerminator();
2283       assert(TI && "Basic block should have a terminator");
2284       // Terminators like invoke can have users. We have to replace their users,
2285       // before removing them.
2286       if (!TI->use_empty())
2287         TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
2288       TI->eraseFromParent();
2289       new UnreachableInst(BB->getContext(), BB);
2290       assert(succ_empty(BB) && "The successor list of BB isn't empty before "
2291                                "applying corresponding DTU updates.");
2292     }
2293   }
2294 
2295   if (DTU) {
2296     DTU->applyUpdatesPermissive(Updates);
2297     bool Deleted = false;
2298     for (auto *BB : DeadBlockSet) {
2299       if (DTU->isBBPendingDeletion(BB))
2300         --NumRemoved;
2301       else
2302         Deleted = true;
2303       DTU->deleteBB(BB);
2304     }
2305     if (!Deleted)
2306       return false;
2307   } else {
2308     for (auto *BB : DeadBlockSet)
2309       BB->eraseFromParent();
2310   }
2311 
2312   return true;
2313 }
2314 
2315 void llvm::combineMetadata(Instruction *K, const Instruction *J,
2316                            ArrayRef<unsigned> KnownIDs, bool DoesKMove) {
2317   SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
2318   K->dropUnknownNonDebugMetadata(KnownIDs);
2319   K->getAllMetadataOtherThanDebugLoc(Metadata);
2320   for (const auto &MD : Metadata) {
2321     unsigned Kind = MD.first;
2322     MDNode *JMD = J->getMetadata(Kind);
2323     MDNode *KMD = MD.second;
2324 
2325     switch (Kind) {
2326       default:
2327         K->setMetadata(Kind, nullptr); // Remove unknown metadata
2328         break;
2329       case LLVMContext::MD_dbg:
2330         llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
2331       case LLVMContext::MD_tbaa:
2332         K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
2333         break;
2334       case LLVMContext::MD_alias_scope:
2335         K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD));
2336         break;
2337       case LLVMContext::MD_noalias:
2338       case LLVMContext::MD_mem_parallel_loop_access:
2339         K->setMetadata(Kind, MDNode::intersect(JMD, KMD));
2340         break;
2341       case LLVMContext::MD_access_group:
2342         K->setMetadata(LLVMContext::MD_access_group,
2343                        intersectAccessGroups(K, J));
2344         break;
2345       case LLVMContext::MD_range:
2346 
2347         // If K does move, use most generic range. Otherwise keep the range of
2348         // K.
2349         if (DoesKMove)
2350           // FIXME: If K does move, we should drop the range info and nonnull.
2351           //        Currently this function is used with DoesKMove in passes
2352           //        doing hoisting/sinking and the current behavior of using the
2353           //        most generic range is correct in those cases.
2354           K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD));
2355         break;
2356       case LLVMContext::MD_fpmath:
2357         K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
2358         break;
2359       case LLVMContext::MD_invariant_load:
2360         // Only set the !invariant.load if it is present in both instructions.
2361         K->setMetadata(Kind, JMD);
2362         break;
2363       case LLVMContext::MD_nonnull:
2364         // If K does move, keep nonull if it is present in both instructions.
2365         if (DoesKMove)
2366           K->setMetadata(Kind, JMD);
2367         break;
2368       case LLVMContext::MD_invariant_group:
2369         // Preserve !invariant.group in K.
2370         break;
2371       case LLVMContext::MD_align:
2372         K->setMetadata(Kind,
2373           MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
2374         break;
2375       case LLVMContext::MD_dereferenceable:
2376       case LLVMContext::MD_dereferenceable_or_null:
2377         K->setMetadata(Kind,
2378           MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
2379         break;
2380       case LLVMContext::MD_preserve_access_index:
2381         // Preserve !preserve.access.index in K.
2382         break;
2383     }
2384   }
2385   // Set !invariant.group from J if J has it. If both instructions have it
2386   // then we will just pick it from J - even when they are different.
2387   // Also make sure that K is load or store - f.e. combining bitcast with load
2388   // could produce bitcast with invariant.group metadata, which is invalid.
2389   // FIXME: we should try to preserve both invariant.group md if they are
2390   // different, but right now instruction can only have one invariant.group.
2391   if (auto *JMD = J->getMetadata(LLVMContext::MD_invariant_group))
2392     if (isa<LoadInst>(K) || isa<StoreInst>(K))
2393       K->setMetadata(LLVMContext::MD_invariant_group, JMD);
2394 }
2395 
2396 void llvm::combineMetadataForCSE(Instruction *K, const Instruction *J,
2397                                  bool KDominatesJ) {
2398   unsigned KnownIDs[] = {
2399       LLVMContext::MD_tbaa,            LLVMContext::MD_alias_scope,
2400       LLVMContext::MD_noalias,         LLVMContext::MD_range,
2401       LLVMContext::MD_invariant_load,  LLVMContext::MD_nonnull,
2402       LLVMContext::MD_invariant_group, LLVMContext::MD_align,
2403       LLVMContext::MD_dereferenceable,
2404       LLVMContext::MD_dereferenceable_or_null,
2405       LLVMContext::MD_access_group,    LLVMContext::MD_preserve_access_index};
2406   combineMetadata(K, J, KnownIDs, KDominatesJ);
2407 }
2408 
2409 void llvm::copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source) {
2410   SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
2411   Source.getAllMetadata(MD);
2412   MDBuilder MDB(Dest.getContext());
2413   Type *NewType = Dest.getType();
2414   const DataLayout &DL = Source.getModule()->getDataLayout();
2415   for (const auto &MDPair : MD) {
2416     unsigned ID = MDPair.first;
2417     MDNode *N = MDPair.second;
2418     // Note, essentially every kind of metadata should be preserved here! This
2419     // routine is supposed to clone a load instruction changing *only its type*.
2420     // The only metadata it makes sense to drop is metadata which is invalidated
2421     // when the pointer type changes. This should essentially never be the case
2422     // in LLVM, but we explicitly switch over only known metadata to be
2423     // conservatively correct. If you are adding metadata to LLVM which pertains
2424     // to loads, you almost certainly want to add it here.
2425     switch (ID) {
2426     case LLVMContext::MD_dbg:
2427     case LLVMContext::MD_tbaa:
2428     case LLVMContext::MD_prof:
2429     case LLVMContext::MD_fpmath:
2430     case LLVMContext::MD_tbaa_struct:
2431     case LLVMContext::MD_invariant_load:
2432     case LLVMContext::MD_alias_scope:
2433     case LLVMContext::MD_noalias:
2434     case LLVMContext::MD_nontemporal:
2435     case LLVMContext::MD_mem_parallel_loop_access:
2436     case LLVMContext::MD_access_group:
2437       // All of these directly apply.
2438       Dest.setMetadata(ID, N);
2439       break;
2440 
2441     case LLVMContext::MD_nonnull:
2442       copyNonnullMetadata(Source, N, Dest);
2443       break;
2444 
2445     case LLVMContext::MD_align:
2446     case LLVMContext::MD_dereferenceable:
2447     case LLVMContext::MD_dereferenceable_or_null:
2448       // These only directly apply if the new type is also a pointer.
2449       if (NewType->isPointerTy())
2450         Dest.setMetadata(ID, N);
2451       break;
2452 
2453     case LLVMContext::MD_range:
2454       copyRangeMetadata(DL, Source, N, Dest);
2455       break;
2456     }
2457   }
2458 }
2459 
2460 void llvm::patchReplacementInstruction(Instruction *I, Value *Repl) {
2461   auto *ReplInst = dyn_cast<Instruction>(Repl);
2462   if (!ReplInst)
2463     return;
2464 
2465   // Patch the replacement so that it is not more restrictive than the value
2466   // being replaced.
2467   // Note that if 'I' is a load being replaced by some operation,
2468   // for example, by an arithmetic operation, then andIRFlags()
2469   // would just erase all math flags from the original arithmetic
2470   // operation, which is clearly not wanted and not needed.
2471   if (!isa<LoadInst>(I))
2472     ReplInst->andIRFlags(I);
2473 
2474   // FIXME: If both the original and replacement value are part of the
2475   // same control-flow region (meaning that the execution of one
2476   // guarantees the execution of the other), then we can combine the
2477   // noalias scopes here and do better than the general conservative
2478   // answer used in combineMetadata().
2479 
2480   // In general, GVN unifies expressions over different control-flow
2481   // regions, and so we need a conservative combination of the noalias
2482   // scopes.
2483   static const unsigned KnownIDs[] = {
2484       LLVMContext::MD_tbaa,            LLVMContext::MD_alias_scope,
2485       LLVMContext::MD_noalias,         LLVMContext::MD_range,
2486       LLVMContext::MD_fpmath,          LLVMContext::MD_invariant_load,
2487       LLVMContext::MD_invariant_group, LLVMContext::MD_nonnull,
2488       LLVMContext::MD_access_group,    LLVMContext::MD_preserve_access_index};
2489   combineMetadata(ReplInst, I, KnownIDs, false);
2490 }
2491 
2492 template <typename RootType, typename DominatesFn>
2493 static unsigned replaceDominatedUsesWith(Value *From, Value *To,
2494                                          const RootType &Root,
2495                                          const DominatesFn &Dominates) {
2496   assert(From->getType() == To->getType());
2497 
2498   unsigned Count = 0;
2499   for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
2500        UI != UE;) {
2501     Use &U = *UI++;
2502     if (!Dominates(Root, U))
2503       continue;
2504     U.set(To);
2505     LLVM_DEBUG(dbgs() << "Replace dominated use of '" << From->getName()
2506                       << "' as " << *To << " in " << *U << "\n");
2507     ++Count;
2508   }
2509   return Count;
2510 }
2511 
2512 unsigned llvm::replaceNonLocalUsesWith(Instruction *From, Value *To) {
2513    assert(From->getType() == To->getType());
2514    auto *BB = From->getParent();
2515    unsigned Count = 0;
2516 
2517   for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
2518        UI != UE;) {
2519     Use &U = *UI++;
2520     auto *I = cast<Instruction>(U.getUser());
2521     if (I->getParent() == BB)
2522       continue;
2523     U.set(To);
2524     ++Count;
2525   }
2526   return Count;
2527 }
2528 
2529 unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
2530                                         DominatorTree &DT,
2531                                         const BasicBlockEdge &Root) {
2532   auto Dominates = [&DT](const BasicBlockEdge &Root, const Use &U) {
2533     return DT.dominates(Root, U);
2534   };
2535   return ::replaceDominatedUsesWith(From, To, Root, Dominates);
2536 }
2537 
2538 unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
2539                                         DominatorTree &DT,
2540                                         const BasicBlock *BB) {
2541   auto ProperlyDominates = [&DT](const BasicBlock *BB, const Use &U) {
2542     auto *I = cast<Instruction>(U.getUser())->getParent();
2543     return DT.properlyDominates(BB, I);
2544   };
2545   return ::replaceDominatedUsesWith(From, To, BB, ProperlyDominates);
2546 }
2547 
2548 bool llvm::callsGCLeafFunction(const CallBase *Call,
2549                                const TargetLibraryInfo &TLI) {
2550   // Check if the function is specifically marked as a gc leaf function.
2551   if (Call->hasFnAttr("gc-leaf-function"))
2552     return true;
2553   if (const Function *F = Call->getCalledFunction()) {
2554     if (F->hasFnAttribute("gc-leaf-function"))
2555       return true;
2556 
2557     if (auto IID = F->getIntrinsicID())
2558       // Most LLVM intrinsics do not take safepoints.
2559       return IID != Intrinsic::experimental_gc_statepoint &&
2560              IID != Intrinsic::experimental_deoptimize;
2561   }
2562 
2563   // Lib calls can be materialized by some passes, and won't be
2564   // marked as 'gc-leaf-function.' All available Libcalls are
2565   // GC-leaf.
2566   LibFunc LF;
2567   if (TLI.getLibFunc(*Call, LF)) {
2568     return TLI.has(LF);
2569   }
2570 
2571   return false;
2572 }
2573 
2574 void llvm::copyNonnullMetadata(const LoadInst &OldLI, MDNode *N,
2575                                LoadInst &NewLI) {
2576   auto *NewTy = NewLI.getType();
2577 
2578   // This only directly applies if the new type is also a pointer.
2579   if (NewTy->isPointerTy()) {
2580     NewLI.setMetadata(LLVMContext::MD_nonnull, N);
2581     return;
2582   }
2583 
2584   // The only other translation we can do is to integral loads with !range
2585   // metadata.
2586   if (!NewTy->isIntegerTy())
2587     return;
2588 
2589   MDBuilder MDB(NewLI.getContext());
2590   const Value *Ptr = OldLI.getPointerOperand();
2591   auto *ITy = cast<IntegerType>(NewTy);
2592   auto *NullInt = ConstantExpr::getPtrToInt(
2593       ConstantPointerNull::get(cast<PointerType>(Ptr->getType())), ITy);
2594   auto *NonNullInt = ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1));
2595   NewLI.setMetadata(LLVMContext::MD_range,
2596                     MDB.createRange(NonNullInt, NullInt));
2597 }
2598 
2599 void llvm::copyRangeMetadata(const DataLayout &DL, const LoadInst &OldLI,
2600                              MDNode *N, LoadInst &NewLI) {
2601   auto *NewTy = NewLI.getType();
2602 
2603   // Give up unless it is converted to a pointer where there is a single very
2604   // valuable mapping we can do reliably.
2605   // FIXME: It would be nice to propagate this in more ways, but the type
2606   // conversions make it hard.
2607   if (!NewTy->isPointerTy())
2608     return;
2609 
2610   unsigned BitWidth = DL.getPointerTypeSizeInBits(NewTy);
2611   if (!getConstantRangeFromMetadata(*N).contains(APInt(BitWidth, 0))) {
2612     MDNode *NN = MDNode::get(OldLI.getContext(), None);
2613     NewLI.setMetadata(LLVMContext::MD_nonnull, NN);
2614   }
2615 }
2616 
2617 void llvm::dropDebugUsers(Instruction &I) {
2618   SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
2619   findDbgUsers(DbgUsers, &I);
2620   for (auto *DII : DbgUsers)
2621     DII->eraseFromParent();
2622 }
2623 
2624 void llvm::hoistAllInstructionsInto(BasicBlock *DomBlock, Instruction *InsertPt,
2625                                     BasicBlock *BB) {
2626   // Since we are moving the instructions out of its basic block, we do not
2627   // retain their original debug locations (DILocations) and debug intrinsic
2628   // instructions.
2629   //
2630   // Doing so would degrade the debugging experience and adversely affect the
2631   // accuracy of profiling information.
2632   //
2633   // Currently, when hoisting the instructions, we take the following actions:
2634   // - Remove their debug intrinsic instructions.
2635   // - Set their debug locations to the values from the insertion point.
2636   //
2637   // As per PR39141 (comment #8), the more fundamental reason why the dbg.values
2638   // need to be deleted, is because there will not be any instructions with a
2639   // DILocation in either branch left after performing the transformation. We
2640   // can only insert a dbg.value after the two branches are joined again.
2641   //
2642   // See PR38762, PR39243 for more details.
2643   //
2644   // TODO: Extend llvm.dbg.value to take more than one SSA Value (PR39141) to
2645   // encode predicated DIExpressions that yield different results on different
2646   // code paths.
2647   for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) {
2648     Instruction *I = &*II;
2649     I->dropUnknownNonDebugMetadata();
2650     if (I->isUsedByMetadata())
2651       dropDebugUsers(*I);
2652     if (isa<DbgInfoIntrinsic>(I)) {
2653       // Remove DbgInfo Intrinsics.
2654       II = I->eraseFromParent();
2655       continue;
2656     }
2657     I->setDebugLoc(InsertPt->getDebugLoc());
2658     ++II;
2659   }
2660   DomBlock->getInstList().splice(InsertPt->getIterator(), BB->getInstList(),
2661                                  BB->begin(),
2662                                  BB->getTerminator()->getIterator());
2663 }
2664 
2665 namespace {
2666 
2667 /// A potential constituent of a bitreverse or bswap expression. See
2668 /// collectBitParts for a fuller explanation.
2669 struct BitPart {
2670   BitPart(Value *P, unsigned BW) : Provider(P) {
2671     Provenance.resize(BW);
2672   }
2673 
2674   /// The Value that this is a bitreverse/bswap of.
2675   Value *Provider;
2676 
2677   /// The "provenance" of each bit. Provenance[A] = B means that bit A
2678   /// in Provider becomes bit B in the result of this expression.
2679   SmallVector<int8_t, 32> Provenance; // int8_t means max size is i128.
2680 
2681   enum { Unset = -1 };
2682 };
2683 
2684 } // end anonymous namespace
2685 
2686 /// Analyze the specified subexpression and see if it is capable of providing
2687 /// pieces of a bswap or bitreverse. The subexpression provides a potential
2688 /// piece of a bswap or bitreverse if it can be proven that each non-zero bit in
2689 /// the output of the expression came from a corresponding bit in some other
2690 /// value. This function is recursive, and the end result is a mapping of
2691 /// bitnumber to bitnumber. It is the caller's responsibility to validate that
2692 /// the bitnumber to bitnumber mapping is correct for a bswap or bitreverse.
2693 ///
2694 /// For example, if the current subexpression if "(shl i32 %X, 24)" then we know
2695 /// that the expression deposits the low byte of %X into the high byte of the
2696 /// result and that all other bits are zero. This expression is accepted and a
2697 /// BitPart is returned with Provider set to %X and Provenance[24-31] set to
2698 /// [0-7].
2699 ///
2700 /// To avoid revisiting values, the BitPart results are memoized into the
2701 /// provided map. To avoid unnecessary copying of BitParts, BitParts are
2702 /// constructed in-place in the \c BPS map. Because of this \c BPS needs to
2703 /// store BitParts objects, not pointers. As we need the concept of a nullptr
2704 /// BitParts (Value has been analyzed and the analysis failed), we an Optional
2705 /// type instead to provide the same functionality.
2706 ///
2707 /// Because we pass around references into \c BPS, we must use a container that
2708 /// does not invalidate internal references (std::map instead of DenseMap).
2709 static const Optional<BitPart> &
2710 collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals,
2711                 std::map<Value *, Optional<BitPart>> &BPS, int Depth) {
2712   auto I = BPS.find(V);
2713   if (I != BPS.end())
2714     return I->second;
2715 
2716   auto &Result = BPS[V] = None;
2717   auto BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2718 
2719   // Prevent stack overflow by limiting the recursion depth
2720   if (Depth == BitPartRecursionMaxDepth) {
2721     LLVM_DEBUG(dbgs() << "collectBitParts max recursion depth reached.\n");
2722     return Result;
2723   }
2724 
2725   if (Instruction *I = dyn_cast<Instruction>(V)) {
2726     // If this is an or instruction, it may be an inner node of the bswap.
2727     if (I->getOpcode() == Instruction::Or) {
2728       auto &A = collectBitParts(I->getOperand(0), MatchBSwaps,
2729                                 MatchBitReversals, BPS, Depth + 1);
2730       auto &B = collectBitParts(I->getOperand(1), MatchBSwaps,
2731                                 MatchBitReversals, BPS, Depth + 1);
2732       if (!A || !B)
2733         return Result;
2734 
2735       // Try and merge the two together.
2736       if (!A->Provider || A->Provider != B->Provider)
2737         return Result;
2738 
2739       Result = BitPart(A->Provider, BitWidth);
2740       for (unsigned i = 0; i < A->Provenance.size(); ++i) {
2741         if (A->Provenance[i] != BitPart::Unset &&
2742             B->Provenance[i] != BitPart::Unset &&
2743             A->Provenance[i] != B->Provenance[i])
2744           return Result = None;
2745 
2746         if (A->Provenance[i] == BitPart::Unset)
2747           Result->Provenance[i] = B->Provenance[i];
2748         else
2749           Result->Provenance[i] = A->Provenance[i];
2750       }
2751 
2752       return Result;
2753     }
2754 
2755     // If this is a logical shift by a constant, recurse then shift the result.
2756     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
2757       unsigned BitShift =
2758           cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
2759       // Ensure the shift amount is defined.
2760       if (BitShift > BitWidth)
2761         return Result;
2762 
2763       auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
2764                                   MatchBitReversals, BPS, Depth + 1);
2765       if (!Res)
2766         return Result;
2767       Result = Res;
2768 
2769       // Perform the "shift" on BitProvenance.
2770       auto &P = Result->Provenance;
2771       if (I->getOpcode() == Instruction::Shl) {
2772         P.erase(std::prev(P.end(), BitShift), P.end());
2773         P.insert(P.begin(), BitShift, BitPart::Unset);
2774       } else {
2775         P.erase(P.begin(), std::next(P.begin(), BitShift));
2776         P.insert(P.end(), BitShift, BitPart::Unset);
2777       }
2778 
2779       return Result;
2780     }
2781 
2782     // If this is a logical 'and' with a mask that clears bits, recurse then
2783     // unset the appropriate bits.
2784     if (I->getOpcode() == Instruction::And &&
2785         isa<ConstantInt>(I->getOperand(1))) {
2786       APInt Bit(I->getType()->getPrimitiveSizeInBits(), 1);
2787       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
2788 
2789       // Check that the mask allows a multiple of 8 bits for a bswap, for an
2790       // early exit.
2791       unsigned NumMaskedBits = AndMask.countPopulation();
2792       if (!MatchBitReversals && NumMaskedBits % 8 != 0)
2793         return Result;
2794 
2795       auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
2796                                   MatchBitReversals, BPS, Depth + 1);
2797       if (!Res)
2798         return Result;
2799       Result = Res;
2800 
2801       for (unsigned i = 0; i < BitWidth; ++i, Bit <<= 1)
2802         // If the AndMask is zero for this bit, clear the bit.
2803         if ((AndMask & Bit) == 0)
2804           Result->Provenance[i] = BitPart::Unset;
2805       return Result;
2806     }
2807 
2808     // If this is a zext instruction zero extend the result.
2809     if (I->getOpcode() == Instruction::ZExt) {
2810       auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
2811                                   MatchBitReversals, BPS, Depth + 1);
2812       if (!Res)
2813         return Result;
2814 
2815       Result = BitPart(Res->Provider, BitWidth);
2816       auto NarrowBitWidth =
2817           cast<IntegerType>(cast<ZExtInst>(I)->getSrcTy())->getBitWidth();
2818       for (unsigned i = 0; i < NarrowBitWidth; ++i)
2819         Result->Provenance[i] = Res->Provenance[i];
2820       for (unsigned i = NarrowBitWidth; i < BitWidth; ++i)
2821         Result->Provenance[i] = BitPart::Unset;
2822       return Result;
2823     }
2824   }
2825 
2826   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
2827   // the input value to the bswap/bitreverse.
2828   Result = BitPart(V, BitWidth);
2829   for (unsigned i = 0; i < BitWidth; ++i)
2830     Result->Provenance[i] = i;
2831   return Result;
2832 }
2833 
2834 static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To,
2835                                           unsigned BitWidth) {
2836   if (From % 8 != To % 8)
2837     return false;
2838   // Convert from bit indices to byte indices and check for a byte reversal.
2839   From >>= 3;
2840   To >>= 3;
2841   BitWidth >>= 3;
2842   return From == BitWidth - To - 1;
2843 }
2844 
2845 static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To,
2846                                                unsigned BitWidth) {
2847   return From == BitWidth - To - 1;
2848 }
2849 
2850 bool llvm::recognizeBSwapOrBitReverseIdiom(
2851     Instruction *I, bool MatchBSwaps, bool MatchBitReversals,
2852     SmallVectorImpl<Instruction *> &InsertedInsts) {
2853   if (Operator::getOpcode(I) != Instruction::Or)
2854     return false;
2855   if (!MatchBSwaps && !MatchBitReversals)
2856     return false;
2857   IntegerType *ITy = dyn_cast<IntegerType>(I->getType());
2858   if (!ITy || ITy->getBitWidth() > 128)
2859     return false;   // Can't do vectors or integers > 128 bits.
2860   unsigned BW = ITy->getBitWidth();
2861 
2862   unsigned DemandedBW = BW;
2863   IntegerType *DemandedTy = ITy;
2864   if (I->hasOneUse()) {
2865     if (TruncInst *Trunc = dyn_cast<TruncInst>(I->user_back())) {
2866       DemandedTy = cast<IntegerType>(Trunc->getType());
2867       DemandedBW = DemandedTy->getBitWidth();
2868     }
2869   }
2870 
2871   // Try to find all the pieces corresponding to the bswap.
2872   std::map<Value *, Optional<BitPart>> BPS;
2873   auto Res = collectBitParts(I, MatchBSwaps, MatchBitReversals, BPS, 0);
2874   if (!Res)
2875     return false;
2876   auto &BitProvenance = Res->Provenance;
2877 
2878   // Now, is the bit permutation correct for a bswap or a bitreverse? We can
2879   // only byteswap values with an even number of bytes.
2880   bool OKForBSwap = DemandedBW % 16 == 0, OKForBitReverse = true;
2881   for (unsigned i = 0; i < DemandedBW; ++i) {
2882     OKForBSwap &=
2883         bitTransformIsCorrectForBSwap(BitProvenance[i], i, DemandedBW);
2884     OKForBitReverse &=
2885         bitTransformIsCorrectForBitReverse(BitProvenance[i], i, DemandedBW);
2886   }
2887 
2888   Intrinsic::ID Intrin;
2889   if (OKForBSwap && MatchBSwaps)
2890     Intrin = Intrinsic::bswap;
2891   else if (OKForBitReverse && MatchBitReversals)
2892     Intrin = Intrinsic::bitreverse;
2893   else
2894     return false;
2895 
2896   if (ITy != DemandedTy) {
2897     Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, DemandedTy);
2898     Value *Provider = Res->Provider;
2899     IntegerType *ProviderTy = cast<IntegerType>(Provider->getType());
2900     // We may need to truncate the provider.
2901     if (DemandedTy != ProviderTy) {
2902       auto *Trunc = CastInst::Create(Instruction::Trunc, Provider, DemandedTy,
2903                                      "trunc", I);
2904       InsertedInsts.push_back(Trunc);
2905       Provider = Trunc;
2906     }
2907     auto *CI = CallInst::Create(F, Provider, "rev", I);
2908     InsertedInsts.push_back(CI);
2909     auto *ExtInst = CastInst::Create(Instruction::ZExt, CI, ITy, "zext", I);
2910     InsertedInsts.push_back(ExtInst);
2911     return true;
2912   }
2913 
2914   Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, ITy);
2915   InsertedInsts.push_back(CallInst::Create(F, Res->Provider, "rev", I));
2916   return true;
2917 }
2918 
2919 // CodeGen has special handling for some string functions that may replace
2920 // them with target-specific intrinsics.  Since that'd skip our interceptors
2921 // in ASan/MSan/TSan/DFSan, and thus make us miss some memory accesses,
2922 // we mark affected calls as NoBuiltin, which will disable optimization
2923 // in CodeGen.
2924 void llvm::maybeMarkSanitizerLibraryCallNoBuiltin(
2925     CallInst *CI, const TargetLibraryInfo *TLI) {
2926   Function *F = CI->getCalledFunction();
2927   LibFunc Func;
2928   if (F && !F->hasLocalLinkage() && F->hasName() &&
2929       TLI->getLibFunc(F->getName(), Func) && TLI->hasOptimizedCodeGen(Func) &&
2930       !F->doesNotAccessMemory())
2931     CI->addAttribute(AttributeList::FunctionIndex, Attribute::NoBuiltin);
2932 }
2933 
2934 bool llvm::canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx) {
2935   // We can't have a PHI with a metadata type.
2936   if (I->getOperand(OpIdx)->getType()->isMetadataTy())
2937     return false;
2938 
2939   // Early exit.
2940   if (!isa<Constant>(I->getOperand(OpIdx)))
2941     return true;
2942 
2943   switch (I->getOpcode()) {
2944   default:
2945     return true;
2946   case Instruction::Call:
2947   case Instruction::Invoke: {
2948     const auto &CB = cast<CallBase>(*I);
2949 
2950     // Can't handle inline asm. Skip it.
2951     if (CB.isInlineAsm())
2952       return false;
2953 
2954     // Constant bundle operands may need to retain their constant-ness for
2955     // correctness.
2956     if (CB.isBundleOperand(OpIdx))
2957       return false;
2958 
2959     if (OpIdx < CB.getNumArgOperands()) {
2960       // Some variadic intrinsics require constants in the variadic arguments,
2961       // which currently aren't markable as immarg.
2962       if (isa<IntrinsicInst>(CB) &&
2963           OpIdx >= CB.getFunctionType()->getNumParams()) {
2964         // This is known to be OK for stackmap.
2965         return CB.getIntrinsicID() == Intrinsic::experimental_stackmap;
2966       }
2967 
2968       // gcroot is a special case, since it requires a constant argument which
2969       // isn't also required to be a simple ConstantInt.
2970       if (CB.getIntrinsicID() == Intrinsic::gcroot)
2971         return false;
2972 
2973       // Some intrinsic operands are required to be immediates.
2974       return !CB.paramHasAttr(OpIdx, Attribute::ImmArg);
2975     }
2976 
2977     // It is never allowed to replace the call argument to an intrinsic, but it
2978     // may be possible for a call.
2979     return !isa<IntrinsicInst>(CB);
2980   }
2981   case Instruction::ShuffleVector:
2982     // Shufflevector masks are constant.
2983     return OpIdx != 2;
2984   case Instruction::Switch:
2985   case Instruction::ExtractValue:
2986     // All operands apart from the first are constant.
2987     return OpIdx == 0;
2988   case Instruction::InsertValue:
2989     // All operands apart from the first and the second are constant.
2990     return OpIdx < 2;
2991   case Instruction::Alloca:
2992     // Static allocas (constant size in the entry block) are handled by
2993     // prologue/epilogue insertion so they're free anyway. We definitely don't
2994     // want to make them non-constant.
2995     return !cast<AllocaInst>(I)->isStaticAlloca();
2996   case Instruction::GetElementPtr:
2997     if (OpIdx == 0)
2998       return true;
2999     gep_type_iterator It = gep_type_begin(I);
3000     for (auto E = std::next(It, OpIdx); It != E; ++It)
3001       if (It.isStruct())
3002         return false;
3003     return true;
3004   }
3005 }
3006 
3007 using AllocaForValueMapTy = DenseMap<Value *, AllocaInst *>;
3008 AllocaInst *llvm::findAllocaForValue(Value *V,
3009                                      AllocaForValueMapTy &AllocaForValue) {
3010   if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
3011     return AI;
3012   // See if we've already calculated (or started to calculate) alloca for a
3013   // given value.
3014   AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
3015   if (I != AllocaForValue.end())
3016     return I->second;
3017   // Store 0 while we're calculating alloca for value V to avoid
3018   // infinite recursion if the value references itself.
3019   AllocaForValue[V] = nullptr;
3020   AllocaInst *Res = nullptr;
3021   if (CastInst *CI = dyn_cast<CastInst>(V))
3022     Res = findAllocaForValue(CI->getOperand(0), AllocaForValue);
3023   else if (PHINode *PN = dyn_cast<PHINode>(V)) {
3024     for (Value *IncValue : PN->incoming_values()) {
3025       // Allow self-referencing phi-nodes.
3026       if (IncValue == PN)
3027         continue;
3028       AllocaInst *IncValueAI = findAllocaForValue(IncValue, AllocaForValue);
3029       // AI for incoming values should exist and should all be equal.
3030       if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
3031         return nullptr;
3032       Res = IncValueAI;
3033     }
3034   } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
3035     Res = findAllocaForValue(EP->getPointerOperand(), AllocaForValue);
3036   } else {
3037     LLVM_DEBUG(dbgs() << "Alloca search cancelled on unknown instruction: "
3038                       << *V << "\n");
3039   }
3040   if (Res)
3041     AllocaForValue[V] = Res;
3042   return Res;
3043 }
3044 
3045 Value *llvm::invertCondition(Value *Condition) {
3046   // First: Check if it's a constant
3047   if (Constant *C = dyn_cast<Constant>(Condition))
3048     return ConstantExpr::getNot(C);
3049 
3050   // Second: If the condition is already inverted, return the original value
3051   Value *NotCondition;
3052   if (match(Condition, m_Not(m_Value(NotCondition))))
3053     return NotCondition;
3054 
3055   if (Instruction *Inst = dyn_cast<Instruction>(Condition)) {
3056     // Third: Check all the users for an invert
3057     BasicBlock *Parent = Inst->getParent();
3058     for (User *U : Condition->users())
3059       if (Instruction *I = dyn_cast<Instruction>(U))
3060         if (I->getParent() == Parent && match(I, m_Not(m_Specific(Condition))))
3061           return I;
3062 
3063     // Last option: Create a new instruction
3064     auto Inverted = BinaryOperator::CreateNot(Inst, "");
3065     if (isa<PHINode>(Inst)) {
3066       // FIXME: This fails if the inversion is to be used in a
3067       // subsequent PHINode in the same basic block.
3068       Inverted->insertBefore(&*Parent->getFirstInsertionPt());
3069     } else {
3070       Inverted->insertAfter(Inst);
3071     }
3072     return Inverted;
3073   }
3074 
3075   if (Argument *Arg = dyn_cast<Argument>(Condition)) {
3076     BasicBlock &EntryBlock = Arg->getParent()->getEntryBlock();
3077     return BinaryOperator::CreateNot(Condition, Arg->getName() + ".inv",
3078                                      &*EntryBlock.getFirstInsertionPt());
3079   }
3080 
3081   llvm_unreachable("Unhandled condition to invert");
3082 }
3083