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 DIExprAddDeref(SmallVectorImpl<uint64_t> &Expr) {
1263   Expr.push_back(dwarf::DW_OP_deref);
1264 }
1265 
1266 static void DIExprAddOffset(SmallVectorImpl<uint64_t> &Expr, int Offset) {
1267   if (Offset > 0) {
1268     Expr.push_back(dwarf::DW_OP_plus);
1269     Expr.push_back(Offset);
1270   } else if (Offset < 0) {
1271     Expr.push_back(dwarf::DW_OP_minus);
1272     Expr.push_back(-Offset);
1273   }
1274 }
1275 
1276 static DIExpression *BuildReplacementDIExpr(DIBuilder &Builder,
1277                                             DIExpression *DIExpr, bool Deref,
1278                                             int Offset) {
1279   if (!Deref && !Offset)
1280     return DIExpr;
1281   // Create a copy of the original DIDescriptor for user variable, prepending
1282   // "deref" operation to a list of address elements, as new llvm.dbg.declare
1283   // will take a value storing address of the memory for variable, not
1284   // alloca itself.
1285   SmallVector<uint64_t, 4> NewDIExpr;
1286   if (Deref)
1287     DIExprAddDeref(NewDIExpr);
1288   DIExprAddOffset(NewDIExpr, Offset);
1289   if (DIExpr)
1290     NewDIExpr.append(DIExpr->elements_begin(), DIExpr->elements_end());
1291   return Builder.createExpression(NewDIExpr);
1292 }
1293 
1294 bool llvm::replaceDbgDeclare(Value *Address, Value *NewAddress,
1295                              Instruction *InsertBefore, DIBuilder &Builder,
1296                              bool Deref, int Offset) {
1297   DbgDeclareInst *DDI = FindAllocaDbgDeclare(Address);
1298   if (!DDI)
1299     return false;
1300   DebugLoc Loc = DDI->getDebugLoc();
1301   auto *DIVar = DDI->getVariable();
1302   auto *DIExpr = DDI->getExpression();
1303   assert(DIVar && "Missing variable");
1304 
1305   DIExpr = BuildReplacementDIExpr(Builder, DIExpr, Deref, Offset);
1306 
1307   // Insert llvm.dbg.declare immediately after the original alloca, and remove
1308   // old llvm.dbg.declare.
1309   Builder.insertDeclare(NewAddress, DIVar, DIExpr, Loc, InsertBefore);
1310   DDI->eraseFromParent();
1311   return true;
1312 }
1313 
1314 bool llvm::replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
1315                                       DIBuilder &Builder, bool Deref, int Offset) {
1316   return replaceDbgDeclare(AI, NewAllocaAddress, AI->getNextNode(), Builder,
1317                            Deref, Offset);
1318 }
1319 
1320 static void replaceOneDbgValueForAlloca(DbgValueInst *DVI, Value *NewAddress,
1321                                         DIBuilder &Builder, int Offset) {
1322   DebugLoc Loc = DVI->getDebugLoc();
1323   auto *DIVar = DVI->getVariable();
1324   auto *DIExpr = DVI->getExpression();
1325   assert(DIVar && "Missing variable");
1326 
1327   // This is an alloca-based llvm.dbg.value. The first thing it should do with
1328   // the alloca pointer is dereference it. Otherwise we don't know how to handle
1329   // it and give up.
1330   if (!DIExpr || DIExpr->getNumElements() < 1 ||
1331       DIExpr->getElement(0) != dwarf::DW_OP_deref)
1332     return;
1333 
1334   // Insert the offset immediately after the first deref.
1335   // We could just change the offset argument of dbg.value, but it's unsigned...
1336   if (Offset) {
1337     SmallVector<uint64_t, 4> NewDIExpr;
1338     DIExprAddDeref(NewDIExpr);
1339     DIExprAddOffset(NewDIExpr, Offset);
1340     NewDIExpr.append(DIExpr->elements_begin() + 1, DIExpr->elements_end());
1341     DIExpr = Builder.createExpression(NewDIExpr);
1342   }
1343 
1344   Builder.insertDbgValueIntrinsic(NewAddress, DVI->getOffset(), DIVar, DIExpr,
1345                                   Loc, DVI);
1346   DVI->eraseFromParent();
1347 }
1348 
1349 void llvm::replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
1350                                     DIBuilder &Builder, int Offset) {
1351   if (auto *L = LocalAsMetadata::getIfExists(AI))
1352     if (auto *MDV = MetadataAsValue::getIfExists(AI->getContext(), L))
1353       for (auto UI = MDV->use_begin(), UE = MDV->use_end(); UI != UE;) {
1354         Use &U = *UI++;
1355         if (auto *DVI = dyn_cast<DbgValueInst>(U.getUser()))
1356           replaceOneDbgValueForAlloca(DVI, NewAllocaAddress, Builder, Offset);
1357       }
1358 }
1359 
1360 unsigned llvm::removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB) {
1361   unsigned NumDeadInst = 0;
1362   // Delete the instructions backwards, as it has a reduced likelihood of
1363   // having to update as many def-use and use-def chains.
1364   Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
1365   while (EndInst != &BB->front()) {
1366     // Delete the next to last instruction.
1367     Instruction *Inst = &*--EndInst->getIterator();
1368     if (!Inst->use_empty() && !Inst->getType()->isTokenTy())
1369       Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
1370     if (Inst->isEHPad() || Inst->getType()->isTokenTy()) {
1371       EndInst = Inst;
1372       continue;
1373     }
1374     if (!isa<DbgInfoIntrinsic>(Inst))
1375       ++NumDeadInst;
1376     Inst->eraseFromParent();
1377   }
1378   return NumDeadInst;
1379 }
1380 
1381 unsigned llvm::changeToUnreachable(Instruction *I, bool UseLLVMTrap,
1382                                    bool PreserveLCSSA) {
1383   BasicBlock *BB = I->getParent();
1384   // Loop over all of the successors, removing BB's entry from any PHI
1385   // nodes.
1386   for (BasicBlock *Successor : successors(BB))
1387     Successor->removePredecessor(BB, PreserveLCSSA);
1388 
1389   // Insert a call to llvm.trap right before this.  This turns the undefined
1390   // behavior into a hard fail instead of falling through into random code.
1391   if (UseLLVMTrap) {
1392     Function *TrapFn =
1393       Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap);
1394     CallInst *CallTrap = CallInst::Create(TrapFn, "", I);
1395     CallTrap->setDebugLoc(I->getDebugLoc());
1396   }
1397   new UnreachableInst(I->getContext(), I);
1398 
1399   // All instructions after this are dead.
1400   unsigned NumInstrsRemoved = 0;
1401   BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end();
1402   while (BBI != BBE) {
1403     if (!BBI->use_empty())
1404       BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
1405     BB->getInstList().erase(BBI++);
1406     ++NumInstrsRemoved;
1407   }
1408   return NumInstrsRemoved;
1409 }
1410 
1411 /// changeToCall - Convert the specified invoke into a normal call.
1412 static void changeToCall(InvokeInst *II) {
1413   SmallVector<Value*, 8> Args(II->arg_begin(), II->arg_end());
1414   SmallVector<OperandBundleDef, 1> OpBundles;
1415   II->getOperandBundlesAsDefs(OpBundles);
1416   CallInst *NewCall = CallInst::Create(II->getCalledValue(), Args, OpBundles,
1417                                        "", II);
1418   NewCall->takeName(II);
1419   NewCall->setCallingConv(II->getCallingConv());
1420   NewCall->setAttributes(II->getAttributes());
1421   NewCall->setDebugLoc(II->getDebugLoc());
1422   II->replaceAllUsesWith(NewCall);
1423 
1424   // Follow the call by a branch to the normal destination.
1425   BranchInst::Create(II->getNormalDest(), II);
1426 
1427   // Update PHI nodes in the unwind destination
1428   II->getUnwindDest()->removePredecessor(II->getParent());
1429   II->eraseFromParent();
1430 }
1431 
1432 BasicBlock *llvm::changeToInvokeAndSplitBasicBlock(CallInst *CI,
1433                                                    BasicBlock *UnwindEdge) {
1434   BasicBlock *BB = CI->getParent();
1435 
1436   // Convert this function call into an invoke instruction.  First, split the
1437   // basic block.
1438   BasicBlock *Split =
1439       BB->splitBasicBlock(CI->getIterator(), CI->getName() + ".noexc");
1440 
1441   // Delete the unconditional branch inserted by splitBasicBlock
1442   BB->getInstList().pop_back();
1443 
1444   // Create the new invoke instruction.
1445   SmallVector<Value *, 8> InvokeArgs(CI->arg_begin(), CI->arg_end());
1446   SmallVector<OperandBundleDef, 1> OpBundles;
1447 
1448   CI->getOperandBundlesAsDefs(OpBundles);
1449 
1450   // Note: we're round tripping operand bundles through memory here, and that
1451   // can potentially be avoided with a cleverer API design that we do not have
1452   // as of this time.
1453 
1454   InvokeInst *II = InvokeInst::Create(CI->getCalledValue(), Split, UnwindEdge,
1455                                       InvokeArgs, OpBundles, CI->getName(), BB);
1456   II->setDebugLoc(CI->getDebugLoc());
1457   II->setCallingConv(CI->getCallingConv());
1458   II->setAttributes(CI->getAttributes());
1459 
1460   // Make sure that anything using the call now uses the invoke!  This also
1461   // updates the CallGraph if present, because it uses a WeakVH.
1462   CI->replaceAllUsesWith(II);
1463 
1464   // Delete the original call
1465   Split->getInstList().pop_front();
1466   return Split;
1467 }
1468 
1469 static bool markAliveBlocks(Function &F,
1470                             SmallPtrSetImpl<BasicBlock*> &Reachable) {
1471 
1472   SmallVector<BasicBlock*, 128> Worklist;
1473   BasicBlock *BB = &F.front();
1474   Worklist.push_back(BB);
1475   Reachable.insert(BB);
1476   bool Changed = false;
1477   do {
1478     BB = Worklist.pop_back_val();
1479 
1480     // Do a quick scan of the basic block, turning any obviously unreachable
1481     // instructions into LLVM unreachable insts.  The instruction combining pass
1482     // canonicalizes unreachable insts into stores to null or undef.
1483     for (Instruction &I : *BB) {
1484       // Assumptions that are known to be false are equivalent to unreachable.
1485       // Also, if the condition is undefined, then we make the choice most
1486       // beneficial to the optimizer, and choose that to also be unreachable.
1487       if (auto *II = dyn_cast<IntrinsicInst>(&I)) {
1488         if (II->getIntrinsicID() == Intrinsic::assume) {
1489           if (match(II->getArgOperand(0), m_CombineOr(m_Zero(), m_Undef()))) {
1490             // Don't insert a call to llvm.trap right before the unreachable.
1491             changeToUnreachable(II, false);
1492             Changed = true;
1493             break;
1494           }
1495         }
1496 
1497         if (II->getIntrinsicID() == Intrinsic::experimental_guard) {
1498           // A call to the guard intrinsic bails out of the current compilation
1499           // unit if the predicate passed to it is false.  If the predicate is a
1500           // constant false, then we know the guard will bail out of the current
1501           // compile unconditionally, so all code following it is dead.
1502           //
1503           // Note: unlike in llvm.assume, it is not "obviously profitable" for
1504           // guards to treat `undef` as `false` since a guard on `undef` can
1505           // still be useful for widening.
1506           if (match(II->getArgOperand(0), m_Zero()))
1507             if (!isa<UnreachableInst>(II->getNextNode())) {
1508               changeToUnreachable(II->getNextNode(), /*UseLLVMTrap=*/ false);
1509               Changed = true;
1510               break;
1511             }
1512         }
1513       }
1514 
1515       if (auto *CI = dyn_cast<CallInst>(&I)) {
1516         Value *Callee = CI->getCalledValue();
1517         if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
1518           changeToUnreachable(CI, /*UseLLVMTrap=*/false);
1519           Changed = true;
1520           break;
1521         }
1522         if (CI->doesNotReturn()) {
1523           // If we found a call to a no-return function, insert an unreachable
1524           // instruction after it.  Make sure there isn't *already* one there
1525           // though.
1526           if (!isa<UnreachableInst>(CI->getNextNode())) {
1527             // Don't insert a call to llvm.trap right before the unreachable.
1528             changeToUnreachable(CI->getNextNode(), false);
1529             Changed = true;
1530           }
1531           break;
1532         }
1533       }
1534 
1535       // Store to undef and store to null are undefined and used to signal that
1536       // they should be changed to unreachable by passes that can't modify the
1537       // CFG.
1538       if (auto *SI = dyn_cast<StoreInst>(&I)) {
1539         // Don't touch volatile stores.
1540         if (SI->isVolatile()) continue;
1541 
1542         Value *Ptr = SI->getOperand(1);
1543 
1544         if (isa<UndefValue>(Ptr) ||
1545             (isa<ConstantPointerNull>(Ptr) &&
1546              SI->getPointerAddressSpace() == 0)) {
1547           changeToUnreachable(SI, true);
1548           Changed = true;
1549           break;
1550         }
1551       }
1552     }
1553 
1554     TerminatorInst *Terminator = BB->getTerminator();
1555     if (auto *II = dyn_cast<InvokeInst>(Terminator)) {
1556       // Turn invokes that call 'nounwind' functions into ordinary calls.
1557       Value *Callee = II->getCalledValue();
1558       if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
1559         changeToUnreachable(II, true);
1560         Changed = true;
1561       } else if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(&F)) {
1562         if (II->use_empty() && II->onlyReadsMemory()) {
1563           // jump to the normal destination branch.
1564           BranchInst::Create(II->getNormalDest(), II);
1565           II->getUnwindDest()->removePredecessor(II->getParent());
1566           II->eraseFromParent();
1567         } else
1568           changeToCall(II);
1569         Changed = true;
1570       }
1571     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) {
1572       // Remove catchpads which cannot be reached.
1573       struct CatchPadDenseMapInfo {
1574         static CatchPadInst *getEmptyKey() {
1575           return DenseMapInfo<CatchPadInst *>::getEmptyKey();
1576         }
1577         static CatchPadInst *getTombstoneKey() {
1578           return DenseMapInfo<CatchPadInst *>::getTombstoneKey();
1579         }
1580         static unsigned getHashValue(CatchPadInst *CatchPad) {
1581           return static_cast<unsigned>(hash_combine_range(
1582               CatchPad->value_op_begin(), CatchPad->value_op_end()));
1583         }
1584         static bool isEqual(CatchPadInst *LHS, CatchPadInst *RHS) {
1585           if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
1586               RHS == getEmptyKey() || RHS == getTombstoneKey())
1587             return LHS == RHS;
1588           return LHS->isIdenticalTo(RHS);
1589         }
1590       };
1591 
1592       // Set of unique CatchPads.
1593       SmallDenseMap<CatchPadInst *, detail::DenseSetEmpty, 4,
1594                     CatchPadDenseMapInfo, detail::DenseSetPair<CatchPadInst *>>
1595           HandlerSet;
1596       detail::DenseSetEmpty Empty;
1597       for (CatchSwitchInst::handler_iterator I = CatchSwitch->handler_begin(),
1598                                              E = CatchSwitch->handler_end();
1599            I != E; ++I) {
1600         BasicBlock *HandlerBB = *I;
1601         auto *CatchPad = cast<CatchPadInst>(HandlerBB->getFirstNonPHI());
1602         if (!HandlerSet.insert({CatchPad, Empty}).second) {
1603           CatchSwitch->removeHandler(I);
1604           --I;
1605           --E;
1606           Changed = true;
1607         }
1608       }
1609     }
1610 
1611     Changed |= ConstantFoldTerminator(BB, true);
1612     for (BasicBlock *Successor : successors(BB))
1613       if (Reachable.insert(Successor).second)
1614         Worklist.push_back(Successor);
1615   } while (!Worklist.empty());
1616   return Changed;
1617 }
1618 
1619 void llvm::removeUnwindEdge(BasicBlock *BB) {
1620   TerminatorInst *TI = BB->getTerminator();
1621 
1622   if (auto *II = dyn_cast<InvokeInst>(TI)) {
1623     changeToCall(II);
1624     return;
1625   }
1626 
1627   TerminatorInst *NewTI;
1628   BasicBlock *UnwindDest;
1629 
1630   if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
1631     NewTI = CleanupReturnInst::Create(CRI->getCleanupPad(), nullptr, CRI);
1632     UnwindDest = CRI->getUnwindDest();
1633   } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
1634     auto *NewCatchSwitch = CatchSwitchInst::Create(
1635         CatchSwitch->getParentPad(), nullptr, CatchSwitch->getNumHandlers(),
1636         CatchSwitch->getName(), CatchSwitch);
1637     for (BasicBlock *PadBB : CatchSwitch->handlers())
1638       NewCatchSwitch->addHandler(PadBB);
1639 
1640     NewTI = NewCatchSwitch;
1641     UnwindDest = CatchSwitch->getUnwindDest();
1642   } else {
1643     llvm_unreachable("Could not find unwind successor");
1644   }
1645 
1646   NewTI->takeName(TI);
1647   NewTI->setDebugLoc(TI->getDebugLoc());
1648   UnwindDest->removePredecessor(BB);
1649   TI->replaceAllUsesWith(NewTI);
1650   TI->eraseFromParent();
1651 }
1652 
1653 /// removeUnreachableBlocksFromFn - Remove blocks that are not reachable, even
1654 /// if they are in a dead cycle.  Return true if a change was made, false
1655 /// otherwise.
1656 bool llvm::removeUnreachableBlocks(Function &F, LazyValueInfo *LVI) {
1657   SmallPtrSet<BasicBlock*, 16> Reachable;
1658   bool Changed = markAliveBlocks(F, Reachable);
1659 
1660   // If there are unreachable blocks in the CFG...
1661   if (Reachable.size() == F.size())
1662     return Changed;
1663 
1664   assert(Reachable.size() < F.size());
1665   NumRemoved += F.size()-Reachable.size();
1666 
1667   // Loop over all of the basic blocks that are not reachable, dropping all of
1668   // their internal references...
1669   for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB) {
1670     if (Reachable.count(&*BB))
1671       continue;
1672 
1673     for (BasicBlock *Successor : successors(&*BB))
1674       if (Reachable.count(Successor))
1675         Successor->removePredecessor(&*BB);
1676     if (LVI)
1677       LVI->eraseBlock(&*BB);
1678     BB->dropAllReferences();
1679   }
1680 
1681   for (Function::iterator I = ++F.begin(); I != F.end();)
1682     if (!Reachable.count(&*I))
1683       I = F.getBasicBlockList().erase(I);
1684     else
1685       ++I;
1686 
1687   return true;
1688 }
1689 
1690 void llvm::combineMetadata(Instruction *K, const Instruction *J,
1691                            ArrayRef<unsigned> KnownIDs) {
1692   SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
1693   K->dropUnknownNonDebugMetadata(KnownIDs);
1694   K->getAllMetadataOtherThanDebugLoc(Metadata);
1695   for (const auto &MD : Metadata) {
1696     unsigned Kind = MD.first;
1697     MDNode *JMD = J->getMetadata(Kind);
1698     MDNode *KMD = MD.second;
1699 
1700     switch (Kind) {
1701       default:
1702         K->setMetadata(Kind, nullptr); // Remove unknown metadata
1703         break;
1704       case LLVMContext::MD_dbg:
1705         llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
1706       case LLVMContext::MD_tbaa:
1707         K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
1708         break;
1709       case LLVMContext::MD_alias_scope:
1710         K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD));
1711         break;
1712       case LLVMContext::MD_noalias:
1713       case LLVMContext::MD_mem_parallel_loop_access:
1714         K->setMetadata(Kind, MDNode::intersect(JMD, KMD));
1715         break;
1716       case LLVMContext::MD_range:
1717         K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD));
1718         break;
1719       case LLVMContext::MD_fpmath:
1720         K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
1721         break;
1722       case LLVMContext::MD_invariant_load:
1723         // Only set the !invariant.load if it is present in both instructions.
1724         K->setMetadata(Kind, JMD);
1725         break;
1726       case LLVMContext::MD_nonnull:
1727         // Only set the !nonnull if it is present in both instructions.
1728         K->setMetadata(Kind, JMD);
1729         break;
1730       case LLVMContext::MD_invariant_group:
1731         // Preserve !invariant.group in K.
1732         break;
1733       case LLVMContext::MD_align:
1734         K->setMetadata(Kind,
1735           MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
1736         break;
1737       case LLVMContext::MD_dereferenceable:
1738       case LLVMContext::MD_dereferenceable_or_null:
1739         K->setMetadata(Kind,
1740           MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
1741         break;
1742     }
1743   }
1744   // Set !invariant.group from J if J has it. If both instructions have it
1745   // then we will just pick it from J - even when they are different.
1746   // Also make sure that K is load or store - f.e. combining bitcast with load
1747   // could produce bitcast with invariant.group metadata, which is invalid.
1748   // FIXME: we should try to preserve both invariant.group md if they are
1749   // different, but right now instruction can only have one invariant.group.
1750   if (auto *JMD = J->getMetadata(LLVMContext::MD_invariant_group))
1751     if (isa<LoadInst>(K) || isa<StoreInst>(K))
1752       K->setMetadata(LLVMContext::MD_invariant_group, JMD);
1753 }
1754 
1755 void llvm::combineMetadataForCSE(Instruction *K, const Instruction *J) {
1756   unsigned KnownIDs[] = {
1757       LLVMContext::MD_tbaa,            LLVMContext::MD_alias_scope,
1758       LLVMContext::MD_noalias,         LLVMContext::MD_range,
1759       LLVMContext::MD_invariant_load,  LLVMContext::MD_nonnull,
1760       LLVMContext::MD_invariant_group, LLVMContext::MD_align,
1761       LLVMContext::MD_dereferenceable,
1762       LLVMContext::MD_dereferenceable_or_null};
1763   combineMetadata(K, J, KnownIDs);
1764 }
1765 
1766 unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
1767                                         DominatorTree &DT,
1768                                         const BasicBlockEdge &Root) {
1769   assert(From->getType() == To->getType());
1770 
1771   unsigned Count = 0;
1772   for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
1773        UI != UE; ) {
1774     Use &U = *UI++;
1775     if (DT.dominates(Root, U)) {
1776       U.set(To);
1777       DEBUG(dbgs() << "Replace dominated use of '"
1778             << From->getName() << "' as "
1779             << *To << " in " << *U << "\n");
1780       ++Count;
1781     }
1782   }
1783   return Count;
1784 }
1785 
1786 unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
1787                                         DominatorTree &DT,
1788                                         const BasicBlock *BB) {
1789   assert(From->getType() == To->getType());
1790 
1791   unsigned Count = 0;
1792   for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
1793        UI != UE;) {
1794     Use &U = *UI++;
1795     auto *I = cast<Instruction>(U.getUser());
1796     if (DT.properlyDominates(BB, I->getParent())) {
1797       U.set(To);
1798       DEBUG(dbgs() << "Replace dominated use of '" << From->getName() << "' as "
1799                    << *To << " in " << *U << "\n");
1800       ++Count;
1801     }
1802   }
1803   return Count;
1804 }
1805 
1806 bool llvm::callsGCLeafFunction(ImmutableCallSite CS) {
1807   // Check if the function is specifically marked as a gc leaf function.
1808   if (CS.hasFnAttr("gc-leaf-function"))
1809     return true;
1810   if (const Function *F = CS.getCalledFunction()) {
1811     if (F->hasFnAttribute("gc-leaf-function"))
1812       return true;
1813 
1814     if (auto IID = F->getIntrinsicID())
1815       // Most LLVM intrinsics do not take safepoints.
1816       return IID != Intrinsic::experimental_gc_statepoint &&
1817              IID != Intrinsic::experimental_deoptimize;
1818   }
1819 
1820   return false;
1821 }
1822 
1823 namespace {
1824 /// A potential constituent of a bitreverse or bswap expression. See
1825 /// collectBitParts for a fuller explanation.
1826 struct BitPart {
1827   BitPart(Value *P, unsigned BW) : Provider(P) {
1828     Provenance.resize(BW);
1829   }
1830 
1831   /// The Value that this is a bitreverse/bswap of.
1832   Value *Provider;
1833   /// The "provenance" of each bit. Provenance[A] = B means that bit A
1834   /// in Provider becomes bit B in the result of this expression.
1835   SmallVector<int8_t, 32> Provenance; // int8_t means max size is i128.
1836 
1837   enum { Unset = -1 };
1838 };
1839 } // end anonymous namespace
1840 
1841 /// Analyze the specified subexpression and see if it is capable of providing
1842 /// pieces of a bswap or bitreverse. The subexpression provides a potential
1843 /// piece of a bswap or bitreverse if it can be proven that each non-zero bit in
1844 /// the output of the expression came from a corresponding bit in some other
1845 /// value. This function is recursive, and the end result is a mapping of
1846 /// bitnumber to bitnumber. It is the caller's responsibility to validate that
1847 /// the bitnumber to bitnumber mapping is correct for a bswap or bitreverse.
1848 ///
1849 /// For example, if the current subexpression if "(shl i32 %X, 24)" then we know
1850 /// that the expression deposits the low byte of %X into the high byte of the
1851 /// result and that all other bits are zero. This expression is accepted and a
1852 /// BitPart is returned with Provider set to %X and Provenance[24-31] set to
1853 /// [0-7].
1854 ///
1855 /// To avoid revisiting values, the BitPart results are memoized into the
1856 /// provided map. To avoid unnecessary copying of BitParts, BitParts are
1857 /// constructed in-place in the \c BPS map. Because of this \c BPS needs to
1858 /// store BitParts objects, not pointers. As we need the concept of a nullptr
1859 /// BitParts (Value has been analyzed and the analysis failed), we an Optional
1860 /// type instead to provide the same functionality.
1861 ///
1862 /// Because we pass around references into \c BPS, we must use a container that
1863 /// does not invalidate internal references (std::map instead of DenseMap).
1864 ///
1865 static const Optional<BitPart> &
1866 collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals,
1867                 std::map<Value *, Optional<BitPart>> &BPS) {
1868   auto I = BPS.find(V);
1869   if (I != BPS.end())
1870     return I->second;
1871 
1872   auto &Result = BPS[V] = None;
1873   auto BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1874 
1875   if (Instruction *I = dyn_cast<Instruction>(V)) {
1876     // If this is an or instruction, it may be an inner node of the bswap.
1877     if (I->getOpcode() == Instruction::Or) {
1878       auto &A = collectBitParts(I->getOperand(0), MatchBSwaps,
1879                                 MatchBitReversals, BPS);
1880       auto &B = collectBitParts(I->getOperand(1), MatchBSwaps,
1881                                 MatchBitReversals, BPS);
1882       if (!A || !B)
1883         return Result;
1884 
1885       // Try and merge the two together.
1886       if (!A->Provider || A->Provider != B->Provider)
1887         return Result;
1888 
1889       Result = BitPart(A->Provider, BitWidth);
1890       for (unsigned i = 0; i < A->Provenance.size(); ++i) {
1891         if (A->Provenance[i] != BitPart::Unset &&
1892             B->Provenance[i] != BitPart::Unset &&
1893             A->Provenance[i] != B->Provenance[i])
1894           return Result = None;
1895 
1896         if (A->Provenance[i] == BitPart::Unset)
1897           Result->Provenance[i] = B->Provenance[i];
1898         else
1899           Result->Provenance[i] = A->Provenance[i];
1900       }
1901 
1902       return Result;
1903     }
1904 
1905     // If this is a logical shift by a constant, recurse then shift the result.
1906     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
1907       unsigned BitShift =
1908           cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1909       // Ensure the shift amount is defined.
1910       if (BitShift > BitWidth)
1911         return Result;
1912 
1913       auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
1914                                   MatchBitReversals, BPS);
1915       if (!Res)
1916         return Result;
1917       Result = Res;
1918 
1919       // Perform the "shift" on BitProvenance.
1920       auto &P = Result->Provenance;
1921       if (I->getOpcode() == Instruction::Shl) {
1922         P.erase(std::prev(P.end(), BitShift), P.end());
1923         P.insert(P.begin(), BitShift, BitPart::Unset);
1924       } else {
1925         P.erase(P.begin(), std::next(P.begin(), BitShift));
1926         P.insert(P.end(), BitShift, BitPart::Unset);
1927       }
1928 
1929       return Result;
1930     }
1931 
1932     // If this is a logical 'and' with a mask that clears bits, recurse then
1933     // unset the appropriate bits.
1934     if (I->getOpcode() == Instruction::And &&
1935         isa<ConstantInt>(I->getOperand(1))) {
1936       APInt Bit(I->getType()->getPrimitiveSizeInBits(), 1);
1937       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
1938 
1939       // Check that the mask allows a multiple of 8 bits for a bswap, for an
1940       // early exit.
1941       unsigned NumMaskedBits = AndMask.countPopulation();
1942       if (!MatchBitReversals && NumMaskedBits % 8 != 0)
1943         return Result;
1944 
1945       auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
1946                                   MatchBitReversals, BPS);
1947       if (!Res)
1948         return Result;
1949       Result = Res;
1950 
1951       for (unsigned i = 0; i < BitWidth; ++i, Bit <<= 1)
1952         // If the AndMask is zero for this bit, clear the bit.
1953         if ((AndMask & Bit) == 0)
1954           Result->Provenance[i] = BitPart::Unset;
1955       return Result;
1956     }
1957 
1958     // If this is a zext instruction zero extend the result.
1959     if (I->getOpcode() == Instruction::ZExt) {
1960       auto &Res = collectBitParts(I->getOperand(0), MatchBSwaps,
1961                                   MatchBitReversals, BPS);
1962       if (!Res)
1963         return Result;
1964 
1965       Result = BitPart(Res->Provider, BitWidth);
1966       auto NarrowBitWidth =
1967           cast<IntegerType>(cast<ZExtInst>(I)->getSrcTy())->getBitWidth();
1968       for (unsigned i = 0; i < NarrowBitWidth; ++i)
1969         Result->Provenance[i] = Res->Provenance[i];
1970       for (unsigned i = NarrowBitWidth; i < BitWidth; ++i)
1971         Result->Provenance[i] = BitPart::Unset;
1972       return Result;
1973     }
1974   }
1975 
1976   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
1977   // the input value to the bswap/bitreverse.
1978   Result = BitPart(V, BitWidth);
1979   for (unsigned i = 0; i < BitWidth; ++i)
1980     Result->Provenance[i] = i;
1981   return Result;
1982 }
1983 
1984 static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To,
1985                                           unsigned BitWidth) {
1986   if (From % 8 != To % 8)
1987     return false;
1988   // Convert from bit indices to byte indices and check for a byte reversal.
1989   From >>= 3;
1990   To >>= 3;
1991   BitWidth >>= 3;
1992   return From == BitWidth - To - 1;
1993 }
1994 
1995 static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To,
1996                                                unsigned BitWidth) {
1997   return From == BitWidth - To - 1;
1998 }
1999 
2000 /// Given an OR instruction, check to see if this is a bitreverse
2001 /// idiom. If so, insert the new intrinsic and return true.
2002 bool llvm::recognizeBSwapOrBitReverseIdiom(
2003     Instruction *I, bool MatchBSwaps, bool MatchBitReversals,
2004     SmallVectorImpl<Instruction *> &InsertedInsts) {
2005   if (Operator::getOpcode(I) != Instruction::Or)
2006     return false;
2007   if (!MatchBSwaps && !MatchBitReversals)
2008     return false;
2009   IntegerType *ITy = dyn_cast<IntegerType>(I->getType());
2010   if (!ITy || ITy->getBitWidth() > 128)
2011     return false;   // Can't do vectors or integers > 128 bits.
2012   unsigned BW = ITy->getBitWidth();
2013 
2014   unsigned DemandedBW = BW;
2015   IntegerType *DemandedTy = ITy;
2016   if (I->hasOneUse()) {
2017     if (TruncInst *Trunc = dyn_cast<TruncInst>(I->user_back())) {
2018       DemandedTy = cast<IntegerType>(Trunc->getType());
2019       DemandedBW = DemandedTy->getBitWidth();
2020     }
2021   }
2022 
2023   // Try to find all the pieces corresponding to the bswap.
2024   std::map<Value *, Optional<BitPart>> BPS;
2025   auto Res = collectBitParts(I, MatchBSwaps, MatchBitReversals, BPS);
2026   if (!Res)
2027     return false;
2028   auto &BitProvenance = Res->Provenance;
2029 
2030   // Now, is the bit permutation correct for a bswap or a bitreverse? We can
2031   // only byteswap values with an even number of bytes.
2032   bool OKForBSwap = DemandedBW % 16 == 0, OKForBitReverse = true;
2033   for (unsigned i = 0; i < DemandedBW; ++i) {
2034     OKForBSwap &=
2035         bitTransformIsCorrectForBSwap(BitProvenance[i], i, DemandedBW);
2036     OKForBitReverse &=
2037         bitTransformIsCorrectForBitReverse(BitProvenance[i], i, DemandedBW);
2038   }
2039 
2040   Intrinsic::ID Intrin;
2041   if (OKForBSwap && MatchBSwaps)
2042     Intrin = Intrinsic::bswap;
2043   else if (OKForBitReverse && MatchBitReversals)
2044     Intrin = Intrinsic::bitreverse;
2045   else
2046     return false;
2047 
2048   if (ITy != DemandedTy) {
2049     Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, DemandedTy);
2050     Value *Provider = Res->Provider;
2051     IntegerType *ProviderTy = cast<IntegerType>(Provider->getType());
2052     // We may need to truncate the provider.
2053     if (DemandedTy != ProviderTy) {
2054       auto *Trunc = CastInst::Create(Instruction::Trunc, Provider, DemandedTy,
2055                                      "trunc", I);
2056       InsertedInsts.push_back(Trunc);
2057       Provider = Trunc;
2058     }
2059     auto *CI = CallInst::Create(F, Provider, "rev", I);
2060     InsertedInsts.push_back(CI);
2061     auto *ExtInst = CastInst::Create(Instruction::ZExt, CI, ITy, "zext", I);
2062     InsertedInsts.push_back(ExtInst);
2063     return true;
2064   }
2065 
2066   Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, ITy);
2067   InsertedInsts.push_back(CallInst::Create(F, Res->Provider, "rev", I));
2068   return true;
2069 }
2070 
2071 // CodeGen has special handling for some string functions that may replace
2072 // them with target-specific intrinsics.  Since that'd skip our interceptors
2073 // in ASan/MSan/TSan/DFSan, and thus make us miss some memory accesses,
2074 // we mark affected calls as NoBuiltin, which will disable optimization
2075 // in CodeGen.
2076 void llvm::maybeMarkSanitizerLibraryCallNoBuiltin(
2077     CallInst *CI, const TargetLibraryInfo *TLI) {
2078   Function *F = CI->getCalledFunction();
2079   LibFunc Func;
2080   if (F && !F->hasLocalLinkage() && F->hasName() &&
2081       TLI->getLibFunc(F->getName(), Func) && TLI->hasOptimizedCodeGen(Func) &&
2082       !F->doesNotAccessMemory())
2083     CI->addAttribute(AttributeSet::FunctionIndex, Attribute::NoBuiltin);
2084 }
2085