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