LLVM API Documentation

Local.cpp
Go to the documentation of this file.
00001 //===-- Local.cpp - Functions to perform local transformations ------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This family of functions perform various local transformations to the
00011 // program.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/Transforms/Utils/Local.h"
00016 #include "llvm/ADT/DenseMap.h"
00017 #include "llvm/ADT/STLExtras.h"
00018 #include "llvm/ADT/SmallPtrSet.h"
00019 #include "llvm/ADT/Statistic.h"
00020 #include "llvm/Analysis/InstructionSimplify.h"
00021 #include "llvm/Analysis/MemoryBuiltins.h"
00022 #include "llvm/Analysis/ValueTracking.h"
00023 #include "llvm/IR/CFG.h"
00024 #include "llvm/IR/Constants.h"
00025 #include "llvm/IR/DIBuilder.h"
00026 #include "llvm/IR/DataLayout.h"
00027 #include "llvm/IR/DebugInfo.h"
00028 #include "llvm/IR/DerivedTypes.h"
00029 #include "llvm/IR/Dominators.h"
00030 #include "llvm/IR/GetElementPtrTypeIterator.h"
00031 #include "llvm/IR/GlobalAlias.h"
00032 #include "llvm/IR/GlobalVariable.h"
00033 #include "llvm/IR/IRBuilder.h"
00034 #include "llvm/IR/Instructions.h"
00035 #include "llvm/IR/IntrinsicInst.h"
00036 #include "llvm/IR/Intrinsics.h"
00037 #include "llvm/IR/MDBuilder.h"
00038 #include "llvm/IR/Metadata.h"
00039 #include "llvm/IR/Operator.h"
00040 #include "llvm/IR/ValueHandle.h"
00041 #include "llvm/Support/Debug.h"
00042 #include "llvm/Support/MathExtras.h"
00043 #include "llvm/Support/raw_ostream.h"
00044 using namespace llvm;
00045 
00046 #define DEBUG_TYPE "local"
00047 
00048 STATISTIC(NumRemoved, "Number of unreachable basic blocks removed");
00049 
00050 //===----------------------------------------------------------------------===//
00051 //  Local constant propagation.
00052 //
00053 
00054 /// ConstantFoldTerminator - If a terminator instruction is predicated on a
00055 /// constant value, convert it into an unconditional branch to the constant
00056 /// destination.  This is a nontrivial operation because the successors of this
00057 /// basic block must have their PHI nodes updated.
00058 /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
00059 /// conditions and indirectbr addresses this might make dead if
00060 /// DeleteDeadConditions is true.
00061 bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
00062                                   const TargetLibraryInfo *TLI) {
00063   TerminatorInst *T = BB->getTerminator();
00064   IRBuilder<> Builder(T);
00065 
00066   // Branch - See if we are conditional jumping on constant
00067   if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
00068     if (BI->isUnconditional()) return false;  // Can't optimize uncond branch
00069     BasicBlock *Dest1 = BI->getSuccessor(0);
00070     BasicBlock *Dest2 = BI->getSuccessor(1);
00071 
00072     if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
00073       // Are we branching on constant?
00074       // YES.  Change to unconditional branch...
00075       BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
00076       BasicBlock *OldDest     = Cond->getZExtValue() ? Dest2 : Dest1;
00077 
00078       //cerr << "Function: " << T->getParent()->getParent()
00079       //     << "\nRemoving branch from " << T->getParent()
00080       //     << "\n\nTo: " << OldDest << endl;
00081 
00082       // Let the basic block know that we are letting go of it.  Based on this,
00083       // it will adjust it's PHI nodes.
00084       OldDest->removePredecessor(BB);
00085 
00086       // Replace the conditional branch with an unconditional one.
00087       Builder.CreateBr(Destination);
00088       BI->eraseFromParent();
00089       return true;
00090     }
00091 
00092     if (Dest2 == Dest1) {       // Conditional branch to same location?
00093       // This branch matches something like this:
00094       //     br bool %cond, label %Dest, label %Dest
00095       // and changes it into:  br label %Dest
00096 
00097       // Let the basic block know that we are letting go of one copy of it.
00098       assert(BI->getParent() && "Terminator not inserted in block!");
00099       Dest1->removePredecessor(BI->getParent());
00100 
00101       // Replace the conditional branch with an unconditional one.
00102       Builder.CreateBr(Dest1);
00103       Value *Cond = BI->getCondition();
00104       BI->eraseFromParent();
00105       if (DeleteDeadConditions)
00106         RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
00107       return true;
00108     }
00109     return false;
00110   }
00111 
00112   if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
00113     // If we are switching on a constant, we can convert the switch into a
00114     // single branch instruction!
00115     ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
00116     BasicBlock *TheOnlyDest = SI->getDefaultDest();
00117     BasicBlock *DefaultDest = TheOnlyDest;
00118 
00119     // Figure out which case it goes to.
00120     for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
00121          i != e; ++i) {
00122       // Found case matching a constant operand?
00123       if (i.getCaseValue() == CI) {
00124         TheOnlyDest = i.getCaseSuccessor();
00125         break;
00126       }
00127 
00128       // Check to see if this branch is going to the same place as the default
00129       // dest.  If so, eliminate it as an explicit compare.
00130       if (i.getCaseSuccessor() == DefaultDest) {
00131         MDNode* MD = SI->getMetadata(LLVMContext::MD_prof);
00132         unsigned NCases = SI->getNumCases();
00133         // Fold the case metadata into the default if there will be any branches
00134         // left, unless the metadata doesn't match the switch.
00135         if (NCases > 1 && MD && MD->getNumOperands() == 2 + NCases) {
00136           // Collect branch weights into a vector.
00137           SmallVector<uint32_t, 8> Weights;
00138           for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
00139                ++MD_i) {
00140             ConstantInt* CI = dyn_cast<ConstantInt>(MD->getOperand(MD_i));
00141             assert(CI);
00142             Weights.push_back(CI->getValue().getZExtValue());
00143           }
00144           // Merge weight of this case to the default weight.
00145           unsigned idx = i.getCaseIndex();
00146           Weights[0] += Weights[idx+1];
00147           // Remove weight for this case.
00148           std::swap(Weights[idx+1], Weights.back());
00149           Weights.pop_back();
00150           SI->setMetadata(LLVMContext::MD_prof,
00151                           MDBuilder(BB->getContext()).
00152                           createBranchWeights(Weights));
00153         }
00154         // Remove this entry.
00155         DefaultDest->removePredecessor(SI->getParent());
00156         SI->removeCase(i);
00157         --i; --e;
00158         continue;
00159       }
00160 
00161       // Otherwise, check to see if the switch only branches to one destination.
00162       // We do this by reseting "TheOnlyDest" to null when we find two non-equal
00163       // destinations.
00164       if (i.getCaseSuccessor() != TheOnlyDest) TheOnlyDest = nullptr;
00165     }
00166 
00167     if (CI && !TheOnlyDest) {
00168       // Branching on a constant, but not any of the cases, go to the default
00169       // successor.
00170       TheOnlyDest = SI->getDefaultDest();
00171     }
00172 
00173     // If we found a single destination that we can fold the switch into, do so
00174     // now.
00175     if (TheOnlyDest) {
00176       // Insert the new branch.
00177       Builder.CreateBr(TheOnlyDest);
00178       BasicBlock *BB = SI->getParent();
00179 
00180       // Remove entries from PHI nodes which we no longer branch to...
00181       for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
00182         // Found case matching a constant operand?
00183         BasicBlock *Succ = SI->getSuccessor(i);
00184         if (Succ == TheOnlyDest)
00185           TheOnlyDest = nullptr; // Don't modify the first branch to TheOnlyDest
00186         else
00187           Succ->removePredecessor(BB);
00188       }
00189 
00190       // Delete the old switch.
00191       Value *Cond = SI->getCondition();
00192       SI->eraseFromParent();
00193       if (DeleteDeadConditions)
00194         RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
00195       return true;
00196     }
00197 
00198     if (SI->getNumCases() == 1) {
00199       // Otherwise, we can fold this switch into a conditional branch
00200       // instruction if it has only one non-default destination.
00201       SwitchInst::CaseIt FirstCase = SI->case_begin();
00202       Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
00203           FirstCase.getCaseValue(), "cond");
00204 
00205       // Insert the new branch.
00206       BranchInst *NewBr = Builder.CreateCondBr(Cond,
00207                                                FirstCase.getCaseSuccessor(),
00208                                                SI->getDefaultDest());
00209       MDNode* MD = SI->getMetadata(LLVMContext::MD_prof);
00210       if (MD && MD->getNumOperands() == 3) {
00211         ConstantInt *SICase = dyn_cast<ConstantInt>(MD->getOperand(2));
00212         ConstantInt *SIDef = dyn_cast<ConstantInt>(MD->getOperand(1));
00213         assert(SICase && SIDef);
00214         // The TrueWeight should be the weight for the single case of SI.
00215         NewBr->setMetadata(LLVMContext::MD_prof,
00216                         MDBuilder(BB->getContext()).
00217                         createBranchWeights(SICase->getValue().getZExtValue(),
00218                                             SIDef->getValue().getZExtValue()));
00219       }
00220 
00221       // Delete the old switch.
00222       SI->eraseFromParent();
00223       return true;
00224     }
00225     return false;
00226   }
00227 
00228   if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(T)) {
00229     // indirectbr blockaddress(@F, @BB) -> br label @BB
00230     if (BlockAddress *BA =
00231           dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
00232       BasicBlock *TheOnlyDest = BA->getBasicBlock();
00233       // Insert the new branch.
00234       Builder.CreateBr(TheOnlyDest);
00235 
00236       for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
00237         if (IBI->getDestination(i) == TheOnlyDest)
00238           TheOnlyDest = nullptr;
00239         else
00240           IBI->getDestination(i)->removePredecessor(IBI->getParent());
00241       }
00242       Value *Address = IBI->getAddress();
00243       IBI->eraseFromParent();
00244       if (DeleteDeadConditions)
00245         RecursivelyDeleteTriviallyDeadInstructions(Address, TLI);
00246 
00247       // If we didn't find our destination in the IBI successor list, then we
00248       // have undefined behavior.  Replace the unconditional branch with an
00249       // 'unreachable' instruction.
00250       if (TheOnlyDest) {
00251         BB->getTerminator()->eraseFromParent();
00252         new UnreachableInst(BB->getContext(), BB);
00253       }
00254 
00255       return true;
00256     }
00257   }
00258 
00259   return false;
00260 }
00261 
00262 
00263 //===----------------------------------------------------------------------===//
00264 //  Local dead code elimination.
00265 //
00266 
00267 /// isInstructionTriviallyDead - Return true if the result produced by the
00268 /// instruction is not used, and the instruction has no side effects.
00269 ///
00270 bool llvm::isInstructionTriviallyDead(Instruction *I,
00271                                       const TargetLibraryInfo *TLI) {
00272   if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
00273 
00274   // We don't want the landingpad instruction removed by anything this general.
00275   if (isa<LandingPadInst>(I))
00276     return false;
00277 
00278   // We don't want debug info removed by anything this general, unless
00279   // debug info is empty.
00280   if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
00281     if (DDI->getAddress())
00282       return false;
00283     return true;
00284   }
00285   if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
00286     if (DVI->getValue())
00287       return false;
00288     return true;
00289   }
00290 
00291   if (!I->mayHaveSideEffects()) return true;
00292 
00293   // Special case intrinsics that "may have side effects" but can be deleted
00294   // when dead.
00295   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
00296     // Safe to delete llvm.stacksave if dead.
00297     if (II->getIntrinsicID() == Intrinsic::stacksave)
00298       return true;
00299 
00300     // Lifetime intrinsics are dead when their right-hand is undef.
00301     if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
00302         II->getIntrinsicID() == Intrinsic::lifetime_end)
00303       return isa<UndefValue>(II->getArgOperand(1));
00304   }
00305 
00306   if (isAllocLikeFn(I, TLI)) return true;
00307 
00308   if (CallInst *CI = isFreeCall(I, TLI))
00309     if (Constant *C = dyn_cast<Constant>(CI->getArgOperand(0)))
00310       return C->isNullValue() || isa<UndefValue>(C);
00311 
00312   return false;
00313 }
00314 
00315 /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
00316 /// trivially dead instruction, delete it.  If that makes any of its operands
00317 /// trivially dead, delete them too, recursively.  Return true if any
00318 /// instructions were deleted.
00319 bool
00320 llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V,
00321                                                  const TargetLibraryInfo *TLI) {
00322   Instruction *I = dyn_cast<Instruction>(V);
00323   if (!I || !I->use_empty() || !isInstructionTriviallyDead(I, TLI))
00324     return false;
00325 
00326   SmallVector<Instruction*, 16> DeadInsts;
00327   DeadInsts.push_back(I);
00328 
00329   do {
00330     I = DeadInsts.pop_back_val();
00331 
00332     // Null out all of the instruction's operands to see if any operand becomes
00333     // dead as we go.
00334     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
00335       Value *OpV = I->getOperand(i);
00336       I->setOperand(i, nullptr);
00337 
00338       if (!OpV->use_empty()) continue;
00339 
00340       // If the operand is an instruction that became dead as we nulled out the
00341       // operand, and if it is 'trivially' dead, delete it in a future loop
00342       // iteration.
00343       if (Instruction *OpI = dyn_cast<Instruction>(OpV))
00344         if (isInstructionTriviallyDead(OpI, TLI))
00345           DeadInsts.push_back(OpI);
00346     }
00347 
00348     I->eraseFromParent();
00349   } while (!DeadInsts.empty());
00350 
00351   return true;
00352 }
00353 
00354 /// areAllUsesEqual - Check whether the uses of a value are all the same.
00355 /// This is similar to Instruction::hasOneUse() except this will also return
00356 /// true when there are no uses or multiple uses that all refer to the same
00357 /// value.
00358 static bool areAllUsesEqual(Instruction *I) {
00359   Value::user_iterator UI = I->user_begin();
00360   Value::user_iterator UE = I->user_end();
00361   if (UI == UE)
00362     return true;
00363 
00364   User *TheUse = *UI;
00365   for (++UI; UI != UE; ++UI) {
00366     if (*UI != TheUse)
00367       return false;
00368   }
00369   return true;
00370 }
00371 
00372 /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
00373 /// dead PHI node, due to being a def-use chain of single-use nodes that
00374 /// either forms a cycle or is terminated by a trivially dead instruction,
00375 /// delete it.  If that makes any of its operands trivially dead, delete them
00376 /// too, recursively.  Return true if a change was made.
00377 bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN,
00378                                         const TargetLibraryInfo *TLI) {
00379   SmallPtrSet<Instruction*, 4> Visited;
00380   for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
00381        I = cast<Instruction>(*I->user_begin())) {
00382     if (I->use_empty())
00383       return RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
00384 
00385     // If we find an instruction more than once, we're on a cycle that
00386     // won't prove fruitful.
00387     if (!Visited.insert(I)) {
00388       // Break the cycle and delete the instruction and its operands.
00389       I->replaceAllUsesWith(UndefValue::get(I->getType()));
00390       (void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
00391       return true;
00392     }
00393   }
00394   return false;
00395 }
00396 
00397 /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
00398 /// simplify any instructions in it and recursively delete dead instructions.
00399 ///
00400 /// This returns true if it changed the code, note that it can delete
00401 /// instructions in other blocks as well in this block.
00402 bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB, const DataLayout *TD,
00403                                        const TargetLibraryInfo *TLI) {
00404   bool MadeChange = false;
00405 
00406 #ifndef NDEBUG
00407   // In debug builds, ensure that the terminator of the block is never replaced
00408   // or deleted by these simplifications. The idea of simplification is that it
00409   // cannot introduce new instructions, and there is no way to replace the
00410   // terminator of a block without introducing a new instruction.
00411   AssertingVH<Instruction> TerminatorVH(--BB->end());
00412 #endif
00413 
00414   for (BasicBlock::iterator BI = BB->begin(), E = --BB->end(); BI != E; ) {
00415     assert(!BI->isTerminator());
00416     Instruction *Inst = BI++;
00417 
00418     WeakVH BIHandle(BI);
00419     if (recursivelySimplifyInstruction(Inst, TD, TLI)) {
00420       MadeChange = true;
00421       if (BIHandle != BI)
00422         BI = BB->begin();
00423       continue;
00424     }
00425 
00426     MadeChange |= RecursivelyDeleteTriviallyDeadInstructions(Inst, TLI);
00427     if (BIHandle != BI)
00428       BI = BB->begin();
00429   }
00430   return MadeChange;
00431 }
00432 
00433 //===----------------------------------------------------------------------===//
00434 //  Control Flow Graph Restructuring.
00435 //
00436 
00437 
00438 /// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
00439 /// method is called when we're about to delete Pred as a predecessor of BB.  If
00440 /// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
00441 ///
00442 /// Unlike the removePredecessor method, this attempts to simplify uses of PHI
00443 /// nodes that collapse into identity values.  For example, if we have:
00444 ///   x = phi(1, 0, 0, 0)
00445 ///   y = and x, z
00446 ///
00447 /// .. and delete the predecessor corresponding to the '1', this will attempt to
00448 /// recursively fold the and to 0.
00449 void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
00450                                         DataLayout *TD) {
00451   // This only adjusts blocks with PHI nodes.
00452   if (!isa<PHINode>(BB->begin()))
00453     return;
00454 
00455   // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
00456   // them down.  This will leave us with single entry phi nodes and other phis
00457   // that can be removed.
00458   BB->removePredecessor(Pred, true);
00459 
00460   WeakVH PhiIt = &BB->front();
00461   while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
00462     PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
00463     Value *OldPhiIt = PhiIt;
00464 
00465     if (!recursivelySimplifyInstruction(PN, TD))
00466       continue;
00467 
00468     // If recursive simplification ended up deleting the next PHI node we would
00469     // iterate to, then our iterator is invalid, restart scanning from the top
00470     // of the block.
00471     if (PhiIt != OldPhiIt) PhiIt = &BB->front();
00472   }
00473 }
00474 
00475 
00476 /// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
00477 /// predecessor is known to have one successor (DestBB!).  Eliminate the edge
00478 /// between them, moving the instructions in the predecessor into DestBB and
00479 /// deleting the predecessor block.
00480 ///
00481 void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, Pass *P) {
00482   // If BB has single-entry PHI nodes, fold them.
00483   while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
00484     Value *NewVal = PN->getIncomingValue(0);
00485     // Replace self referencing PHI with undef, it must be dead.
00486     if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
00487     PN->replaceAllUsesWith(NewVal);
00488     PN->eraseFromParent();
00489   }
00490 
00491   BasicBlock *PredBB = DestBB->getSinglePredecessor();
00492   assert(PredBB && "Block doesn't have a single predecessor!");
00493 
00494   // Zap anything that took the address of DestBB.  Not doing this will give the
00495   // address an invalid value.
00496   if (DestBB->hasAddressTaken()) {
00497     BlockAddress *BA = BlockAddress::get(DestBB);
00498     Constant *Replacement =
00499       ConstantInt::get(llvm::Type::getInt32Ty(BA->getContext()), 1);
00500     BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
00501                                                      BA->getType()));
00502     BA->destroyConstant();
00503   }
00504 
00505   // Anything that branched to PredBB now branches to DestBB.
00506   PredBB->replaceAllUsesWith(DestBB);
00507 
00508   // Splice all the instructions from PredBB to DestBB.
00509   PredBB->getTerminator()->eraseFromParent();
00510   DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
00511 
00512   // If the PredBB is the entry block of the function, move DestBB up to
00513   // become the entry block after we erase PredBB.
00514   if (PredBB == &DestBB->getParent()->getEntryBlock())
00515     DestBB->moveAfter(PredBB);
00516 
00517   if (P) {
00518     if (DominatorTreeWrapperPass *DTWP =
00519             P->getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
00520       DominatorTree &DT = DTWP->getDomTree();
00521       BasicBlock *PredBBIDom = DT.getNode(PredBB)->getIDom()->getBlock();
00522       DT.changeImmediateDominator(DestBB, PredBBIDom);
00523       DT.eraseNode(PredBB);
00524     }
00525   }
00526   // Nuke BB.
00527   PredBB->eraseFromParent();
00528 }
00529 
00530 /// CanMergeValues - Return true if we can choose one of these values to use
00531 /// in place of the other. Note that we will always choose the non-undef
00532 /// value to keep.
00533 static bool CanMergeValues(Value *First, Value *Second) {
00534   return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
00535 }
00536 
00537 /// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
00538 /// almost-empty BB ending in an unconditional branch to Succ, into Succ.
00539 ///
00540 /// Assumption: Succ is the single successor for BB.
00541 ///
00542 static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
00543   assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
00544 
00545   DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
00546         << Succ->getName() << "\n");
00547   // Shortcut, if there is only a single predecessor it must be BB and merging
00548   // is always safe
00549   if (Succ->getSinglePredecessor()) return true;
00550 
00551   // Make a list of the predecessors of BB
00552   SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
00553 
00554   // Look at all the phi nodes in Succ, to see if they present a conflict when
00555   // merging these blocks
00556   for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
00557     PHINode *PN = cast<PHINode>(I);
00558 
00559     // If the incoming value from BB is again a PHINode in
00560     // BB which has the same incoming value for *PI as PN does, we can
00561     // merge the phi nodes and then the blocks can still be merged
00562     PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
00563     if (BBPN && BBPN->getParent() == BB) {
00564       for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
00565         BasicBlock *IBB = PN->getIncomingBlock(PI);
00566         if (BBPreds.count(IBB) &&
00567             !CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
00568                             PN->getIncomingValue(PI))) {
00569           DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
00570                 << Succ->getName() << " is conflicting with "
00571                 << BBPN->getName() << " with regard to common predecessor "
00572                 << IBB->getName() << "\n");
00573           return false;
00574         }
00575       }
00576     } else {
00577       Value* Val = PN->getIncomingValueForBlock(BB);
00578       for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
00579         // See if the incoming value for the common predecessor is equal to the
00580         // one for BB, in which case this phi node will not prevent the merging
00581         // of the block.
00582         BasicBlock *IBB = PN->getIncomingBlock(PI);
00583         if (BBPreds.count(IBB) &&
00584             !CanMergeValues(Val, PN->getIncomingValue(PI))) {
00585           DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
00586                 << Succ->getName() << " is conflicting with regard to common "
00587                 << "predecessor " << IBB->getName() << "\n");
00588           return false;
00589         }
00590       }
00591     }
00592   }
00593 
00594   return true;
00595 }
00596 
00597 typedef SmallVector<BasicBlock *, 16> PredBlockVector;
00598 typedef DenseMap<BasicBlock *, Value *> IncomingValueMap;
00599 
00600 /// \brief Determines the value to use as the phi node input for a block.
00601 ///
00602 /// Select between \p OldVal any value that we know flows from \p BB
00603 /// to a particular phi on the basis of which one (if either) is not
00604 /// undef. Update IncomingValues based on the selected value.
00605 ///
00606 /// \param OldVal The value we are considering selecting.
00607 /// \param BB The block that the value flows in from.
00608 /// \param IncomingValues A map from block-to-value for other phi inputs
00609 /// that we have examined.
00610 ///
00611 /// \returns the selected value.
00612 static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
00613                                           IncomingValueMap &IncomingValues) {
00614   if (!isa<UndefValue>(OldVal)) {
00615     assert((!IncomingValues.count(BB) ||
00616             IncomingValues.find(BB)->second == OldVal) &&
00617            "Expected OldVal to match incoming value from BB!");
00618 
00619     IncomingValues.insert(std::make_pair(BB, OldVal));
00620     return OldVal;
00621   }
00622 
00623   IncomingValueMap::const_iterator It = IncomingValues.find(BB);
00624   if (It != IncomingValues.end()) return It->second;
00625 
00626   return OldVal;
00627 }
00628 
00629 /// \brief Create a map from block to value for the operands of a
00630 /// given phi.
00631 ///
00632 /// Create a map from block to value for each non-undef value flowing
00633 /// into \p PN.
00634 ///
00635 /// \param PN The phi we are collecting the map for.
00636 /// \param IncomingValues [out] The map from block to value for this phi.
00637 static void gatherIncomingValuesToPhi(PHINode *PN,
00638                                       IncomingValueMap &IncomingValues) {
00639   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00640     BasicBlock *BB = PN->getIncomingBlock(i);
00641     Value *V = PN->getIncomingValue(i);
00642 
00643     if (!isa<UndefValue>(V))
00644       IncomingValues.insert(std::make_pair(BB, V));
00645   }
00646 }
00647 
00648 /// \brief Replace the incoming undef values to a phi with the values
00649 /// from a block-to-value map.
00650 ///
00651 /// \param PN The phi we are replacing the undefs in.
00652 /// \param IncomingValues A map from block to value.
00653 static void replaceUndefValuesInPhi(PHINode *PN,
00654                                     const IncomingValueMap &IncomingValues) {
00655   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00656     Value *V = PN->getIncomingValue(i);
00657 
00658     if (!isa<UndefValue>(V)) continue;
00659 
00660     BasicBlock *BB = PN->getIncomingBlock(i);
00661     IncomingValueMap::const_iterator It = IncomingValues.find(BB);
00662     if (It == IncomingValues.end()) continue;
00663 
00664     PN->setIncomingValue(i, It->second);
00665   }
00666 }
00667 
00668 /// \brief Replace a value flowing from a block to a phi with
00669 /// potentially multiple instances of that value flowing from the
00670 /// block's predecessors to the phi.
00671 ///
00672 /// \param BB The block with the value flowing into the phi.
00673 /// \param BBPreds The predecessors of BB.
00674 /// \param PN The phi that we are updating.
00675 static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
00676                                                 const PredBlockVector &BBPreds,
00677                                                 PHINode *PN) {
00678   Value *OldVal = PN->removeIncomingValue(BB, false);
00679   assert(OldVal && "No entry in PHI for Pred BB!");
00680 
00681   IncomingValueMap IncomingValues;
00682 
00683   // We are merging two blocks - BB, and the block containing PN - and
00684   // as a result we need to redirect edges from the predecessors of BB
00685   // to go to the block containing PN, and update PN
00686   // accordingly. Since we allow merging blocks in the case where the
00687   // predecessor and successor blocks both share some predecessors,
00688   // and where some of those common predecessors might have undef
00689   // values flowing into PN, we want to rewrite those values to be
00690   // consistent with the non-undef values.
00691 
00692   gatherIncomingValuesToPhi(PN, IncomingValues);
00693 
00694   // If this incoming value is one of the PHI nodes in BB, the new entries
00695   // in the PHI node are the entries from the old PHI.
00696   if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
00697     PHINode *OldValPN = cast<PHINode>(OldVal);
00698     for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
00699       // Note that, since we are merging phi nodes and BB and Succ might
00700       // have common predecessors, we could end up with a phi node with
00701       // identical incoming branches. This will be cleaned up later (and
00702       // will trigger asserts if we try to clean it up now, without also
00703       // simplifying the corresponding conditional branch).
00704       BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
00705       Value *PredVal = OldValPN->getIncomingValue(i);
00706       Value *Selected = selectIncomingValueForBlock(PredVal, PredBB,
00707                                                     IncomingValues);
00708 
00709       // And add a new incoming value for this predecessor for the
00710       // newly retargeted branch.
00711       PN->addIncoming(Selected, PredBB);
00712     }
00713   } else {
00714     for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) {
00715       // Update existing incoming values in PN for this
00716       // predecessor of BB.
00717       BasicBlock *PredBB = BBPreds[i];
00718       Value *Selected = selectIncomingValueForBlock(OldVal, PredBB,
00719                                                     IncomingValues);
00720 
00721       // And add a new incoming value for this predecessor for the
00722       // newly retargeted branch.
00723       PN->addIncoming(Selected, PredBB);
00724     }
00725   }
00726 
00727   replaceUndefValuesInPhi(PN, IncomingValues);
00728 }
00729 
00730 /// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
00731 /// unconditional branch, and contains no instructions other than PHI nodes,
00732 /// potential side-effect free intrinsics and the branch.  If possible,
00733 /// eliminate BB by rewriting all the predecessors to branch to the successor
00734 /// block and return true.  If we can't transform, return false.
00735 bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) {
00736   assert(BB != &BB->getParent()->getEntryBlock() &&
00737          "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
00738 
00739   // We can't eliminate infinite loops.
00740   BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
00741   if (BB == Succ) return false;
00742 
00743   // Check to see if merging these blocks would cause conflicts for any of the
00744   // phi nodes in BB or Succ. If not, we can safely merge.
00745   if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
00746 
00747   // Check for cases where Succ has multiple predecessors and a PHI node in BB
00748   // has uses which will not disappear when the PHI nodes are merged.  It is
00749   // possible to handle such cases, but difficult: it requires checking whether
00750   // BB dominates Succ, which is non-trivial to calculate in the case where
00751   // Succ has multiple predecessors.  Also, it requires checking whether
00752   // constructing the necessary self-referential PHI node doesn't introduce any
00753   // conflicts; this isn't too difficult, but the previous code for doing this
00754   // was incorrect.
00755   //
00756   // Note that if this check finds a live use, BB dominates Succ, so BB is
00757   // something like a loop pre-header (or rarely, a part of an irreducible CFG);
00758   // folding the branch isn't profitable in that case anyway.
00759   if (!Succ->getSinglePredecessor()) {
00760     BasicBlock::iterator BBI = BB->begin();
00761     while (isa<PHINode>(*BBI)) {
00762       for (Use &U : BBI->uses()) {
00763         if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
00764           if (PN->getIncomingBlock(U) != BB)
00765             return false;
00766         } else {
00767           return false;
00768         }
00769       }
00770       ++BBI;
00771     }
00772   }
00773 
00774   DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
00775 
00776   if (isa<PHINode>(Succ->begin())) {
00777     // If there is more than one pred of succ, and there are PHI nodes in
00778     // the successor, then we need to add incoming edges for the PHI nodes
00779     //
00780     const PredBlockVector BBPreds(pred_begin(BB), pred_end(BB));
00781 
00782     // Loop over all of the PHI nodes in the successor of BB.
00783     for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
00784       PHINode *PN = cast<PHINode>(I);
00785 
00786       redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN);
00787     }
00788   }
00789 
00790   if (Succ->getSinglePredecessor()) {
00791     // BB is the only predecessor of Succ, so Succ will end up with exactly
00792     // the same predecessors BB had.
00793 
00794     // Copy over any phi, debug or lifetime instruction.
00795     BB->getTerminator()->eraseFromParent();
00796     Succ->getInstList().splice(Succ->getFirstNonPHI(), BB->getInstList());
00797   } else {
00798     while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
00799       // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
00800       assert(PN->use_empty() && "There shouldn't be any uses here!");
00801       PN->eraseFromParent();
00802     }
00803   }
00804 
00805   // Everything that jumped to BB now goes to Succ.
00806   BB->replaceAllUsesWith(Succ);
00807   if (!Succ->hasName()) Succ->takeName(BB);
00808   BB->eraseFromParent();              // Delete the old basic block.
00809   return true;
00810 }
00811 
00812 /// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
00813 /// nodes in this block. This doesn't try to be clever about PHI nodes
00814 /// which differ only in the order of the incoming values, but instcombine
00815 /// orders them so it usually won't matter.
00816 ///
00817 bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
00818   bool Changed = false;
00819 
00820   // This implementation doesn't currently consider undef operands
00821   // specially. Theoretically, two phis which are identical except for
00822   // one having an undef where the other doesn't could be collapsed.
00823 
00824   // Map from PHI hash values to PHI nodes. If multiple PHIs have
00825   // the same hash value, the element is the first PHI in the
00826   // linked list in CollisionMap.
00827   DenseMap<uintptr_t, PHINode *> HashMap;
00828 
00829   // Maintain linked lists of PHI nodes with common hash values.
00830   DenseMap<PHINode *, PHINode *> CollisionMap;
00831 
00832   // Examine each PHI.
00833   for (BasicBlock::iterator I = BB->begin();
00834        PHINode *PN = dyn_cast<PHINode>(I++); ) {
00835     // Compute a hash value on the operands. Instcombine will likely have sorted
00836     // them, which helps expose duplicates, but we have to check all the
00837     // operands to be safe in case instcombine hasn't run.
00838     uintptr_t Hash = 0;
00839     // This hash algorithm is quite weak as hash functions go, but it seems
00840     // to do a good enough job for this particular purpose, and is very quick.
00841     for (User::op_iterator I = PN->op_begin(), E = PN->op_end(); I != E; ++I) {
00842       Hash ^= reinterpret_cast<uintptr_t>(static_cast<Value *>(*I));
00843       Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
00844     }
00845     for (PHINode::block_iterator I = PN->block_begin(), E = PN->block_end();
00846          I != E; ++I) {
00847       Hash ^= reinterpret_cast<uintptr_t>(static_cast<BasicBlock *>(*I));
00848       Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
00849     }
00850     // Avoid colliding with the DenseMap sentinels ~0 and ~0-1.
00851     Hash >>= 1;
00852     // If we've never seen this hash value before, it's a unique PHI.
00853     std::pair<DenseMap<uintptr_t, PHINode *>::iterator, bool> Pair =
00854       HashMap.insert(std::make_pair(Hash, PN));
00855     if (Pair.second) continue;
00856     // Otherwise it's either a duplicate or a hash collision.
00857     for (PHINode *OtherPN = Pair.first->second; ; ) {
00858       if (OtherPN->isIdenticalTo(PN)) {
00859         // A duplicate. Replace this PHI with its duplicate.
00860         PN->replaceAllUsesWith(OtherPN);
00861         PN->eraseFromParent();
00862         Changed = true;
00863         break;
00864       }
00865       // A non-duplicate hash collision.
00866       DenseMap<PHINode *, PHINode *>::iterator I = CollisionMap.find(OtherPN);
00867       if (I == CollisionMap.end()) {
00868         // Set this PHI to be the head of the linked list of colliding PHIs.
00869         PHINode *Old = Pair.first->second;
00870         Pair.first->second = PN;
00871         CollisionMap[PN] = Old;
00872         break;
00873       }
00874       // Proceed to the next PHI in the list.
00875       OtherPN = I->second;
00876     }
00877   }
00878 
00879   return Changed;
00880 }
00881 
00882 /// enforceKnownAlignment - If the specified pointer points to an object that
00883 /// we control, modify the object's alignment to PrefAlign. This isn't
00884 /// often possible though. If alignment is important, a more reliable approach
00885 /// is to simply align all global variables and allocation instructions to
00886 /// their preferred alignment from the beginning.
00887 ///
00888 static unsigned enforceKnownAlignment(Value *V, unsigned Align,
00889                                       unsigned PrefAlign, const DataLayout *TD) {
00890   V = V->stripPointerCasts();
00891 
00892   if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
00893     // If the preferred alignment is greater than the natural stack alignment
00894     // then don't round up. This avoids dynamic stack realignment.
00895     if (TD && TD->exceedsNaturalStackAlignment(PrefAlign))
00896       return Align;
00897     // If there is a requested alignment and if this is an alloca, round up.
00898     if (AI->getAlignment() >= PrefAlign)
00899       return AI->getAlignment();
00900     AI->setAlignment(PrefAlign);
00901     return PrefAlign;
00902   }
00903 
00904   if (auto *GO = dyn_cast<GlobalObject>(V)) {
00905     // If there is a large requested alignment and we can, bump up the alignment
00906     // of the global.
00907     if (GO->isDeclaration())
00908       return Align;
00909     // If the memory we set aside for the global may not be the memory used by
00910     // the final program then it is impossible for us to reliably enforce the
00911     // preferred alignment.
00912     if (GO->isWeakForLinker())
00913       return Align;
00914 
00915     if (GO->getAlignment() >= PrefAlign)
00916       return GO->getAlignment();
00917     // We can only increase the alignment of the global if it has no alignment
00918     // specified or if it is not assigned a section.  If it is assigned a
00919     // section, the global could be densely packed with other objects in the
00920     // section, increasing the alignment could cause padding issues.
00921     if (!GO->hasSection() || GO->getAlignment() == 0)
00922       GO->setAlignment(PrefAlign);
00923     return GO->getAlignment();
00924   }
00925 
00926   return Align;
00927 }
00928 
00929 /// getOrEnforceKnownAlignment - If the specified pointer has an alignment that
00930 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
00931 /// and it is more than the alignment of the ultimate object, see if we can
00932 /// increase the alignment of the ultimate object, making this check succeed.
00933 unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
00934                                           const DataLayout *DL) {
00935   assert(V->getType()->isPointerTy() &&
00936          "getOrEnforceKnownAlignment expects a pointer!");
00937   unsigned BitWidth = DL ? DL->getPointerTypeSizeInBits(V->getType()) : 64;
00938 
00939   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
00940   computeKnownBits(V, KnownZero, KnownOne, DL);
00941   unsigned TrailZ = KnownZero.countTrailingOnes();
00942 
00943   // Avoid trouble with ridiculously large TrailZ values, such as
00944   // those computed from a null pointer.
00945   TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
00946 
00947   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
00948 
00949   // LLVM doesn't support alignments larger than this currently.
00950   Align = std::min(Align, +Value::MaximumAlignment);
00951 
00952   if (PrefAlign > Align)
00953     Align = enforceKnownAlignment(V, Align, PrefAlign, DL);
00954 
00955   // We don't need to make any adjustment.
00956   return Align;
00957 }
00958 
00959 ///===---------------------------------------------------------------------===//
00960 ///  Dbg Intrinsic utilities
00961 ///
00962 
00963 /// See if there is a dbg.value intrinsic for DIVar before I.
00964 static bool LdStHasDebugValue(DIVariable &DIVar, Instruction *I) {
00965   // Since we can't guarantee that the original dbg.declare instrinsic
00966   // is removed by LowerDbgDeclare(), we need to make sure that we are
00967   // not inserting the same dbg.value intrinsic over and over.
00968   llvm::BasicBlock::InstListType::iterator PrevI(I);
00969   if (PrevI != I->getParent()->getInstList().begin()) {
00970     --PrevI;
00971     if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(PrevI))
00972       if (DVI->getValue() == I->getOperand(0) &&
00973           DVI->getOffset() == 0 &&
00974           DVI->getVariable() == DIVar)
00975         return true;
00976   }
00977   return false;
00978 }
00979 
00980 /// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
00981 /// that has an associated llvm.dbg.decl intrinsic.
00982 bool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
00983                                            StoreInst *SI, DIBuilder &Builder) {
00984   DIVariable DIVar(DDI->getVariable());
00985   assert((!DIVar || DIVar.isVariable()) &&
00986          "Variable in DbgDeclareInst should be either null or a DIVariable.");
00987   if (!DIVar)
00988     return false;
00989 
00990   if (LdStHasDebugValue(DIVar, SI))
00991     return true;
00992 
00993   Instruction *DbgVal = nullptr;
00994   // If an argument is zero extended then use argument directly. The ZExt
00995   // may be zapped by an optimization pass in future.
00996   Argument *ExtendedArg = nullptr;
00997   if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
00998     ExtendedArg = dyn_cast<Argument>(ZExt->getOperand(0));
00999   if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
01000     ExtendedArg = dyn_cast<Argument>(SExt->getOperand(0));
01001   if (ExtendedArg)
01002     DbgVal = Builder.insertDbgValueIntrinsic(ExtendedArg, 0, DIVar, SI);
01003   else
01004     DbgVal = Builder.insertDbgValueIntrinsic(SI->getOperand(0), 0, DIVar, SI);
01005   DbgVal->setDebugLoc(DDI->getDebugLoc());
01006   return true;
01007 }
01008 
01009 /// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
01010 /// that has an associated llvm.dbg.decl intrinsic.
01011 bool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
01012                                            LoadInst *LI, DIBuilder &Builder) {
01013   DIVariable DIVar(DDI->getVariable());
01014   assert((!DIVar || DIVar.isVariable()) &&
01015          "Variable in DbgDeclareInst should be either null or a DIVariable.");
01016   if (!DIVar)
01017     return false;
01018 
01019   if (LdStHasDebugValue(DIVar, LI))
01020     return true;
01021 
01022   Instruction *DbgVal =
01023     Builder.insertDbgValueIntrinsic(LI->getOperand(0), 0,
01024                                     DIVar, LI);
01025   DbgVal->setDebugLoc(DDI->getDebugLoc());
01026   return true;
01027 }
01028 
01029 /// Determine whether this alloca is either a VLA or an array.
01030 static bool isArray(AllocaInst *AI) {
01031   return AI->isArrayAllocation() ||
01032     AI->getType()->getElementType()->isArrayTy();
01033 }
01034 
01035 /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
01036 /// of llvm.dbg.value intrinsics.
01037 bool llvm::LowerDbgDeclare(Function &F) {
01038   DIBuilder DIB(*F.getParent());
01039   SmallVector<DbgDeclareInst *, 4> Dbgs;
01040   for (auto &FI : F)
01041     for (BasicBlock::iterator BI : FI)
01042       if (auto DDI = dyn_cast<DbgDeclareInst>(BI))
01043         Dbgs.push_back(DDI);
01044 
01045   if (Dbgs.empty())
01046     return false;
01047 
01048   for (auto &I : Dbgs) {
01049     DbgDeclareInst *DDI = I;
01050     AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
01051     // If this is an alloca for a scalar variable, insert a dbg.value
01052     // at each load and store to the alloca and erase the dbg.declare.
01053     // The dbg.values allow tracking a variable even if it is not
01054     // stored on the stack, while the dbg.declare can only describe
01055     // the stack slot (and at a lexical-scope granularity). Later
01056     // passes will attempt to elide the stack slot.
01057     if (AI && !isArray(AI)) {
01058       for (User *U : AI->users())
01059         if (StoreInst *SI = dyn_cast<StoreInst>(U))
01060           ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
01061         else if (LoadInst *LI = dyn_cast<LoadInst>(U))
01062           ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
01063         else if (CallInst *CI = dyn_cast<CallInst>(U)) {
01064     // This is a call by-value or some other instruction that
01065     // takes a pointer to the variable. Insert a *value*
01066     // intrinsic that describes the alloca.
01067     auto DbgVal =
01068       DIB.insertDbgValueIntrinsic(AI, 0,
01069           DIVariable(DDI->getVariable()), CI);
01070     DbgVal->setDebugLoc(DDI->getDebugLoc());
01071   }
01072       DDI->eraseFromParent();
01073     }
01074   }
01075   return true;
01076 }
01077 
01078 /// FindAllocaDbgDeclare - Finds the llvm.dbg.declare intrinsic describing the
01079 /// alloca 'V', if any.
01080 DbgDeclareInst *llvm::FindAllocaDbgDeclare(Value *V) {
01081   if (MDNode *DebugNode = MDNode::getIfExists(V->getContext(), V))
01082     for (User *U : DebugNode->users())
01083       if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
01084         return DDI;
01085 
01086   return nullptr;
01087 }
01088 
01089 bool llvm::replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
01090                                       DIBuilder &Builder) {
01091   DbgDeclareInst *DDI = FindAllocaDbgDeclare(AI);
01092   if (!DDI)
01093     return false;
01094   DIVariable DIVar(DDI->getVariable());
01095   assert((!DIVar || DIVar.isVariable()) &&
01096          "Variable in DbgDeclareInst should be either null or a DIVariable.");
01097   if (!DIVar)
01098     return false;
01099 
01100   // Create a copy of the original DIDescriptor for user variable, appending
01101   // "deref" operation to a list of address elements, as new llvm.dbg.declare
01102   // will take a value storing address of the memory for variable, not
01103   // alloca itself.
01104   Type *Int64Ty = Type::getInt64Ty(AI->getContext());
01105   SmallVector<Value*, 4> NewDIVarAddress;
01106   if (DIVar.hasComplexAddress()) {
01107     for (unsigned i = 0, n = DIVar.getNumAddrElements(); i < n; ++i) {
01108       NewDIVarAddress.push_back(
01109           ConstantInt::get(Int64Ty, DIVar.getAddrElement(i)));
01110     }
01111   }
01112   NewDIVarAddress.push_back(ConstantInt::get(Int64Ty, DIBuilder::OpDeref));
01113   DIVariable NewDIVar = Builder.createComplexVariable(
01114       DIVar.getTag(), DIVar.getContext(), DIVar.getName(),
01115       DIVar.getFile(), DIVar.getLineNumber(), DIVar.getType(),
01116       NewDIVarAddress, DIVar.getArgNumber());
01117 
01118   // Insert llvm.dbg.declare in the same basic block as the original alloca,
01119   // and remove old llvm.dbg.declare.
01120   BasicBlock *BB = AI->getParent();
01121   Builder.insertDeclare(NewAllocaAddress, NewDIVar, BB);
01122   DDI->eraseFromParent();
01123   return true;
01124 }
01125 
01126 /// changeToUnreachable - Insert an unreachable instruction before the specified
01127 /// instruction, making it and the rest of the code in the block dead.
01128 static void changeToUnreachable(Instruction *I, bool UseLLVMTrap) {
01129   BasicBlock *BB = I->getParent();
01130   // Loop over all of the successors, removing BB's entry from any PHI
01131   // nodes.
01132   for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
01133     (*SI)->removePredecessor(BB);
01134 
01135   // Insert a call to llvm.trap right before this.  This turns the undefined
01136   // behavior into a hard fail instead of falling through into random code.
01137   if (UseLLVMTrap) {
01138     Function *TrapFn =
01139       Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap);
01140     CallInst *CallTrap = CallInst::Create(TrapFn, "", I);
01141     CallTrap->setDebugLoc(I->getDebugLoc());
01142   }
01143   new UnreachableInst(I->getContext(), I);
01144 
01145   // All instructions after this are dead.
01146   BasicBlock::iterator BBI = I, BBE = BB->end();
01147   while (BBI != BBE) {
01148     if (!BBI->use_empty())
01149       BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
01150     BB->getInstList().erase(BBI++);
01151   }
01152 }
01153 
01154 /// changeToCall - Convert the specified invoke into a normal call.
01155 static void changeToCall(InvokeInst *II) {
01156   SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
01157   CallInst *NewCall = CallInst::Create(II->getCalledValue(), Args, "", II);
01158   NewCall->takeName(II);
01159   NewCall->setCallingConv(II->getCallingConv());
01160   NewCall->setAttributes(II->getAttributes());
01161   NewCall->setDebugLoc(II->getDebugLoc());
01162   II->replaceAllUsesWith(NewCall);
01163 
01164   // Follow the call by a branch to the normal destination.
01165   BranchInst::Create(II->getNormalDest(), II);
01166 
01167   // Update PHI nodes in the unwind destination
01168   II->getUnwindDest()->removePredecessor(II->getParent());
01169   II->eraseFromParent();
01170 }
01171 
01172 static bool markAliveBlocks(BasicBlock *BB,
01173                             SmallPtrSet<BasicBlock*, 128> &Reachable) {
01174 
01175   SmallVector<BasicBlock*, 128> Worklist;
01176   Worklist.push_back(BB);
01177   Reachable.insert(BB);
01178   bool Changed = false;
01179   do {
01180     BB = Worklist.pop_back_val();
01181 
01182     // Do a quick scan of the basic block, turning any obviously unreachable
01183     // instructions into LLVM unreachable insts.  The instruction combining pass
01184     // canonicalizes unreachable insts into stores to null or undef.
01185     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E;++BBI){
01186       if (CallInst *CI = dyn_cast<CallInst>(BBI)) {
01187         if (CI->doesNotReturn()) {
01188           // If we found a call to a no-return function, insert an unreachable
01189           // instruction after it.  Make sure there isn't *already* one there
01190           // though.
01191           ++BBI;
01192           if (!isa<UnreachableInst>(BBI)) {
01193             // Don't insert a call to llvm.trap right before the unreachable.
01194             changeToUnreachable(BBI, false);
01195             Changed = true;
01196           }
01197           break;
01198         }
01199       }
01200 
01201       // Store to undef and store to null are undefined and used to signal that
01202       // they should be changed to unreachable by passes that can't modify the
01203       // CFG.
01204       if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
01205         // Don't touch volatile stores.
01206         if (SI->isVolatile()) continue;
01207 
01208         Value *Ptr = SI->getOperand(1);
01209 
01210         if (isa<UndefValue>(Ptr) ||
01211             (isa<ConstantPointerNull>(Ptr) &&
01212              SI->getPointerAddressSpace() == 0)) {
01213           changeToUnreachable(SI, true);
01214           Changed = true;
01215           break;
01216         }
01217       }
01218     }
01219 
01220     // Turn invokes that call 'nounwind' functions into ordinary calls.
01221     if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
01222       Value *Callee = II->getCalledValue();
01223       if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
01224         changeToUnreachable(II, true);
01225         Changed = true;
01226       } else if (II->doesNotThrow()) {
01227         if (II->use_empty() && II->onlyReadsMemory()) {
01228           // jump to the normal destination branch.
01229           BranchInst::Create(II->getNormalDest(), II);
01230           II->getUnwindDest()->removePredecessor(II->getParent());
01231           II->eraseFromParent();
01232         } else
01233           changeToCall(II);
01234         Changed = true;
01235       }
01236     }
01237 
01238     Changed |= ConstantFoldTerminator(BB, true);
01239     for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
01240       if (Reachable.insert(*SI))
01241         Worklist.push_back(*SI);
01242   } while (!Worklist.empty());
01243   return Changed;
01244 }
01245 
01246 /// removeUnreachableBlocksFromFn - Remove blocks that are not reachable, even
01247 /// if they are in a dead cycle.  Return true if a change was made, false
01248 /// otherwise.
01249 bool llvm::removeUnreachableBlocks(Function &F) {
01250   SmallPtrSet<BasicBlock*, 128> Reachable;
01251   bool Changed = markAliveBlocks(F.begin(), Reachable);
01252 
01253   // If there are unreachable blocks in the CFG...
01254   if (Reachable.size() == F.size())
01255     return Changed;
01256 
01257   assert(Reachable.size() < F.size());
01258   NumRemoved += F.size()-Reachable.size();
01259 
01260   // Loop over all of the basic blocks that are not reachable, dropping all of
01261   // their internal references...
01262   for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB) {
01263     if (Reachable.count(BB))
01264       continue;
01265 
01266     for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
01267       if (Reachable.count(*SI))
01268         (*SI)->removePredecessor(BB);
01269     BB->dropAllReferences();
01270   }
01271 
01272   for (Function::iterator I = ++F.begin(); I != F.end();)
01273     if (!Reachable.count(I))
01274       I = F.getBasicBlockList().erase(I);
01275     else
01276       ++I;
01277 
01278   return true;
01279 }