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