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/DenseMap.h"
17 #include "llvm/ADT/DenseSet.h"
18 #include "llvm/ADT/Hashing.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/EHPersonalities.h"
24 #include "llvm/Analysis/InstructionSimplify.h"
25 #include "llvm/Analysis/MemoryBuiltins.h"
26 #include "llvm/Analysis/LazyValueInfo.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/IR/CFG.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DIBuilder.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/DebugInfo.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/Dominators.h"
35 #include "llvm/IR/GetElementPtrTypeIterator.h"
36 #include "llvm/IR/GlobalAlias.h"
37 #include "llvm/IR/GlobalVariable.h"
38 #include "llvm/IR/IRBuilder.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/IntrinsicInst.h"
41 #include "llvm/IR/Intrinsics.h"
42 #include "llvm/IR/MDBuilder.h"
43 #include "llvm/IR/Metadata.h"
44 #include "llvm/IR/Operator.h"
45 #include "llvm/IR/PatternMatch.h"
46 #include "llvm/IR/ValueHandle.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Support/raw_ostream.h"
50 using namespace llvm;
51 using namespace llvm::PatternMatch;
52 
53 #define DEBUG_TYPE "local"
54 
55 STATISTIC(NumRemoved, "Number of unreachable basic blocks removed");
56 
57 //===----------------------------------------------------------------------===//
58 //  Local constant propagation.
59 //
60 
61 /// ConstantFoldTerminator - If a terminator instruction is predicated on a
62 /// constant value, convert it into an unconditional branch to the constant
63 /// destination.  This is a nontrivial operation because the successors of this
64 /// basic block must have their PHI nodes updated.
65 /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
66 /// conditions and indirectbr addresses this might make dead if
67 /// DeleteDeadConditions is true.
68 bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
69                                   const TargetLibraryInfo *TLI) {
70   TerminatorInst *T = BB->getTerminator();
71   IRBuilder<> Builder(T);
72 
73   // Branch - See if we are conditional jumping on constant
74   if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
75     if (BI->isUnconditional()) return false;  // Can't optimize uncond branch
76     BasicBlock *Dest1 = BI->getSuccessor(0);
77     BasicBlock *Dest2 = BI->getSuccessor(1);
78 
79     if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
80       // Are we branching on constant?
81       // YES.  Change to unconditional branch...
82       BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
83       BasicBlock *OldDest     = Cond->getZExtValue() ? Dest2 : Dest1;
84 
85       //cerr << "Function: " << T->getParent()->getParent()
86       //     << "\nRemoving branch from " << T->getParent()
87       //     << "\n\nTo: " << OldDest << endl;
88 
89       // Let the basic block know that we are letting go of it.  Based on this,
90       // it will adjust it's PHI nodes.
91       OldDest->removePredecessor(BB);
92 
93       // Replace the conditional branch with an unconditional one.
94       Builder.CreateBr(Destination);
95       BI->eraseFromParent();
96       return true;
97     }
98 
99     if (Dest2 == Dest1) {       // Conditional branch to same location?
100       // This branch matches something like this:
101       //     br bool %cond, label %Dest, label %Dest
102       // and changes it into:  br label %Dest
103 
104       // Let the basic block know that we are letting go of one copy of it.
105       assert(BI->getParent() && "Terminator not inserted in block!");
106       Dest1->removePredecessor(BI->getParent());
107 
108       // Replace the conditional branch with an unconditional one.
109       Builder.CreateBr(Dest1);
110       Value *Cond = BI->getCondition();
111       BI->eraseFromParent();
112       if (DeleteDeadConditions)
113         RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
114       return true;
115     }
116     return false;
117   }
118 
119   if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
120     // If we are switching on a constant, we can convert the switch to an
121     // unconditional branch.
122     ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
123     BasicBlock *DefaultDest = SI->getDefaultDest();
124     BasicBlock *TheOnlyDest = DefaultDest;
125 
126     // If the default is unreachable, ignore it when searching for TheOnlyDest.
127     if (isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()) &&
128         SI->getNumCases() > 0) {
129       TheOnlyDest = SI->case_begin().getCaseSuccessor();
130     }
131 
132     // Figure out which case it goes to.
133     for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
134          i != e; ++i) {
135       // Found case matching a constant operand?
136       if (i.getCaseValue() == CI) {
137         TheOnlyDest = i.getCaseSuccessor();
138         break;
139       }
140 
141       // Check to see if this branch is going to the same place as the default
142       // dest.  If so, eliminate it as an explicit compare.
143       if (i.getCaseSuccessor() == DefaultDest) {
144         MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
145         unsigned NCases = SI->getNumCases();
146         // Fold the case metadata into the default if there will be any branches
147         // left, unless the metadata doesn't match the switch.
148         if (NCases > 1 && MD && MD->getNumOperands() == 2 + NCases) {
149           // Collect branch weights into a vector.
150           SmallVector<uint32_t, 8> Weights;
151           for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
152                ++MD_i) {
153             auto *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
154             Weights.push_back(CI->getValue().getZExtValue());
155           }
156           // Merge weight of this case to the default weight.
157           unsigned idx = i.getCaseIndex();
158           Weights[0] += Weights[idx+1];
159           // Remove weight for this case.
160           std::swap(Weights[idx+1], Weights.back());
161           Weights.pop_back();
162           SI->setMetadata(LLVMContext::MD_prof,
163                           MDBuilder(BB->getContext()).
164                           createBranchWeights(Weights));
165         }
166         // Remove this entry.
167         DefaultDest->removePredecessor(SI->getParent());
168         SI->removeCase(i);
169         --i; --e;
170         continue;
171       }
172 
173       // Otherwise, check to see if the switch only branches to one destination.
174       // We do this by reseting "TheOnlyDest" to null when we find two non-equal
175       // destinations.
176       if (i.getCaseSuccessor() != TheOnlyDest) TheOnlyDest = nullptr;
177     }
178 
179     if (CI && !TheOnlyDest) {
180       // Branching on a constant, but not any of the cases, go to the default
181       // successor.
182       TheOnlyDest = SI->getDefaultDest();
183     }
184 
185     // If we found a single destination that we can fold the switch into, do so
186     // now.
187     if (TheOnlyDest) {
188       // Insert the new branch.
189       Builder.CreateBr(TheOnlyDest);
190       BasicBlock *BB = SI->getParent();
191 
192       // Remove entries from PHI nodes which we no longer branch to...
193       for (BasicBlock *Succ : SI->successors()) {
194         // Found case matching a constant operand?
195         if (Succ == TheOnlyDest)
196           TheOnlyDest = nullptr; // Don't modify the first branch to TheOnlyDest
197         else
198           Succ->removePredecessor(BB);
199       }
200 
201       // Delete the old switch.
202       Value *Cond = SI->getCondition();
203       SI->eraseFromParent();
204       if (DeleteDeadConditions)
205         RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
206       return true;
207     }
208 
209     if (SI->getNumCases() == 1) {
210       // Otherwise, we can fold this switch into a conditional branch
211       // instruction if it has only one non-default destination.
212       SwitchInst::CaseIt FirstCase = SI->case_begin();
213       Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
214           FirstCase.getCaseValue(), "cond");
215 
216       // Insert the new branch.
217       BranchInst *NewBr = Builder.CreateCondBr(Cond,
218                                                FirstCase.getCaseSuccessor(),
219                                                SI->getDefaultDest());
220       MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
221       if (MD && MD->getNumOperands() == 3) {
222         ConstantInt *SICase =
223             mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
224         ConstantInt *SIDef =
225             mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
226         assert(SICase && SIDef);
227         // The TrueWeight should be the weight for the single case of SI.
228         NewBr->setMetadata(LLVMContext::MD_prof,
229                         MDBuilder(BB->getContext()).
230                         createBranchWeights(SICase->getValue().getZExtValue(),
231                                             SIDef->getValue().getZExtValue()));
232       }
233 
234       // Update make.implicit metadata to the newly-created conditional branch.
235       MDNode *MakeImplicitMD = SI->getMetadata(LLVMContext::MD_make_implicit);
236       if (MakeImplicitMD)
237         NewBr->setMetadata(LLVMContext::MD_make_implicit, MakeImplicitMD);
238 
239       // Delete the old switch.
240       SI->eraseFromParent();
241       return true;
242     }
243     return false;
244   }
245 
246   if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(T)) {
247     // indirectbr blockaddress(@F, @BB) -> br label @BB
248     if (BlockAddress *BA =
249           dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
250       BasicBlock *TheOnlyDest = BA->getBasicBlock();
251       // Insert the new branch.
252       Builder.CreateBr(TheOnlyDest);
253 
254       for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
255         if (IBI->getDestination(i) == TheOnlyDest)
256           TheOnlyDest = nullptr;
257         else
258           IBI->getDestination(i)->removePredecessor(IBI->getParent());
259       }
260       Value *Address = IBI->getAddress();
261       IBI->eraseFromParent();
262       if (DeleteDeadConditions)
263         RecursivelyDeleteTriviallyDeadInstructions(Address, TLI);
264 
265       // If we didn't find our destination in the IBI successor list, then we
266       // have undefined behavior.  Replace the unconditional branch with an
267       // 'unreachable' instruction.
268       if (TheOnlyDest) {
269         BB->getTerminator()->eraseFromParent();
270         new UnreachableInst(BB->getContext(), BB);
271       }
272 
273       return true;
274     }
275   }
276 
277   return false;
278 }
279 
280 
281 //===----------------------------------------------------------------------===//
282 //  Local dead code elimination.
283 //
284 
285 /// isInstructionTriviallyDead - Return true if the result produced by the
286 /// instruction is not used, and the instruction has no side effects.
287 ///
288 bool llvm::isInstructionTriviallyDead(Instruction *I,
289                                       const TargetLibraryInfo *TLI) {
290   if (!I->use_empty())
291     return false;
292   return wouldInstructionBeTriviallyDead(I, TLI);
293 }
294 
295 bool llvm::wouldInstructionBeTriviallyDead(Instruction *I,
296                                            const TargetLibraryInfo *TLI) {
297   if (isa<TerminatorInst>(I))
298     return false;
299 
300   // We don't want the landingpad-like instructions removed by anything this
301   // general.
302   if (I->isEHPad())
303     return false;
304 
305   // We don't want debug info removed by anything this general, unless
306   // debug info is empty.
307   if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
308     if (DDI->getAddress())
309       return false;
310     return true;
311   }
312   if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
313     if (DVI->getValue())
314       return false;
315     return true;
316   }
317 
318   if (!I->mayHaveSideEffects())
319     return true;
320 
321   // Special case intrinsics that "may have side effects" but can be deleted
322   // when dead.
323   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
324     // Safe to delete llvm.stacksave if dead.
325     if (II->getIntrinsicID() == Intrinsic::stacksave)
326       return true;
327 
328     // Lifetime intrinsics are dead when their right-hand is undef.
329     if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
330         II->getIntrinsicID() == Intrinsic::lifetime_end)
331       return isa<UndefValue>(II->getArgOperand(1));
332 
333     // Assumptions are dead if their condition is trivially true.  Guards on
334     // true are operationally no-ops.  In the future we can consider more
335     // sophisticated tradeoffs for guards considering potential for check
336     // widening, but for now we keep things simple.
337     if (II->getIntrinsicID() == Intrinsic::assume ||
338         II->getIntrinsicID() == Intrinsic::experimental_guard) {
339       if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0)))
340         return !Cond->isZero();
341 
342       return false;
343     }
344   }
345 
346   if (isAllocLikeFn(I, TLI))
347     return true;
348 
349   if (CallInst *CI = isFreeCall(I, TLI))
350     if (Constant *C = dyn_cast<Constant>(CI->getArgOperand(0)))
351       return C->isNullValue() || isa<UndefValue>(C);
352 
353   if (CallSite CS = CallSite(I))
354     if (isMathLibCallNoop(CS, TLI))
355       return true;
356 
357   return false;
358 }
359 
360 /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
361 /// trivially dead instruction, delete it.  If that makes any of its operands
362 /// trivially dead, delete them too, recursively.  Return true if any
363 /// instructions were deleted.
364 bool
365 llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V,
366                                                  const TargetLibraryInfo *TLI) {
367   Instruction *I = dyn_cast<Instruction>(V);
368   if (!I || !I->use_empty() || !isInstructionTriviallyDead(I, TLI))
369     return false;
370 
371   SmallVector<Instruction*, 16> DeadInsts;
372   DeadInsts.push_back(I);
373 
374   do {
375     I = DeadInsts.pop_back_val();
376 
377     // Null out all of the instruction's operands to see if any operand becomes
378     // dead as we go.
379     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
380       Value *OpV = I->getOperand(i);
381       I->setOperand(i, nullptr);
382 
383       if (!OpV->use_empty()) continue;
384 
385       // If the operand is an instruction that became dead as we nulled out the
386       // operand, and if it is 'trivially' dead, delete it in a future loop
387       // iteration.
388       if (Instruction *OpI = dyn_cast<Instruction>(OpV))
389         if (isInstructionTriviallyDead(OpI, TLI))
390           DeadInsts.push_back(OpI);
391     }
392 
393     I->eraseFromParent();
394   } while (!DeadInsts.empty());
395 
396   return true;
397 }
398 
399 /// areAllUsesEqual - Check whether the uses of a value are all the same.
400 /// This is similar to Instruction::hasOneUse() except this will also return
401 /// true when there are no uses or multiple uses that all refer to the same
402 /// value.
403 static bool areAllUsesEqual(Instruction *I) {
404   Value::user_iterator UI = I->user_begin();
405   Value::user_iterator UE = I->user_end();
406   if (UI == UE)
407     return true;
408 
409   User *TheUse = *UI;
410   for (++UI; UI != UE; ++UI) {
411     if (*UI != TheUse)
412       return false;
413   }
414   return true;
415 }
416 
417 /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
418 /// dead PHI node, due to being a def-use chain of single-use nodes that
419 /// either forms a cycle or is terminated by a trivially dead instruction,
420 /// delete it.  If that makes any of its operands trivially dead, delete them
421 /// too, recursively.  Return true if a change was made.
422 bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN,
423                                         const TargetLibraryInfo *TLI) {
424   SmallPtrSet<Instruction*, 4> Visited;
425   for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
426        I = cast<Instruction>(*I->user_begin())) {
427     if (I->use_empty())
428       return RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
429 
430     // If we find an instruction more than once, we're on a cycle that
431     // won't prove fruitful.
432     if (!Visited.insert(I).second) {
433       // Break the cycle and delete the instruction and its operands.
434       I->replaceAllUsesWith(UndefValue::get(I->getType()));
435       (void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
436       return true;
437     }
438   }
439   return false;
440 }
441 
442 static bool
443 simplifyAndDCEInstruction(Instruction *I,
444                           SmallSetVector<Instruction *, 16> &WorkList,
445                           const DataLayout &DL,
446                           const TargetLibraryInfo *TLI) {
447   if (isInstructionTriviallyDead(I, TLI)) {
448     // Null out all of the instruction's operands to see if any operand becomes
449     // dead as we go.
450     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
451       Value *OpV = I->getOperand(i);
452       I->setOperand(i, nullptr);
453 
454       if (!OpV->use_empty() || I == OpV)
455         continue;
456 
457       // If the operand is an instruction that became dead as we nulled out the
458       // operand, and if it is 'trivially' dead, delete it in a future loop
459       // iteration.
460       if (Instruction *OpI = dyn_cast<Instruction>(OpV))
461         if (isInstructionTriviallyDead(OpI, TLI))
462           WorkList.insert(OpI);
463     }
464 
465     I->eraseFromParent();
466 
467     return true;
468   }
469 
470   if (Value *SimpleV = SimplifyInstruction(I, DL)) {
471     // Add the users to the worklist. CAREFUL: an instruction can use itself,
472     // in the case of a phi node.
473     for (User *U : I->users()) {
474       if (U != I) {
475         WorkList.insert(cast<Instruction>(U));
476       }
477     }
478 
479     // Replace the instruction with its simplified value.
480     bool Changed = false;
481     if (!I->use_empty()) {
482       I->replaceAllUsesWith(SimpleV);
483       Changed = true;
484     }
485     if (isInstructionTriviallyDead(I, TLI)) {
486       I->eraseFromParent();
487       Changed = true;
488     }
489     return Changed;
490   }
491   return false;
492 }
493 
494 /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
495 /// simplify any instructions in it and recursively delete dead instructions.
496 ///
497 /// This returns true if it changed the code, note that it can delete
498 /// instructions in other blocks as well in this block.
499 bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB,
500                                        const TargetLibraryInfo *TLI) {
501   bool MadeChange = false;
502   const DataLayout &DL = BB->getModule()->getDataLayout();
503 
504 #ifndef NDEBUG
505   // In debug builds, ensure that the terminator of the block is never replaced
506   // or deleted by these simplifications. The idea of simplification is that it
507   // cannot introduce new instructions, and there is no way to replace the
508   // terminator of a block without introducing a new instruction.
509   AssertingVH<Instruction> TerminatorVH(&BB->back());
510 #endif
511 
512   SmallSetVector<Instruction *, 16> WorkList;
513   // Iterate over the original function, only adding insts to the worklist
514   // if they actually need to be revisited. This avoids having to pre-init
515   // the worklist with the entire function's worth of instructions.
516   for (BasicBlock::iterator BI = BB->begin(), E = std::prev(BB->end());
517        BI != E;) {
518     assert(!BI->isTerminator());
519     Instruction *I = &*BI;
520     ++BI;
521 
522     // We're visiting this instruction now, so make sure it's not in the
523     // worklist from an earlier visit.
524     if (!WorkList.count(I))
525       MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
526   }
527 
528   while (!WorkList.empty()) {
529     Instruction *I = WorkList.pop_back_val();
530     MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
531   }
532   return MadeChange;
533 }
534 
535 //===----------------------------------------------------------------------===//
536 //  Control Flow Graph Restructuring.
537 //
538 
539 
540 /// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
541 /// method is called when we're about to delete Pred as a predecessor of BB.  If
542 /// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
543 ///
544 /// Unlike the removePredecessor method, this attempts to simplify uses of PHI
545 /// nodes that collapse into identity values.  For example, if we have:
546 ///   x = phi(1, 0, 0, 0)
547 ///   y = and x, z
548 ///
549 /// .. and delete the predecessor corresponding to the '1', this will attempt to
550 /// recursively fold the and to 0.
551 void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred) {
552   // This only adjusts blocks with PHI nodes.
553   if (!isa<PHINode>(BB->begin()))
554     return;
555 
556   // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
557   // them down.  This will leave us with single entry phi nodes and other phis
558   // that can be removed.
559   BB->removePredecessor(Pred, true);
560 
561   WeakVH PhiIt = &BB->front();
562   while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
563     PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
564     Value *OldPhiIt = PhiIt;
565 
566     if (!recursivelySimplifyInstruction(PN))
567       continue;
568 
569     // If recursive simplification ended up deleting the next PHI node we would
570     // iterate to, then our iterator is invalid, restart scanning from the top
571     // of the block.
572     if (PhiIt != OldPhiIt) PhiIt = &BB->front();
573   }
574 }
575 
576 
577 /// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
578 /// predecessor is known to have one successor (DestBB!).  Eliminate the edge
579 /// between them, moving the instructions in the predecessor into DestBB and
580 /// deleting the predecessor block.
581 ///
582 void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, DominatorTree *DT) {
583   // If BB has single-entry PHI nodes, fold them.
584   while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
585     Value *NewVal = PN->getIncomingValue(0);
586     // Replace self referencing PHI with undef, it must be dead.
587     if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
588     PN->replaceAllUsesWith(NewVal);
589     PN->eraseFromParent();
590   }
591 
592   BasicBlock *PredBB = DestBB->getSinglePredecessor();
593   assert(PredBB && "Block doesn't have a single predecessor!");
594 
595   // Zap anything that took the address of DestBB.  Not doing this will give the
596   // address an invalid value.
597   if (DestBB->hasAddressTaken()) {
598     BlockAddress *BA = BlockAddress::get(DestBB);
599     Constant *Replacement =
600       ConstantInt::get(llvm::Type::getInt32Ty(BA->getContext()), 1);
601     BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
602                                                      BA->getType()));
603     BA->destroyConstant();
604   }
605 
606   // Anything that branched to PredBB now branches to DestBB.
607   PredBB->replaceAllUsesWith(DestBB);
608 
609   // Splice all the instructions from PredBB to DestBB.
610   PredBB->getTerminator()->eraseFromParent();
611   DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
612 
613   // If the PredBB is the entry block of the function, move DestBB up to
614   // become the entry block after we erase PredBB.
615   if (PredBB == &DestBB->getParent()->getEntryBlock())
616     DestBB->moveAfter(PredBB);
617 
618   if (DT) {
619     BasicBlock *PredBBIDom = DT->getNode(PredBB)->getIDom()->getBlock();
620     DT->changeImmediateDominator(DestBB, PredBBIDom);
621     DT->eraseNode(PredBB);
622   }
623   // Nuke BB.
624   PredBB->eraseFromParent();
625 }
626 
627 /// CanMergeValues - Return true if we can choose one of these values to use
628 /// in place of the other. Note that we will always choose the non-undef
629 /// value to keep.
630 static bool CanMergeValues(Value *First, Value *Second) {
631   return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
632 }
633 
634 /// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
635 /// almost-empty BB ending in an unconditional branch to Succ, into Succ.
636 ///
637 /// Assumption: Succ is the single successor for BB.
638 ///
639 static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
640   assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
641 
642   DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
643         << Succ->getName() << "\n");
644   // Shortcut, if there is only a single predecessor it must be BB and merging
645   // is always safe
646   if (Succ->getSinglePredecessor()) return true;
647 
648   // Make a list of the predecessors of BB
649   SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
650 
651   // Look at all the phi nodes in Succ, to see if they present a conflict when
652   // merging these blocks
653   for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
654     PHINode *PN = cast<PHINode>(I);
655 
656     // If the incoming value from BB is again a PHINode in
657     // BB which has the same incoming value for *PI as PN does, we can
658     // merge the phi nodes and then the blocks can still be merged
659     PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
660     if (BBPN && BBPN->getParent() == BB) {
661       for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
662         BasicBlock *IBB = PN->getIncomingBlock(PI);
663         if (BBPreds.count(IBB) &&
664             !CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
665                             PN->getIncomingValue(PI))) {
666           DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
667                 << Succ->getName() << " is conflicting with "
668                 << BBPN->getName() << " with regard to common predecessor "
669                 << IBB->getName() << "\n");
670           return false;
671         }
672       }
673     } else {
674       Value* Val = PN->getIncomingValueForBlock(BB);
675       for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
676         // See if the incoming value for the common predecessor is equal to the
677         // one for BB, in which case this phi node will not prevent the merging
678         // of the block.
679         BasicBlock *IBB = PN->getIncomingBlock(PI);
680         if (BBPreds.count(IBB) &&
681             !CanMergeValues(Val, PN->getIncomingValue(PI))) {
682           DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
683                 << Succ->getName() << " is conflicting with regard to common "
684                 << "predecessor " << IBB->getName() << "\n");
685           return false;
686         }
687       }
688     }
689   }
690 
691   return true;
692 }
693 
694 typedef SmallVector<BasicBlock *, 16> PredBlockVector;
695 typedef DenseMap<BasicBlock *, Value *> IncomingValueMap;
696 
697 /// \brief Determines the value to use as the phi node input for a block.
698 ///
699 /// Select between \p OldVal any value that we know flows from \p BB
700 /// to a particular phi on the basis of which one (if either) is not
701 /// undef. Update IncomingValues based on the selected value.
702 ///
703 /// \param OldVal The value we are considering selecting.
704 /// \param BB The block that the value flows in from.
705 /// \param IncomingValues A map from block-to-value for other phi inputs
706 /// that we have examined.
707 ///
708 /// \returns the selected value.
709 static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
710                                           IncomingValueMap &IncomingValues) {
711   if (!isa<UndefValue>(OldVal)) {
712     assert((!IncomingValues.count(BB) ||
713             IncomingValues.find(BB)->second == OldVal) &&
714            "Expected OldVal to match incoming value from BB!");
715 
716     IncomingValues.insert(std::make_pair(BB, OldVal));
717     return OldVal;
718   }
719 
720   IncomingValueMap::const_iterator It = IncomingValues.find(BB);
721   if (It != IncomingValues.end()) return It->second;
722 
723   return OldVal;
724 }
725 
726 /// \brief Create a map from block to value for the operands of a
727 /// given phi.
728 ///
729 /// Create a map from block to value for each non-undef value flowing
730 /// into \p PN.
731 ///
732 /// \param PN The phi we are collecting the map for.
733 /// \param IncomingValues [out] The map from block to value for this phi.
734 static void gatherIncomingValuesToPhi(PHINode *PN,
735                                       IncomingValueMap &IncomingValues) {
736   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
737     BasicBlock *BB = PN->getIncomingBlock(i);
738     Value *V = PN->getIncomingValue(i);
739 
740     if (!isa<UndefValue>(V))
741       IncomingValues.insert(std::make_pair(BB, V));
742   }
743 }
744 
745 /// \brief Replace the incoming undef values to a phi with the values
746 /// from a block-to-value map.
747 ///
748 /// \param PN The phi we are replacing the undefs in.
749 /// \param IncomingValues A map from block to value.
750 static void replaceUndefValuesInPhi(PHINode *PN,
751                                     const IncomingValueMap &IncomingValues) {
752   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
753     Value *V = PN->getIncomingValue(i);
754 
755     if (!isa<UndefValue>(V)) continue;
756 
757     BasicBlock *BB = PN->getIncomingBlock(i);
758     IncomingValueMap::const_iterator It = IncomingValues.find(BB);
759     if (It == IncomingValues.end()) continue;
760 
761     PN->setIncomingValue(i, It->second);
762   }
763 }
764 
765 /// \brief Replace a value flowing from a block to a phi with
766 /// potentially multiple instances of that value flowing from the
767 /// block's predecessors to the phi.
768 ///
769 /// \param BB The block with the value flowing into the phi.
770 /// \param BBPreds The predecessors of BB.
771 /// \param PN The phi that we are updating.
772 static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
773                                                 const PredBlockVector &BBPreds,
774                                                 PHINode *PN) {
775   Value *OldVal = PN->removeIncomingValue(BB, false);
776   assert(OldVal && "No entry in PHI for Pred BB!");
777 
778   IncomingValueMap IncomingValues;
779 
780   // We are merging two blocks - BB, and the block containing PN - and
781   // as a result we need to redirect edges from the predecessors of BB
782   // to go to the block containing PN, and update PN
783   // accordingly. Since we allow merging blocks in the case where the
784   // predecessor and successor blocks both share some predecessors,
785   // and where some of those common predecessors might have undef
786   // values flowing into PN, we want to rewrite those values to be
787   // consistent with the non-undef values.
788 
789   gatherIncomingValuesToPhi(PN, IncomingValues);
790 
791   // If this incoming value is one of the PHI nodes in BB, the new entries
792   // in the PHI node are the entries from the old PHI.
793   if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
794     PHINode *OldValPN = cast<PHINode>(OldVal);
795     for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
796       // Note that, since we are merging phi nodes and BB and Succ might
797       // have common predecessors, we could end up with a phi node with
798       // identical incoming branches. This will be cleaned up later (and
799       // will trigger asserts if we try to clean it up now, without also
800       // simplifying the corresponding conditional branch).
801       BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
802       Value *PredVal = OldValPN->getIncomingValue(i);
803       Value *Selected = selectIncomingValueForBlock(PredVal, PredBB,
804                                                     IncomingValues);
805 
806       // And add a new incoming value for this predecessor for the
807       // newly retargeted branch.
808       PN->addIncoming(Selected, PredBB);
809     }
810   } else {
811     for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) {
812       // Update existing incoming values in PN for this
813       // predecessor of BB.
814       BasicBlock *PredBB = BBPreds[i];
815       Value *Selected = selectIncomingValueForBlock(OldVal, PredBB,
816                                                     IncomingValues);
817 
818       // And add a new incoming value for this predecessor for the
819       // newly retargeted branch.
820       PN->addIncoming(Selected, PredBB);
821     }
822   }
823 
824   replaceUndefValuesInPhi(PN, IncomingValues);
825 }
826 
827 /// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
828 /// unconditional branch, and contains no instructions other than PHI nodes,
829 /// potential side-effect free intrinsics and the branch.  If possible,
830 /// eliminate BB by rewriting all the predecessors to branch to the successor
831 /// block and return true.  If we can't transform, return false.
832 bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) {
833   assert(BB != &BB->getParent()->getEntryBlock() &&
834          "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
835 
836   // We can't eliminate infinite loops.
837   BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
838   if (BB == Succ) return false;
839 
840   // Check to see if merging these blocks would cause conflicts for any of the
841   // phi nodes in BB or Succ. If not, we can safely merge.
842   if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
843 
844   // Check for cases where Succ has multiple predecessors and a PHI node in BB
845   // has uses which will not disappear when the PHI nodes are merged.  It is
846   // possible to handle such cases, but difficult: it requires checking whether
847   // BB dominates Succ, which is non-trivial to calculate in the case where
848   // Succ has multiple predecessors.  Also, it requires checking whether
849   // constructing the necessary self-referential PHI node doesn't introduce any
850   // conflicts; this isn't too difficult, but the previous code for doing this
851   // was incorrect.
852   //
853   // Note that if this check finds a live use, BB dominates Succ, so BB is
854   // something like a loop pre-header (or rarely, a part of an irreducible CFG);
855   // folding the branch isn't profitable in that case anyway.
856   if (!Succ->getSinglePredecessor()) {
857     BasicBlock::iterator BBI = BB->begin();
858     while (isa<PHINode>(*BBI)) {
859       for (Use &U : BBI->uses()) {
860         if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
861           if (PN->getIncomingBlock(U) != BB)
862             return false;
863         } else {
864           return false;
865         }
866       }
867       ++BBI;
868     }
869   }
870 
871   DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
872 
873   if (isa<PHINode>(Succ->begin())) {
874     // If there is more than one pred of succ, and there are PHI nodes in
875     // the successor, then we need to add incoming edges for the PHI nodes
876     //
877     const PredBlockVector BBPreds(pred_begin(BB), pred_end(BB));
878 
879     // Loop over all of the PHI nodes in the successor of BB.
880     for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
881       PHINode *PN = cast<PHINode>(I);
882 
883       redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN);
884     }
885   }
886 
887   if (Succ->getSinglePredecessor()) {
888     // BB is the only predecessor of Succ, so Succ will end up with exactly
889     // the same predecessors BB had.
890 
891     // Copy over any phi, debug or lifetime instruction.
892     BB->getTerminator()->eraseFromParent();
893     Succ->getInstList().splice(Succ->getFirstNonPHI()->getIterator(),
894                                BB->getInstList());
895   } else {
896     while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
897       // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
898       assert(PN->use_empty() && "There shouldn't be any uses here!");
899       PN->eraseFromParent();
900     }
901   }
902 
903   // If the unconditional branch we replaced contains llvm.loop metadata, we
904   // add the metadata to the branch instructions in the predecessors.
905   unsigned LoopMDKind = BB->getContext().getMDKindID("llvm.loop");
906   Instruction *TI = BB->getTerminator();
907   if (TI)
908     if (MDNode *LoopMD = TI->getMetadata(LoopMDKind))
909       for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
910         BasicBlock *Pred = *PI;
911         Pred->getTerminator()->setMetadata(LoopMDKind, LoopMD);
912       }
913 
914   // Everything that jumped to BB now goes to Succ.
915   BB->replaceAllUsesWith(Succ);
916   if (!Succ->hasName()) Succ->takeName(BB);
917   BB->eraseFromParent();              // Delete the old basic block.
918   return true;
919 }
920 
921 /// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
922 /// nodes in this block. This doesn't try to be clever about PHI nodes
923 /// which differ only in the order of the incoming values, but instcombine
924 /// orders them so it usually won't matter.
925 ///
926 bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
927   // This implementation doesn't currently consider undef operands
928   // specially. Theoretically, two phis which are identical except for
929   // one having an undef where the other doesn't could be collapsed.
930 
931   struct PHIDenseMapInfo {
932     static PHINode *getEmptyKey() {
933       return DenseMapInfo<PHINode *>::getEmptyKey();
934     }
935     static PHINode *getTombstoneKey() {
936       return DenseMapInfo<PHINode *>::getTombstoneKey();
937     }
938     static unsigned getHashValue(PHINode *PN) {
939       // Compute a hash value on the operands. Instcombine will likely have
940       // sorted them, which helps expose duplicates, but we have to check all
941       // the operands to be safe in case instcombine hasn't run.
942       return static_cast<unsigned>(hash_combine(
943           hash_combine_range(PN->value_op_begin(), PN->value_op_end()),
944           hash_combine_range(PN->block_begin(), PN->block_end())));
945     }
946     static bool isEqual(PHINode *LHS, PHINode *RHS) {
947       if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
948           RHS == getEmptyKey() || RHS == getTombstoneKey())
949         return LHS == RHS;
950       return LHS->isIdenticalTo(RHS);
951     }
952   };
953 
954   // Set of unique PHINodes.
955   DenseSet<PHINode *, PHIDenseMapInfo> PHISet;
956 
957   // Examine each PHI.
958   bool Changed = false;
959   for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I++);) {
960     auto Inserted = PHISet.insert(PN);
961     if (!Inserted.second) {
962       // A duplicate. Replace this PHI with its duplicate.
963       PN->replaceAllUsesWith(*Inserted.first);
964       PN->eraseFromParent();
965       Changed = true;
966 
967       // The RAUW can change PHIs that we already visited. Start over from the
968       // beginning.
969       PHISet.clear();
970       I = BB->begin();
971     }
972   }
973 
974   return Changed;
975 }
976 
977 /// enforceKnownAlignment - If the specified pointer points to an object that
978 /// we control, modify the object's alignment to PrefAlign. This isn't
979 /// often possible though. If alignment is important, a more reliable approach
980 /// is to simply align all global variables and allocation instructions to
981 /// their preferred alignment from the beginning.
982 ///
983 static unsigned enforceKnownAlignment(Value *V, unsigned Align,
984                                       unsigned PrefAlign,
985                                       const DataLayout &DL) {
986   assert(PrefAlign > Align);
987 
988   V = V->stripPointerCasts();
989 
990   if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
991     // TODO: ideally, computeKnownBits ought to have used
992     // AllocaInst::getAlignment() in its computation already, making
993     // the below max redundant. But, as it turns out,
994     // stripPointerCasts recurses through infinite layers of bitcasts,
995     // while computeKnownBits is not allowed to traverse more than 6
996     // levels.
997     Align = std::max(AI->getAlignment(), Align);
998     if (PrefAlign <= Align)
999       return Align;
1000 
1001     // If the preferred alignment is greater than the natural stack alignment
1002     // then don't round up. This avoids dynamic stack realignment.
1003     if (DL.exceedsNaturalStackAlignment(PrefAlign))
1004       return Align;
1005     AI->setAlignment(PrefAlign);
1006     return PrefAlign;
1007   }
1008 
1009   if (auto *GO = dyn_cast<GlobalObject>(V)) {
1010     // TODO: as above, this shouldn't be necessary.
1011     Align = std::max(GO->getAlignment(), Align);
1012     if (PrefAlign <= Align)
1013       return Align;
1014 
1015     // If there is a large requested alignment and we can, bump up the alignment
1016     // of the global.  If the memory we set aside for the global may not be the
1017     // memory used by the final program then it is impossible for us to reliably
1018     // enforce the preferred alignment.
1019     if (!GO->canIncreaseAlignment())
1020       return Align;
1021 
1022     GO->setAlignment(PrefAlign);
1023     return PrefAlign;
1024   }
1025 
1026   return Align;
1027 }
1028 
1029 unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
1030                                           const DataLayout &DL,
1031                                           const Instruction *CxtI,
1032                                           AssumptionCache *AC,
1033                                           const DominatorTree *DT) {
1034   assert(V->getType()->isPointerTy() &&
1035          "getOrEnforceKnownAlignment expects a pointer!");
1036   unsigned BitWidth = DL.getPointerTypeSizeInBits(V->getType());
1037 
1038   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1039   computeKnownBits(V, KnownZero, KnownOne, DL, 0, AC, CxtI, DT);
1040   unsigned TrailZ = KnownZero.countTrailingOnes();
1041 
1042   // Avoid trouble with ridiculously large TrailZ values, such as
1043   // those computed from a null pointer.
1044   TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
1045 
1046   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
1047 
1048   // LLVM doesn't support alignments larger than this currently.
1049   Align = std::min(Align, +Value::MaximumAlignment);
1050 
1051   if (PrefAlign > Align)
1052     Align = enforceKnownAlignment(V, Align, PrefAlign, DL);
1053 
1054   // We don't need to make any adjustment.
1055   return Align;
1056 }
1057 
1058 ///===---------------------------------------------------------------------===//
1059 ///  Dbg Intrinsic utilities
1060 ///
1061 
1062 /// See if there is a dbg.value intrinsic for DIVar before I.
1063 static bool LdStHasDebugValue(DILocalVariable *DIVar, DIExpression *DIExpr,
1064                               Instruction *I) {
1065   // Since we can't guarantee that the original dbg.declare instrinsic
1066   // is removed by LowerDbgDeclare(), we need to make sure that we are
1067   // not inserting the same dbg.value intrinsic over and over.
1068   llvm::BasicBlock::InstListType::iterator PrevI(I);
1069   if (PrevI != I->getParent()->getInstList().begin()) {
1070     --PrevI;
1071     if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(PrevI))
1072       if (DVI->getValue() == I->getOperand(0) &&
1073           DVI->getOffset() == 0 &&
1074           DVI->getVariable() == DIVar &&
1075           DVI->getExpression() == DIExpr)
1076         return true;
1077   }
1078   return false;
1079 }
1080 
1081 /// See if there is a dbg.value intrinsic for DIVar for the PHI node.
1082 static bool PhiHasDebugValue(DILocalVariable *DIVar,
1083                              DIExpression *DIExpr,
1084                              PHINode *APN) {
1085   // Since we can't guarantee that the original dbg.declare instrinsic
1086   // is removed by LowerDbgDeclare(), we need to make sure that we are
1087   // not inserting the same dbg.value intrinsic over and over.
1088   SmallVector<DbgValueInst *, 1> DbgValues;
1089   findDbgValues(DbgValues, APN);
1090   for (auto *DVI : DbgValues) {
1091     assert(DVI->getValue() == APN);
1092     assert(DVI->getOffset() == 0);
1093     if ((DVI->getVariable() == DIVar) && (DVI->getExpression() == DIExpr))
1094       return true;
1095   }
1096   return false;
1097 }
1098 
1099 /// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
1100 /// that has an associated llvm.dbg.decl intrinsic.
1101 void llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
1102                                            StoreInst *SI, DIBuilder &Builder) {
1103   auto *DIVar = DDI->getVariable();
1104   auto *DIExpr = DDI->getExpression();
1105   assert(DIVar && "Missing variable");
1106 
1107   // If an argument is zero extended then use argument directly. The ZExt
1108   // may be zapped by an optimization pass in future.
1109   Argument *ExtendedArg = nullptr;
1110   if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1111     ExtendedArg = dyn_cast<Argument>(ZExt->getOperand(0));
1112   if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1113     ExtendedArg = dyn_cast<Argument>(SExt->getOperand(0));
1114   if (ExtendedArg) {
1115     // We're now only describing a subset of the variable. The fragment we're
1116     // describing will always be smaller than the variable size, because
1117     // VariableSize == Size of Alloca described by DDI. Since SI stores
1118     // to the alloca described by DDI, if it's first operand is an extend,
1119     // we're guaranteed that before extension, the value was narrower than
1120     // the size of the alloca, hence the size of the described variable.
1121     SmallVector<uint64_t, 3> Ops;
1122     unsigned FragmentOffset = 0;
1123     // If this already is a bit fragment, we drop the bit fragment from the
1124     // expression and record the offset.
1125     auto Fragment = DIExpr->getFragmentInfo();
1126     if (Fragment) {
1127       Ops.append(DIExpr->elements_begin(), DIExpr->elements_end()-3);
1128       FragmentOffset = Fragment->OffsetInBits;
1129     } else {
1130       Ops.append(DIExpr->elements_begin(), DIExpr->elements_end());
1131     }
1132     Ops.push_back(dwarf::DW_OP_LLVM_fragment);
1133     Ops.push_back(FragmentOffset);
1134     const DataLayout &DL = DDI->getModule()->getDataLayout();
1135     Ops.push_back(DL.getTypeSizeInBits(ExtendedArg->getType()));
1136     auto NewDIExpr = Builder.createExpression(Ops);
1137     if (!LdStHasDebugValue(DIVar, NewDIExpr, SI))
1138       Builder.insertDbgValueIntrinsic(ExtendedArg, 0, DIVar, NewDIExpr,
1139                                       DDI->getDebugLoc(), SI);
1140   } else if (!LdStHasDebugValue(DIVar, DIExpr, SI))
1141     Builder.insertDbgValueIntrinsic(SI->getOperand(0), 0, DIVar, DIExpr,
1142                                     DDI->getDebugLoc(), SI);
1143 }
1144 
1145 /// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
1146 /// that has an associated llvm.dbg.decl intrinsic.
1147 void llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
1148                                            LoadInst *LI, DIBuilder &Builder) {
1149   auto *DIVar = DDI->getVariable();
1150   auto *DIExpr = DDI->getExpression();
1151   assert(DIVar && "Missing variable");
1152 
1153   if (LdStHasDebugValue(DIVar, DIExpr, LI))
1154     return;
1155 
1156   // We are now tracking the loaded value instead of the address. In the
1157   // future if multi-location support is added to the IR, it might be
1158   // preferable to keep tracking both the loaded value and the original
1159   // address in case the alloca can not be elided.
1160   Instruction *DbgValue = Builder.insertDbgValueIntrinsic(
1161       LI, 0, DIVar, DIExpr, DDI->getDebugLoc(), (Instruction *)nullptr);
1162   DbgValue->insertAfter(LI);
1163 }
1164 
1165 /// Inserts a llvm.dbg.value intrinsic after a phi
1166 /// that has an associated llvm.dbg.decl intrinsic.
1167 void llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
1168                                            PHINode *APN, DIBuilder &Builder) {
1169   auto *DIVar = DDI->getVariable();
1170   auto *DIExpr = DDI->getExpression();
1171   assert(DIVar && "Missing variable");
1172 
1173   if (PhiHasDebugValue(DIVar, DIExpr, APN))
1174     return;
1175 
1176   BasicBlock *BB = APN->getParent();
1177   auto InsertionPt = BB->getFirstInsertionPt();
1178 
1179   // The block may be a catchswitch block, which does not have a valid
1180   // insertion point.
1181   // FIXME: Insert dbg.value markers in the successors when appropriate.
1182   if (InsertionPt != BB->end())
1183     Builder.insertDbgValueIntrinsic(APN, 0, DIVar, DIExpr, DDI->getDebugLoc(),
1184                                     &*InsertionPt);
1185 }
1186 
1187 /// Determine whether this alloca is either a VLA or an array.
1188 static bool isArray(AllocaInst *AI) {
1189   return AI->isArrayAllocation() ||
1190     AI->getType()->getElementType()->isArrayTy();
1191 }
1192 
1193 /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
1194 /// of llvm.dbg.value intrinsics.
1195 bool llvm::LowerDbgDeclare(Function &F) {
1196   DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
1197   SmallVector<DbgDeclareInst *, 4> Dbgs;
1198   for (auto &FI : F)
1199     for (Instruction &BI : FI)
1200       if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
1201         Dbgs.push_back(DDI);
1202 
1203   if (Dbgs.empty())
1204     return false;
1205 
1206   for (auto &I : Dbgs) {
1207     DbgDeclareInst *DDI = I;
1208     AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
1209     // If this is an alloca for a scalar variable, insert a dbg.value
1210     // at each load and store to the alloca and erase the dbg.declare.
1211     // The dbg.values allow tracking a variable even if it is not
1212     // stored on the stack, while the dbg.declare can only describe
1213     // the stack slot (and at a lexical-scope granularity). Later
1214     // passes will attempt to elide the stack slot.
1215     if (AI && !isArray(AI)) {
1216       for (auto &AIUse : AI->uses()) {
1217         User *U = AIUse.getUser();
1218         if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1219           if (AIUse.getOperandNo() == 1)
1220             ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1221         } else if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1222           ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1223         } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
1224           // This is a call by-value or some other instruction that
1225           // takes a pointer to the variable. Insert a *value*
1226           // intrinsic that describes the alloca.
1227           SmallVector<uint64_t, 1> NewDIExpr;
1228           auto *DIExpr = DDI->getExpression();
1229           NewDIExpr.push_back(dwarf::DW_OP_deref);
1230           NewDIExpr.append(DIExpr->elements_begin(), DIExpr->elements_end());
1231           DIB.insertDbgValueIntrinsic(AI, 0, DDI->getVariable(),
1232                                       DIB.createExpression(NewDIExpr),
1233                                       DDI->getDebugLoc(), CI);
1234         }
1235       }
1236       DDI->eraseFromParent();
1237     }
1238   }
1239   return true;
1240 }
1241 
1242 /// FindAllocaDbgDeclare - Finds the llvm.dbg.declare intrinsic describing the
1243 /// alloca 'V', if any.
1244 DbgDeclareInst *llvm::FindAllocaDbgDeclare(Value *V) {
1245   if (auto *L = LocalAsMetadata::getIfExists(V))
1246     if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
1247       for (User *U : MDV->users())
1248         if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
1249           return DDI;
1250 
1251   return nullptr;
1252 }
1253 
1254 void llvm::findDbgValues(SmallVectorImpl<DbgValueInst *> &DbgValues, Value *V) {
1255   if (auto *L = LocalAsMetadata::getIfExists(V))
1256     if (auto *MDV = MetadataAsValue::getIfExists(V->getContext(), L))
1257       for (User *U : MDV->users())
1258         if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
1259           DbgValues.push_back(DVI);
1260 }
1261 
1262 static void appendOffset(SmallVectorImpl<uint64_t> &Ops, int64_t Offset) {
1263   if (Offset > 0) {
1264     Ops.push_back(dwarf::DW_OP_plus);
1265     Ops.push_back(Offset);
1266   } else if (Offset < 0) {
1267     Ops.push_back(dwarf::DW_OP_minus);
1268     Ops.push_back(-Offset);
1269   }
1270 }
1271 
1272 /// Prepend \p DIExpr with a deref and offset operation.
1273 static DIExpression *prependDIExpr(DIBuilder &Builder, DIExpression *DIExpr,
1274                                    bool Deref, int64_t Offset) {
1275   if (!Deref && !Offset)
1276     return DIExpr;
1277   // Create a copy of the original DIDescriptor for user variable, prepending
1278   // "deref" operation to a list of address elements, as new llvm.dbg.declare
1279   // will take a value storing address of the memory for variable, not
1280   // alloca itself.
1281   SmallVector<uint64_t, 4> Ops;
1282   if (Deref)
1283     Ops.push_back(dwarf::DW_OP_deref);
1284   appendOffset(Ops, Offset);
1285   if (DIExpr)
1286     Ops.append(DIExpr->elements_begin(), DIExpr->elements_end());
1287   return Builder.createExpression(Ops);
1288 }
1289 
1290 bool llvm::replaceDbgDeclare(Value *Address, Value *NewAddress,
1291                              Instruction *InsertBefore, DIBuilder &Builder,
1292                              bool Deref, int Offset) {
1293   DbgDeclareInst *DDI = FindAllocaDbgDeclare(Address);
1294   if (!DDI)
1295     return false;
1296   DebugLoc Loc = DDI->getDebugLoc();
1297   auto *DIVar = DDI->getVariable();
1298   auto *DIExpr = DDI->getExpression();
1299   assert(DIVar && "Missing variable");
1300 
1301   DIExpr = prependDIExpr(Builder, DIExpr, Deref, Offset);
1302 
1303   // Insert llvm.dbg.declare immediately after the original alloca, and remove
1304   // old llvm.dbg.declare.
1305   Builder.insertDeclare(NewAddress, DIVar, DIExpr, Loc, InsertBefore);
1306   DDI->eraseFromParent();
1307   return true;
1308 }
1309 
1310 bool llvm::replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
1311                                       DIBuilder &Builder, bool Deref, int Offset) {
1312   return replaceDbgDeclare(AI, NewAllocaAddress, AI->getNextNode(), Builder,
1313                            Deref, Offset);
1314 }
1315 
1316 static void replaceOneDbgValueForAlloca(DbgValueInst *DVI, Value *NewAddress,
1317                                         DIBuilder &Builder, int Offset) {
1318   DebugLoc Loc = DVI->getDebugLoc();
1319   auto *DIVar = DVI->getVariable();
1320   auto *DIExpr = DVI->getExpression();
1321   assert(DIVar && "Missing variable");
1322 
1323   // This is an alloca-based llvm.dbg.value. The first thing it should do with
1324   // the alloca pointer is dereference it. Otherwise we don't know how to handle
1325   // it and give up.
1326   if (!DIExpr || DIExpr->getNumElements() < 1 ||
1327       DIExpr->getElement(0) != dwarf::DW_OP_deref)
1328     return;
1329 
1330   // Insert the offset immediately after the first deref.
1331   // We could just change the offset argument of dbg.value, but it's unsigned...
1332   if (Offset) {
1333     SmallVector<uint64_t, 4> Ops;
1334     Ops.push_back(dwarf::DW_OP_deref);
1335     appendOffset(Ops, Offset);
1336     Ops.append(DIExpr->elements_begin() + 1, DIExpr->elements_end());
1337     DIExpr = Builder.createExpression(Ops);
1338   }
1339 
1340   Builder.insertDbgValueIntrinsic(NewAddress, DVI->getOffset(), DIVar, DIExpr,
1341                                   Loc, DVI);
1342   DVI->eraseFromParent();
1343 }
1344 
1345 void llvm::replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
1346                                     DIBuilder &Builder, int Offset) {
1347   if (auto *L = LocalAsMetadata::getIfExists(AI))
1348     if (auto *MDV = MetadataAsValue::getIfExists(AI->getContext(), L))
1349       for (auto UI = MDV->use_begin(), UE = MDV->use_end(); UI != UE;) {
1350         Use &U = *UI++;
1351         if (auto *DVI = dyn_cast<DbgValueInst>(U.getUser()))
1352           replaceOneDbgValueForAlloca(DVI, NewAllocaAddress, Builder, Offset);
1353       }
1354 }
1355 
1356 void llvm::salvageDebugInfo(Instruction &I) {
1357   SmallVector<DbgValueInst *, 1> DbgValues;
1358   auto &M = *I.getModule();
1359 
1360   auto MDWrap = [&](Value *V) {
1361     return MetadataAsValue::get(I.getContext(), ValueAsMetadata::get(V));
1362   };
1363 
1364   if (isa<BitCastInst>(&I)) {
1365     findDbgValues(DbgValues, &I);
1366     for (auto *DVI : DbgValues) {
1367       // Bitcasts are entirely irrelevant for debug info. Rewrite the dbg.value
1368       // to use the cast's source.
1369       DVI->setOperand(0, MDWrap(I.getOperand(0)));
1370       DEBUG(dbgs() << "SALVAGE: " << *DVI << '\n');
1371     }
1372   } else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1373     findDbgValues(DbgValues, &I);
1374     for (auto *DVI : DbgValues) {
1375       unsigned BitWidth =
1376           M.getDataLayout().getPointerSizeInBits(GEP->getPointerAddressSpace());
1377       APInt Offset(BitWidth, 0);
1378       // Rewrite a constant GEP into a DIExpression.
1379       if (GEP->accumulateConstantOffset(M.getDataLayout(), Offset)) {
1380         auto *DIExpr = DVI->getExpression();
1381         DIBuilder DIB(M, /*AllowUnresolved*/ false);
1382         // GEP offsets are i32 and thus alwaus fit into an int64_t.
1383         DIExpr = prependDIExpr(DIB, DIExpr, NoDeref, Offset.getSExtValue());
1384         DVI->setOperand(0, MDWrap(I.getOperand(0)));
1385         DVI->setOperand(3, MetadataAsValue::get(I.getContext(), DIExpr));
1386         DEBUG(dbgs() << "SALVAGE: " << *DVI << '\n');
1387       }
1388     }
1389   } else if (isa<LoadInst>(&I)) {
1390     findDbgValues(DbgValues, &I);
1391     for (auto *DVI : DbgValues) {
1392       // Rewrite the load into DW_OP_deref.
1393       auto *DIExpr = DVI->getExpression();
1394       DIBuilder DIB(M, /*AllowUnresolved*/ false);
1395       DIExpr = prependDIExpr(DIB, DIExpr, WithDeref, 0);
1396       DVI->setOperand(0, MDWrap(I.getOperand(0)));
1397       DVI->setOperand(3, MetadataAsValue::get(I.getContext(), DIExpr));
1398       DEBUG(dbgs() << "SALVAGE:  " << *DVI << '\n');
1399     }
1400   }
1401 }
1402 
1403 unsigned llvm::removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB) {
1404   unsigned NumDeadInst = 0;
1405   // Delete the instructions backwards, as it has a reduced likelihood of
1406   // having to update as many def-use and use-def chains.
1407   Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
1408   while (EndInst != &BB->front()) {
1409     // Delete the next to last instruction.
1410     Instruction *Inst = &*--EndInst->getIterator();
1411     if (!Inst->use_empty() && !Inst->getType()->isTokenTy())
1412       Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
1413     if (Inst->isEHPad() || Inst->getType()->isTokenTy()) {
1414       EndInst = Inst;
1415       continue;
1416     }
1417     if (!isa<DbgInfoIntrinsic>(Inst))
1418       ++NumDeadInst;
1419     Inst->eraseFromParent();
1420   }
1421   return NumDeadInst;
1422 }
1423 
1424 unsigned llvm::changeToUnreachable(Instruction *I, bool UseLLVMTrap,
1425                                    bool PreserveLCSSA) {
1426   BasicBlock *BB = I->getParent();
1427   // Loop over all of the successors, removing BB's entry from any PHI
1428   // nodes.
1429   for (BasicBlock *Successor : successors(BB))
1430     Successor->removePredecessor(BB, PreserveLCSSA);
1431 
1432   // Insert a call to llvm.trap right before this.  This turns the undefined
1433   // behavior into a hard fail instead of falling through into random code.
1434   if (UseLLVMTrap) {
1435     Function *TrapFn =
1436       Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap);
1437     CallInst *CallTrap = CallInst::Create(TrapFn, "", I);
1438     CallTrap->setDebugLoc(I->getDebugLoc());
1439   }
1440   new UnreachableInst(I->getContext(), I);
1441 
1442   // All instructions after this are dead.
1443   unsigned NumInstrsRemoved = 0;
1444   BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end();
1445   while (BBI != BBE) {
1446     if (!BBI->use_empty())
1447       BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
1448     BB->getInstList().erase(BBI++);
1449     ++NumInstrsRemoved;
1450   }
1451   return NumInstrsRemoved;
1452 }
1453 
1454 /// changeToCall - Convert the specified invoke into a normal call.
1455 static void changeToCall(InvokeInst *II) {
1456   SmallVector<Value*, 8> Args(II->arg_begin(), II->arg_end());
1457   SmallVector<OperandBundleDef, 1> OpBundles;
1458   II->getOperandBundlesAsDefs(OpBundles);
1459   CallInst *NewCall = CallInst::Create(II->getCalledValue(), Args, OpBundles,
1460                                        "", II);
1461   NewCall->takeName(II);
1462   NewCall->setCallingConv(II->getCallingConv());
1463   NewCall->setAttributes(II->getAttributes());
1464   NewCall->setDebugLoc(II->getDebugLoc());
1465   II->replaceAllUsesWith(NewCall);
1466 
1467   // Follow the call by a branch to the normal destination.
1468   BranchInst::Create(II->getNormalDest(), II);
1469 
1470   // Update PHI nodes in the unwind destination
1471   II->getUnwindDest()->removePredecessor(II->getParent());
1472   II->eraseFromParent();
1473 }
1474 
1475 BasicBlock *llvm::changeToInvokeAndSplitBasicBlock(CallInst *CI,
1476                                                    BasicBlock *UnwindEdge) {
1477   BasicBlock *BB = CI->getParent();
1478 
1479   // Convert this function call into an invoke instruction.  First, split the
1480   // basic block.
1481   BasicBlock *Split =
1482       BB->splitBasicBlock(CI->getIterator(), CI->getName() + ".noexc");
1483 
1484   // Delete the unconditional branch inserted by splitBasicBlock
1485   BB->getInstList().pop_back();
1486 
1487   // Create the new invoke instruction.
1488   SmallVector<Value *, 8> InvokeArgs(CI->arg_begin(), CI->arg_end());
1489   SmallVector<OperandBundleDef, 1> OpBundles;
1490 
1491   CI->getOperandBundlesAsDefs(OpBundles);
1492 
1493   // Note: we're round tripping operand bundles through memory here, and that
1494   // can potentially be avoided with a cleverer API design that we do not have
1495   // as of this time.
1496 
1497   InvokeInst *II = InvokeInst::Create(CI->getCalledValue(), Split, UnwindEdge,
1498                                       InvokeArgs, OpBundles, CI->getName(), BB);
1499   II->setDebugLoc(CI->getDebugLoc());
1500   II->setCallingConv(CI->getCallingConv());
1501   II->setAttributes(CI->getAttributes());
1502 
1503   // Make sure that anything using the call now uses the invoke!  This also
1504   // updates the CallGraph if present, because it uses a WeakVH.
1505   CI->replaceAllUsesWith(II);
1506 
1507   // Delete the original call
1508   Split->getInstList().pop_front();
1509   return Split;
1510 }
1511 
1512 static bool markAliveBlocks(Function &F,
1513                             SmallPtrSetImpl<BasicBlock*> &Reachable) {
1514 
1515   SmallVector<BasicBlock*, 128> Worklist;
1516   BasicBlock *BB = &F.front();
1517   Worklist.push_back(BB);
1518   Reachable.insert(BB);
1519   bool Changed = false;
1520   do {
1521     BB = Worklist.pop_back_val();
1522 
1523     // Do a quick scan of the basic block, turning any obviously unreachable
1524     // instructions into LLVM unreachable insts.  The instruction combining pass
1525     // canonicalizes unreachable insts into stores to null or undef.
1526     for (Instruction &I : *BB) {
1527       // Assumptions that are known to be false are equivalent to unreachable.
1528       // Also, if the condition is undefined, then we make the choice most
1529       // beneficial to the optimizer, and choose that to also be unreachable.
1530       if (auto *II = dyn_cast<IntrinsicInst>(&I)) {
1531         if (II->getIntrinsicID() == Intrinsic::assume) {
1532           if (match(II->getArgOperand(0), m_CombineOr(m_Zero(), m_Undef()))) {
1533             // Don't insert a call to llvm.trap right before the unreachable.
1534             changeToUnreachable(II, false);
1535             Changed = true;
1536             break;
1537           }
1538         }
1539 
1540         if (II->getIntrinsicID() == Intrinsic::experimental_guard) {
1541           // A call to the guard intrinsic bails out of the current compilation
1542           // unit if the predicate passed to it is false.  If the predicate is a
1543           // constant false, then we know the guard will bail out of the current
1544           // compile unconditionally, so all code following it is dead.
1545           //
1546           // Note: unlike in llvm.assume, it is not "obviously profitable" for
1547           // guards to treat `undef` as `false` since a guard on `undef` can
1548           // still be useful for widening.
1549           if (match(II->getArgOperand(0), m_Zero()))
1550             if (!isa<UnreachableInst>(II->getNextNode())) {
1551               changeToUnreachable(II->getNextNode(), /*UseLLVMTrap=*/ false);
1552               Changed = true;
1553               break;
1554             }
1555         }
1556       }
1557 
1558       if (auto *CI = dyn_cast<CallInst>(&I)) {
1559         Value *Callee = CI->getCalledValue();
1560         if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
1561           changeToUnreachable(CI, /*UseLLVMTrap=*/false);
1562           Changed = true;
1563           break;
1564         }
1565         if (CI->doesNotReturn()) {
1566           // If we found a call to a no-return function, insert an unreachable
1567           // instruction after it.  Make sure there isn't *already* one there
1568           // though.
1569           if (!isa<UnreachableInst>(CI->getNextNode())) {
1570             // Don't insert a call to llvm.trap right before the unreachable.
1571             changeToUnreachable(CI->getNextNode(), false);
1572             Changed = true;
1573           }
1574           break;
1575         }
1576       }
1577 
1578       // Store to undef and store to null are undefined and used to signal that
1579       // they should be changed to unreachable by passes that can't modify the
1580       // CFG.
1581       if (auto *SI = dyn_cast<StoreInst>(&I)) {
1582         // Don't touch volatile stores.
1583         if (SI->isVolatile()) continue;
1584 
1585         Value *Ptr = SI->getOperand(1);
1586 
1587         if (isa<UndefValue>(Ptr) ||
1588             (isa<ConstantPointerNull>(Ptr) &&
1589              SI->getPointerAddressSpace() == 0)) {
1590           changeToUnreachable(SI, true);
1591           Changed = true;
1592           break;
1593         }
1594       }
1595     }
1596 
1597     TerminatorInst *Terminator = BB->getTerminator();
1598     if (auto *II = dyn_cast<InvokeInst>(Terminator)) {
1599       // Turn invokes that call 'nounwind' functions into ordinary calls.
1600       Value *Callee = II->getCalledValue();
1601       if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
1602         changeToUnreachable(II, true);
1603         Changed = true;
1604       } else if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(&F)) {
1605         if (II->use_empty() && II->onlyReadsMemory()) {
1606           // jump to the normal destination branch.
1607           BranchInst::Create(II->getNormalDest(), II);
1608           II->getUnwindDest()->removePredecessor(II->getParent());
1609           II->eraseFromParent();
1610         } else
1611           changeToCall(II);
1612         Changed = true;
1613       }
1614     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) {
1615       // Remove catchpads which cannot be reached.
1616       struct CatchPadDenseMapInfo {
1617         static CatchPadInst *getEmptyKey() {
1618           return DenseMapInfo<CatchPadInst *>::getEmptyKey();
1619         }
1620         static CatchPadInst *getTombstoneKey() {
1621           return DenseMapInfo<CatchPadInst *>::getTombstoneKey();
1622         }
1623         static unsigned getHashValue(CatchPadInst *CatchPad) {
1624           return static_cast<unsigned>(hash_combine_range(
1625               CatchPad->value_op_begin(), CatchPad->value_op_end()));
1626         }
1627         static bool isEqual(CatchPadInst *LHS, CatchPadInst *RHS) {
1628           if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
1629               RHS == getEmptyKey() || RHS == getTombstoneKey())
1630             return LHS == RHS;
1631           return LHS->isIdenticalTo(RHS);
1632         }
1633       };
1634 
1635       // Set of unique CatchPads.
1636       SmallDenseMap<CatchPadInst *, detail::DenseSetEmpty, 4,
1637                     CatchPadDenseMapInfo, detail::DenseSetPair<CatchPadInst *>>
1638           HandlerSet;
1639       detail::DenseSetEmpty Empty;
1640       for (CatchSwitchInst::handler_iterator I = CatchSwitch->handler_begin(),
1641                                              E = CatchSwitch->handler_end();
1642            I != E; ++I) {
1643         BasicBlock *HandlerBB = *I;
1644         auto *CatchPad = cast<CatchPadInst>(HandlerBB->getFirstNonPHI());
1645         if (!HandlerSet.insert({CatchPad, Empty}).second) {
1646           CatchSwitch->removeHandler(I);
1647           --I;
1648           --E;
1649           Changed = true;
1650         }
1651       }
1652     }
1653 
1654     Changed |= ConstantFoldTerminator(BB, true);
1655     for (BasicBlock *Successor : successors(BB))
1656       if (Reachable.insert(Successor).second)
1657         Worklist.push_back(Successor);
1658   } while (!Worklist.empty());
1659   return Changed;
1660 }
1661 
1662 void llvm::removeUnwindEdge(BasicBlock *BB) {
1663   TerminatorInst *TI = BB->getTerminator();
1664 
1665   if (auto *II = dyn_cast<InvokeInst>(TI)) {
1666     changeToCall(II);
1667     return;
1668   }
1669 
1670   TerminatorInst *NewTI;
1671   BasicBlock *UnwindDest;
1672 
1673   if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
1674     NewTI = CleanupReturnInst::Create(CRI->getCleanupPad(), nullptr, CRI);
1675     UnwindDest = CRI->getUnwindDest();
1676   } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
1677     auto *NewCatchSwitch = CatchSwitchInst::Create(
1678         CatchSwitch->getParentPad(), nullptr, CatchSwitch->getNumHandlers(),
1679         CatchSwitch->getName(), CatchSwitch);
1680     for (BasicBlock *PadBB : CatchSwitch->handlers())
1681       NewCatchSwitch->addHandler(PadBB);
1682 
1683     NewTI = NewCatchSwitch;
1684     UnwindDest = CatchSwitch->getUnwindDest();
1685   } else {
1686     llvm_unreachable("Could not find unwind successor");
1687   }
1688 
1689   NewTI->takeName(TI);
1690   NewTI->setDebugLoc(TI->getDebugLoc());
1691   UnwindDest->removePredecessor(BB);
1692   TI->replaceAllUsesWith(NewTI);
1693   TI->eraseFromParent();
1694 }
1695 
1696 /// removeUnreachableBlocksFromFn - Remove blocks that are not reachable, even
1697 /// if they are in a dead cycle.  Return true if a change was made, false
1698 /// otherwise.
1699 bool llvm::removeUnreachableBlocks(Function &F, LazyValueInfo *LVI) {
1700   SmallPtrSet<BasicBlock*, 16> Reachable;
1701   bool Changed = markAliveBlocks(F, Reachable);
1702 
1703   // If there are unreachable blocks in the CFG...
1704   if (Reachable.size() == F.size())
1705     return Changed;
1706 
1707   assert(Reachable.size() < F.size());
1708   NumRemoved += F.size()-Reachable.size();
1709 
1710   // Loop over all of the basic blocks that are not reachable, dropping all of
1711   // their internal references...
1712   for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB) {
1713     if (Reachable.count(&*BB))
1714       continue;
1715 
1716     for (BasicBlock *Successor : successors(&*BB))
1717       if (Reachable.count(Successor))
1718         Successor->removePredecessor(&*BB);
1719     if (LVI)
1720       LVI->eraseBlock(&*BB);
1721     BB->dropAllReferences();
1722   }
1723 
1724   for (Function::iterator I = ++F.begin(); I != F.end();)
1725     if (!Reachable.count(&*I))
1726       I = F.getBasicBlockList().erase(I);
1727     else
1728       ++I;
1729 
1730   return true;
1731 }
1732 
1733 void llvm::combineMetadata(Instruction *K, const Instruction *J,
1734                            ArrayRef<unsigned> KnownIDs) {
1735   SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
1736   K->dropUnknownNonDebugMetadata(KnownIDs);
1737   K->getAllMetadataOtherThanDebugLoc(Metadata);
1738   for (const auto &MD : Metadata) {
1739     unsigned Kind = MD.first;
1740     MDNode *JMD = J->getMetadata(Kind);
1741     MDNode *KMD = MD.second;
1742 
1743     switch (Kind) {
1744       default:
1745         K->setMetadata(Kind, nullptr); // Remove unknown metadata
1746         break;
1747       case LLVMContext::MD_dbg:
1748         llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
1749       case LLVMContext::MD_tbaa:
1750         K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
1751         break;
1752       case LLVMContext::MD_alias_scope:
1753         K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD));
1754         break;
1755       case LLVMContext::MD_noalias:
1756       case LLVMContext::MD_mem_parallel_loop_access:
1757         K->setMetadata(Kind, MDNode::intersect(JMD, KMD));
1758         break;
1759       case LLVMContext::MD_range:
1760         K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD));
1761         break;
1762       case LLVMContext::MD_fpmath:
1763         K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
1764         break;
1765       case LLVMContext::MD_invariant_load:
1766         // Only set the !invariant.load if it is present in both instructions.
1767         K->setMetadata(Kind, JMD);
1768         break;
1769       case LLVMContext::MD_nonnull:
1770         // Only set the !nonnull if it is present in both instructions.
1771         K->setMetadata(Kind, JMD);
1772         break;
1773       case LLVMContext::MD_invariant_group:
1774         // Preserve !invariant.group in K.
1775         break;
1776       case LLVMContext::MD_align:
1777         K->setMetadata(Kind,
1778           MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
1779         break;
1780       case LLVMContext::MD_dereferenceable:
1781       case LLVMContext::MD_dereferenceable_or_null:
1782         K->setMetadata(Kind,
1783           MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
1784         break;
1785     }
1786   }
1787   // Set !invariant.group from J if J has it. If both instructions have it
1788   // then we will just pick it from J - even when they are different.
1789   // Also make sure that K is load or store - f.e. combining bitcast with load
1790   // could produce bitcast with invariant.group metadata, which is invalid.
1791   // FIXME: we should try to preserve both invariant.group md if they are
1792   // different, but right now instruction can only have one invariant.group.
1793   if (auto *JMD = J->getMetadata(LLVMContext::MD_invariant_group))
1794     if (isa<LoadInst>(K) || isa<StoreInst>(K))
1795       K->setMetadata(LLVMContext::MD_invariant_group, JMD);
1796 }
1797 
1798 void llvm::combineMetadataForCSE(Instruction *K, const Instruction *J) {
1799   unsigned KnownIDs[] = {
1800       LLVMContext::MD_tbaa,            LLVMContext::MD_alias_scope,
1801       LLVMContext::MD_noalias,         LLVMContext::MD_range,
1802       LLVMContext::MD_invariant_load,  LLVMContext::MD_nonnull,
1803       LLVMContext::MD_invariant_group, LLVMContext::MD_align,
1804       LLVMContext::MD_dereferenceable,
1805       LLVMContext::MD_dereferenceable_or_null};
1806   combineMetadata(K, J, KnownIDs);
1807 }
1808 
1809 unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
1810                                         DominatorTree &DT,
1811                                         const BasicBlockEdge &Root) {
1812   assert(From->getType() == To->getType());
1813 
1814   unsigned Count = 0;
1815   for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
1816        UI != UE; ) {
1817     Use &U = *UI++;
1818     if (DT.dominates(Root, U)) {
1819       U.set(To);
1820       DEBUG(dbgs() << "Replace dominated use of '"
1821             << From->getName() << "' as "
1822             << *To << " in " << *U << "\n");
1823       ++Count;
1824     }
1825   }
1826   return Count;
1827 }
1828 
1829 unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
1830                                         DominatorTree &DT,
1831                                         const BasicBlock *BB) {
1832   assert(From->getType() == To->getType());
1833 
1834   unsigned Count = 0;
1835   for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
1836        UI != UE;) {
1837     Use &U = *UI++;
1838     auto *I = cast<Instruction>(U.getUser());
1839     if (DT.properlyDominates(BB, I->getParent())) {
1840       U.set(To);
1841       DEBUG(dbgs() << "Replace dominated use of '" << From->getName() << "' as "
1842                    << *To << " in " << *U << "\n");
1843       ++Count;
1844     }
1845   }
1846   return Count;
1847 }
1848 
1849 bool llvm::callsGCLeafFunction(ImmutableCallSite CS) {
1850   // Check if the function is specifically marked as a gc leaf function.
1851   if (CS.hasFnAttr("gc-leaf-function"))
1852     return true;
1853   if (const Function *F = CS.getCalledFunction()) {
1854     if (F->hasFnAttribute("gc-leaf-function"))
1855       return true;
1856 
1857     if (auto IID = F->getIntrinsicID())
1858       // Most LLVM intrinsics do not take safepoints.
1859       return IID != Intrinsic::experimental_gc_statepoint &&
1860              IID != Intrinsic::experimental_deoptimize;
1861   }
1862 
1863   return false;
1864 }
1865 
1866 namespace {
1867 /// A potential constituent of a bitreverse or bswap expression. See
1868 /// collectBitParts for a fuller explanation.
1869 struct BitPart {
1870   BitPart(Value *P, unsigned BW) : Provider(P) {
1871     Provenance.resize(BW);
1872   }
1873 
1874   /// The Value that this is a bitreverse/bswap of.
1875   Value *Provider;
1876   /// The "provenance" of each bit. Provenance[A] = B means that bit A
1877   /// in Provider becomes bit B in the result of this expression.
1878   SmallVector<int8_t, 32> Provenance; // int8_t means max size is i128.
1879 
1880   enum { Unset = -1 };
1881 };
1882 } // end anonymous namespace
1883 
1884 /// Analyze the specified subexpression and see if it is capable of providing
1885 /// pieces of a bswap or bitreverse. The subexpression provides a potential
1886 /// piece of a bswap or bitreverse if it can be proven that each non-zero bit in
1887 /// the output of the expression came from a corresponding bit in some other
1888 /// value. This function is recursive, and the end result is a mapping of
1889 /// bitnumber to bitnumber. It is the caller's responsibility to validate that
1890 /// the bitnumber to bitnumber mapping is correct for a bswap or bitreverse.
1891 ///
1892 /// For example, if the current subexpression if "(shl i32 %X, 24)" then we know
1893 /// that the expression deposits the low byte of %X into the high byte of the
1894 /// result and that all other bits are zero. This expression is accepted and a
1895 /// BitPart is returned with Provider set to %X and Provenance[24-31] set to
1896 /// [0-7].
1897 ///
1898 /// To avoid revisiting values, the BitPart results are memoized into the
1899 /// provided map. To avoid unnecessary copying of BitParts, BitParts are
1900 /// constructed in-place in the \c BPS map. Because of this \c BPS needs to
1901 /// store BitParts objects, not pointers. As we need the concept of a nullptr
1902 /// BitParts (Value has been analyzed and the analysis failed), we an Optional
1903 /// type instead to provide the same functionality.
1904 ///
1905 /// Because we pass around references into \c BPS, we must use a container that
1906 /// does not invalidate internal references (std::map instead of DenseMap).
1907 ///
1908 static const Optional<BitPart> &
1909 collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals,
1910                 std::map<Value *, Optional<BitPart>> &BPS) {
1911   auto I = BPS.find(V);
1912   if (I != BPS.end())
1913     return I->second;
1914 
1915   auto &Result = BPS[V] = None;
1916   auto BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1917 
1918   if (Instruction *I = dyn_cast<Instruction>(V)) {
1919     // If this is an or instruction, it may be an inner node of the bswap.
1920     if (I->getOpcode() == Instruction::Or) {
1921       auto &A = collectBitParts(I->getOperand(0), MatchBSwaps,
1922                                 MatchBitReversals, BPS);
1923       auto &B = collectBitParts(I->getOperand(1), MatchBSwaps,
1924                                 MatchBitReversals, BPS);
1925       if (!A || !B)
1926         return Result;
1927 
1928       // Try and merge the two together.
1929       if (!A->Provider || A->Provider != B->Provider)
1930         return Result;
1931 
1932       Result = BitPart(A->Provider, BitWidth);
1933       for (unsigned i = 0; i < A->Provenance.size(); ++i) {
1934         if (A->Provenance[i] != BitPart::Unset &&
1935             B->Provenance[i] != BitPart::Unset &&
1936             A->Provenance[i] != B->Provenance[i])
1937           return Result = None;
1938 
1939         if (A->Provenance[i] == BitPart::Unset)
1940           Result->Provenance[i] = B->Provenance[i];
1941         else
1942           Result->Provenance[i] = A->Provenance[i];
1943       }
1944 
1945       return Result;
1946     }
1947 
1948     // If this is a logical shift by a constant, recurse then shift the result.
1949     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
1950       unsigned BitShift =
1951           cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1952       // Ensure the shift amount is defined.
1953       if (BitShift > BitWidth)
1954         return Result;
1955 
1956       auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
1957                                   MatchBitReversals, BPS);
1958       if (!Res)
1959         return Result;
1960       Result = Res;
1961 
1962       // Perform the "shift" on BitProvenance.
1963       auto &P = Result->Provenance;
1964       if (I->getOpcode() == Instruction::Shl) {
1965         P.erase(std::prev(P.end(), BitShift), P.end());
1966         P.insert(P.begin(), BitShift, BitPart::Unset);
1967       } else {
1968         P.erase(P.begin(), std::next(P.begin(), BitShift));
1969         P.insert(P.end(), BitShift, BitPart::Unset);
1970       }
1971 
1972       return Result;
1973     }
1974 
1975     // If this is a logical 'and' with a mask that clears bits, recurse then
1976     // unset the appropriate bits.
1977     if (I->getOpcode() == Instruction::And &&
1978         isa<ConstantInt>(I->getOperand(1))) {
1979       APInt Bit(I->getType()->getPrimitiveSizeInBits(), 1);
1980       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
1981 
1982       // Check that the mask allows a multiple of 8 bits for a bswap, for an
1983       // early exit.
1984       unsigned NumMaskedBits = AndMask.countPopulation();
1985       if (!MatchBitReversals && NumMaskedBits % 8 != 0)
1986         return Result;
1987 
1988       auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
1989                                   MatchBitReversals, BPS);
1990       if (!Res)
1991         return Result;
1992       Result = Res;
1993 
1994       for (unsigned i = 0; i < BitWidth; ++i, Bit <<= 1)
1995         // If the AndMask is zero for this bit, clear the bit.
1996         if ((AndMask & Bit) == 0)
1997           Result->Provenance[i] = BitPart::Unset;
1998       return Result;
1999     }
2000 
2001     // If this is a zext instruction zero extend the result.
2002     if (I->getOpcode() == Instruction::ZExt) {
2003       auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
2004                                   MatchBitReversals, BPS);
2005       if (!Res)
2006         return Result;
2007 
2008       Result = BitPart(Res->Provider, BitWidth);
2009       auto NarrowBitWidth =
2010           cast<IntegerType>(cast<ZExtInst>(I)->getSrcTy())->getBitWidth();
2011       for (unsigned i = 0; i < NarrowBitWidth; ++i)
2012         Result->Provenance[i] = Res->Provenance[i];
2013       for (unsigned i = NarrowBitWidth; i < BitWidth; ++i)
2014         Result->Provenance[i] = BitPart::Unset;
2015       return Result;
2016     }
2017   }
2018 
2019   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
2020   // the input value to the bswap/bitreverse.
2021   Result = BitPart(V, BitWidth);
2022   for (unsigned i = 0; i < BitWidth; ++i)
2023     Result->Provenance[i] = i;
2024   return Result;
2025 }
2026 
2027 static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To,
2028                                           unsigned BitWidth) {
2029   if (From % 8 != To % 8)
2030     return false;
2031   // Convert from bit indices to byte indices and check for a byte reversal.
2032   From >>= 3;
2033   To >>= 3;
2034   BitWidth >>= 3;
2035   return From == BitWidth - To - 1;
2036 }
2037 
2038 static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To,
2039                                                unsigned BitWidth) {
2040   return From == BitWidth - To - 1;
2041 }
2042 
2043 /// Given an OR instruction, check to see if this is a bitreverse
2044 /// idiom. If so, insert the new intrinsic and return true.
2045 bool llvm::recognizeBSwapOrBitReverseIdiom(
2046     Instruction *I, bool MatchBSwaps, bool MatchBitReversals,
2047     SmallVectorImpl<Instruction *> &InsertedInsts) {
2048   if (Operator::getOpcode(I) != Instruction::Or)
2049     return false;
2050   if (!MatchBSwaps && !MatchBitReversals)
2051     return false;
2052   IntegerType *ITy = dyn_cast<IntegerType>(I->getType());
2053   if (!ITy || ITy->getBitWidth() > 128)
2054     return false;   // Can't do vectors or integers > 128 bits.
2055   unsigned BW = ITy->getBitWidth();
2056 
2057   unsigned DemandedBW = BW;
2058   IntegerType *DemandedTy = ITy;
2059   if (I->hasOneUse()) {
2060     if (TruncInst *Trunc = dyn_cast<TruncInst>(I->user_back())) {
2061       DemandedTy = cast<IntegerType>(Trunc->getType());
2062       DemandedBW = DemandedTy->getBitWidth();
2063     }
2064   }
2065 
2066   // Try to find all the pieces corresponding to the bswap.
2067   std::map<Value *, Optional<BitPart>> BPS;
2068   auto Res = collectBitParts(I, MatchBSwaps, MatchBitReversals, BPS);
2069   if (!Res)
2070     return false;
2071   auto &BitProvenance = Res->Provenance;
2072 
2073   // Now, is the bit permutation correct for a bswap or a bitreverse? We can
2074   // only byteswap values with an even number of bytes.
2075   bool OKForBSwap = DemandedBW % 16 == 0, OKForBitReverse = true;
2076   for (unsigned i = 0; i < DemandedBW; ++i) {
2077     OKForBSwap &=
2078         bitTransformIsCorrectForBSwap(BitProvenance[i], i, DemandedBW);
2079     OKForBitReverse &=
2080         bitTransformIsCorrectForBitReverse(BitProvenance[i], i, DemandedBW);
2081   }
2082 
2083   Intrinsic::ID Intrin;
2084   if (OKForBSwap && MatchBSwaps)
2085     Intrin = Intrinsic::bswap;
2086   else if (OKForBitReverse && MatchBitReversals)
2087     Intrin = Intrinsic::bitreverse;
2088   else
2089     return false;
2090 
2091   if (ITy != DemandedTy) {
2092     Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, DemandedTy);
2093     Value *Provider = Res->Provider;
2094     IntegerType *ProviderTy = cast<IntegerType>(Provider->getType());
2095     // We may need to truncate the provider.
2096     if (DemandedTy != ProviderTy) {
2097       auto *Trunc = CastInst::Create(Instruction::Trunc, Provider, DemandedTy,
2098                                      "trunc", I);
2099       InsertedInsts.push_back(Trunc);
2100       Provider = Trunc;
2101     }
2102     auto *CI = CallInst::Create(F, Provider, "rev", I);
2103     InsertedInsts.push_back(CI);
2104     auto *ExtInst = CastInst::Create(Instruction::ZExt, CI, ITy, "zext", I);
2105     InsertedInsts.push_back(ExtInst);
2106     return true;
2107   }
2108 
2109   Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, ITy);
2110   InsertedInsts.push_back(CallInst::Create(F, Res->Provider, "rev", I));
2111   return true;
2112 }
2113 
2114 // CodeGen has special handling for some string functions that may replace
2115 // them with target-specific intrinsics.  Since that'd skip our interceptors
2116 // in ASan/MSan/TSan/DFSan, and thus make us miss some memory accesses,
2117 // we mark affected calls as NoBuiltin, which will disable optimization
2118 // in CodeGen.
2119 void llvm::maybeMarkSanitizerLibraryCallNoBuiltin(
2120     CallInst *CI, const TargetLibraryInfo *TLI) {
2121   Function *F = CI->getCalledFunction();
2122   LibFunc Func;
2123   if (F && !F->hasLocalLinkage() && F->hasName() &&
2124       TLI->getLibFunc(F->getName(), Func) && TLI->hasOptimizedCodeGen(Func) &&
2125       !F->doesNotAccessMemory())
2126     CI->addAttribute(AttributeList::FunctionIndex, Attribute::NoBuiltin);
2127 }
2128