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 = 0;
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 = 0;  // 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 = 0;
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, 0);
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 (P) {
00513     if (DominatorTreeWrapperPass *DTWP =
00514             P->getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
00515       DominatorTree &DT = DTWP->getDomTree();
00516       BasicBlock *PredBBIDom = DT.getNode(PredBB)->getIDom()->getBlock();
00517       DT.changeImmediateDominator(DestBB, PredBBIDom);
00518       DT.eraseNode(PredBB);
00519     }
00520   }
00521   // Nuke BB.
00522   PredBB->eraseFromParent();
00523 }
00524 
00525 /// CanMergeValues - Return true if we can choose one of these values to use
00526 /// in place of the other. Note that we will always choose the non-undef
00527 /// value to keep.
00528 static bool CanMergeValues(Value *First, Value *Second) {
00529   return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
00530 }
00531 
00532 /// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
00533 /// almost-empty BB ending in an unconditional branch to Succ, into Succ.
00534 ///
00535 /// Assumption: Succ is the single successor for BB.
00536 ///
00537 static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
00538   assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
00539 
00540   DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
00541         << Succ->getName() << "\n");
00542   // Shortcut, if there is only a single predecessor it must be BB and merging
00543   // is always safe
00544   if (Succ->getSinglePredecessor()) return true;
00545 
00546   // Make a list of the predecessors of BB
00547   SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
00548 
00549   // Look at all the phi nodes in Succ, to see if they present a conflict when
00550   // merging these blocks
00551   for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
00552     PHINode *PN = cast<PHINode>(I);
00553 
00554     // If the incoming value from BB is again a PHINode in
00555     // BB which has the same incoming value for *PI as PN does, we can
00556     // merge the phi nodes and then the blocks can still be merged
00557     PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
00558     if (BBPN && BBPN->getParent() == BB) {
00559       for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
00560         BasicBlock *IBB = PN->getIncomingBlock(PI);
00561         if (BBPreds.count(IBB) &&
00562             !CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
00563                             PN->getIncomingValue(PI))) {
00564           DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
00565                 << Succ->getName() << " is conflicting with "
00566                 << BBPN->getName() << " with regard to common predecessor "
00567                 << IBB->getName() << "\n");
00568           return false;
00569         }
00570       }
00571     } else {
00572       Value* Val = PN->getIncomingValueForBlock(BB);
00573       for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
00574         // See if the incoming value for the common predecessor is equal to the
00575         // one for BB, in which case this phi node will not prevent the merging
00576         // of the block.
00577         BasicBlock *IBB = PN->getIncomingBlock(PI);
00578         if (BBPreds.count(IBB) &&
00579             !CanMergeValues(Val, PN->getIncomingValue(PI))) {
00580           DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
00581                 << Succ->getName() << " is conflicting with regard to common "
00582                 << "predecessor " << IBB->getName() << "\n");
00583           return false;
00584         }
00585       }
00586     }
00587   }
00588 
00589   return true;
00590 }
00591 
00592 typedef SmallVector<BasicBlock *, 16> PredBlockVector;
00593 typedef DenseMap<BasicBlock *, Value *> IncomingValueMap;
00594 
00595 /// \brief Determines the value to use as the phi node input for a block.
00596 ///
00597 /// Select between \p OldVal any value that we know flows from \p BB
00598 /// to a particular phi on the basis of which one (if either) is not
00599 /// undef. Update IncomingValues based on the selected value.
00600 ///
00601 /// \param OldVal The value we are considering selecting.
00602 /// \param BB The block that the value flows in from.
00603 /// \param IncomingValues A map from block-to-value for other phi inputs
00604 /// that we have examined.
00605 ///
00606 /// \returns the selected value.
00607 static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
00608                                           IncomingValueMap &IncomingValues) {
00609   if (!isa<UndefValue>(OldVal)) {
00610     assert((!IncomingValues.count(BB) ||
00611             IncomingValues.find(BB)->second == OldVal) &&
00612            "Expected OldVal to match incoming value from BB!");
00613 
00614     IncomingValues.insert(std::make_pair(BB, OldVal));
00615     return OldVal;
00616   }
00617 
00618   IncomingValueMap::const_iterator It = IncomingValues.find(BB);
00619   if (It != IncomingValues.end()) return It->second;
00620 
00621   return OldVal;
00622 }
00623 
00624 /// \brief Create a map from block to value for the operands of a
00625 /// given phi.
00626 ///
00627 /// Create a map from block to value for each non-undef value flowing
00628 /// into \p PN.
00629 ///
00630 /// \param PN The phi we are collecting the map for.
00631 /// \param IncomingValues [out] The map from block to value for this phi.
00632 static void gatherIncomingValuesToPhi(PHINode *PN,
00633                                       IncomingValueMap &IncomingValues) {
00634   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00635     BasicBlock *BB = PN->getIncomingBlock(i);
00636     Value *V = PN->getIncomingValue(i);
00637 
00638     if (!isa<UndefValue>(V))
00639       IncomingValues.insert(std::make_pair(BB, V));
00640   }
00641 }
00642 
00643 /// \brief Replace the incoming undef values to a phi with the values
00644 /// from a block-to-value map.
00645 ///
00646 /// \param PN The phi we are replacing the undefs in.
00647 /// \param IncomingValues A map from block to value.
00648 static void replaceUndefValuesInPhi(PHINode *PN,
00649                                     const IncomingValueMap &IncomingValues) {
00650   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00651     Value *V = PN->getIncomingValue(i);
00652 
00653     if (!isa<UndefValue>(V)) continue;
00654 
00655     BasicBlock *BB = PN->getIncomingBlock(i);
00656     IncomingValueMap::const_iterator It = IncomingValues.find(BB);
00657     if (It == IncomingValues.end()) continue;
00658 
00659     PN->setIncomingValue(i, It->second);
00660   }
00661 }
00662 
00663 /// \brief Replace a value flowing from a block to a phi with
00664 /// potentially multiple instances of that value flowing from the
00665 /// block's predecessors to the phi.
00666 ///
00667 /// \param BB The block with the value flowing into the phi.
00668 /// \param BBPreds The predecessors of BB.
00669 /// \param PN The phi that we are updating.
00670 static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
00671                                                 const PredBlockVector &BBPreds,
00672                                                 PHINode *PN) {
00673   Value *OldVal = PN->removeIncomingValue(BB, false);
00674   assert(OldVal && "No entry in PHI for Pred BB!");
00675 
00676   IncomingValueMap IncomingValues;
00677 
00678   // We are merging two blocks - BB, and the block containing PN - and
00679   // as a result we need to redirect edges from the predecessors of BB
00680   // to go to the block containing PN, and update PN
00681   // accordingly. Since we allow merging blocks in the case where the
00682   // predecessor and successor blocks both share some predecessors,
00683   // and where some of those common predecessors might have undef
00684   // values flowing into PN, we want to rewrite those values to be
00685   // consistent with the non-undef values.
00686 
00687   gatherIncomingValuesToPhi(PN, IncomingValues);
00688 
00689   // If this incoming value is one of the PHI nodes in BB, the new entries
00690   // in the PHI node are the entries from the old PHI.
00691   if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
00692     PHINode *OldValPN = cast<PHINode>(OldVal);
00693     for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
00694       // Note that, since we are merging phi nodes and BB and Succ might
00695       // have common predecessors, we could end up with a phi node with
00696       // identical incoming branches. This will be cleaned up later (and
00697       // will trigger asserts if we try to clean it up now, without also
00698       // simplifying the corresponding conditional branch).
00699       BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
00700       Value *PredVal = OldValPN->getIncomingValue(i);
00701       Value *Selected = selectIncomingValueForBlock(PredVal, PredBB,
00702                                                     IncomingValues);
00703 
00704       // And add a new incoming value for this predecessor for the
00705       // newly retargeted branch.
00706       PN->addIncoming(Selected, PredBB);
00707     }
00708   } else {
00709     for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) {
00710       // Update existing incoming values in PN for this
00711       // predecessor of BB.
00712       BasicBlock *PredBB = BBPreds[i];
00713       Value *Selected = selectIncomingValueForBlock(OldVal, PredBB,
00714                                                     IncomingValues);
00715 
00716       // And add a new incoming value for this predecessor for the
00717       // newly retargeted branch.
00718       PN->addIncoming(Selected, PredBB);
00719     }
00720   }
00721 
00722   replaceUndefValuesInPhi(PN, IncomingValues);
00723 }
00724 
00725 /// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
00726 /// unconditional branch, and contains no instructions other than PHI nodes,
00727 /// potential side-effect free intrinsics and the branch.  If possible,
00728 /// eliminate BB by rewriting all the predecessors to branch to the successor
00729 /// block and return true.  If we can't transform, return false.
00730 bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) {
00731   assert(BB != &BB->getParent()->getEntryBlock() &&
00732          "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
00733 
00734   // We can't eliminate infinite loops.
00735   BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
00736   if (BB == Succ) return false;
00737 
00738   // Check to see if merging these blocks would cause conflicts for any of the
00739   // phi nodes in BB or Succ. If not, we can safely merge.
00740   if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
00741 
00742   // Check for cases where Succ has multiple predecessors and a PHI node in BB
00743   // has uses which will not disappear when the PHI nodes are merged.  It is
00744   // possible to handle such cases, but difficult: it requires checking whether
00745   // BB dominates Succ, which is non-trivial to calculate in the case where
00746   // Succ has multiple predecessors.  Also, it requires checking whether
00747   // constructing the necessary self-referential PHI node doesn't introduce any
00748   // conflicts; this isn't too difficult, but the previous code for doing this
00749   // was incorrect.
00750   //
00751   // Note that if this check finds a live use, BB dominates Succ, so BB is
00752   // something like a loop pre-header (or rarely, a part of an irreducible CFG);
00753   // folding the branch isn't profitable in that case anyway.
00754   if (!Succ->getSinglePredecessor()) {
00755     BasicBlock::iterator BBI = BB->begin();
00756     while (isa<PHINode>(*BBI)) {
00757       for (Use &U : BBI->uses()) {
00758         if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
00759           if (PN->getIncomingBlock(U) != BB)
00760             return false;
00761         } else {
00762           return false;
00763         }
00764       }
00765       ++BBI;
00766     }
00767   }
00768 
00769   DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
00770 
00771   if (isa<PHINode>(Succ->begin())) {
00772     // If there is more than one pred of succ, and there are PHI nodes in
00773     // the successor, then we need to add incoming edges for the PHI nodes
00774     //
00775     const PredBlockVector BBPreds(pred_begin(BB), pred_end(BB));
00776 
00777     // Loop over all of the PHI nodes in the successor of BB.
00778     for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
00779       PHINode *PN = cast<PHINode>(I);
00780 
00781       redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN);
00782     }
00783   }
00784 
00785   if (Succ->getSinglePredecessor()) {
00786     // BB is the only predecessor of Succ, so Succ will end up with exactly
00787     // the same predecessors BB had.
00788 
00789     // Copy over any phi, debug or lifetime instruction.
00790     BB->getTerminator()->eraseFromParent();
00791     Succ->getInstList().splice(Succ->getFirstNonPHI(), BB->getInstList());
00792   } else {
00793     while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
00794       // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
00795       assert(PN->use_empty() && "There shouldn't be any uses here!");
00796       PN->eraseFromParent();
00797     }
00798   }
00799 
00800   // Everything that jumped to BB now goes to Succ.
00801   BB->replaceAllUsesWith(Succ);
00802   if (!Succ->hasName()) Succ->takeName(BB);
00803   BB->eraseFromParent();              // Delete the old basic block.
00804   return true;
00805 }
00806 
00807 /// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
00808 /// nodes in this block. This doesn't try to be clever about PHI nodes
00809 /// which differ only in the order of the incoming values, but instcombine
00810 /// orders them so it usually won't matter.
00811 ///
00812 bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
00813   bool Changed = false;
00814 
00815   // This implementation doesn't currently consider undef operands
00816   // specially. Theoretically, two phis which are identical except for
00817   // one having an undef where the other doesn't could be collapsed.
00818 
00819   // Map from PHI hash values to PHI nodes. If multiple PHIs have
00820   // the same hash value, the element is the first PHI in the
00821   // linked list in CollisionMap.
00822   DenseMap<uintptr_t, PHINode *> HashMap;
00823 
00824   // Maintain linked lists of PHI nodes with common hash values.
00825   DenseMap<PHINode *, PHINode *> CollisionMap;
00826 
00827   // Examine each PHI.
00828   for (BasicBlock::iterator I = BB->begin();
00829        PHINode *PN = dyn_cast<PHINode>(I++); ) {
00830     // Compute a hash value on the operands. Instcombine will likely have sorted
00831     // them, which helps expose duplicates, but we have to check all the
00832     // operands to be safe in case instcombine hasn't run.
00833     uintptr_t Hash = 0;
00834     // This hash algorithm is quite weak as hash functions go, but it seems
00835     // to do a good enough job for this particular purpose, and is very quick.
00836     for (User::op_iterator I = PN->op_begin(), E = PN->op_end(); I != E; ++I) {
00837       Hash ^= reinterpret_cast<uintptr_t>(static_cast<Value *>(*I));
00838       Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
00839     }
00840     for (PHINode::block_iterator I = PN->block_begin(), E = PN->block_end();
00841          I != E; ++I) {
00842       Hash ^= reinterpret_cast<uintptr_t>(static_cast<BasicBlock *>(*I));
00843       Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
00844     }
00845     // Avoid colliding with the DenseMap sentinels ~0 and ~0-1.
00846     Hash >>= 1;
00847     // If we've never seen this hash value before, it's a unique PHI.
00848     std::pair<DenseMap<uintptr_t, PHINode *>::iterator, bool> Pair =
00849       HashMap.insert(std::make_pair(Hash, PN));
00850     if (Pair.second) continue;
00851     // Otherwise it's either a duplicate or a hash collision.
00852     for (PHINode *OtherPN = Pair.first->second; ; ) {
00853       if (OtherPN->isIdenticalTo(PN)) {
00854         // A duplicate. Replace this PHI with its duplicate.
00855         PN->replaceAllUsesWith(OtherPN);
00856         PN->eraseFromParent();
00857         Changed = true;
00858         break;
00859       }
00860       // A non-duplicate hash collision.
00861       DenseMap<PHINode *, PHINode *>::iterator I = CollisionMap.find(OtherPN);
00862       if (I == CollisionMap.end()) {
00863         // Set this PHI to be the head of the linked list of colliding PHIs.
00864         PHINode *Old = Pair.first->second;
00865         Pair.first->second = PN;
00866         CollisionMap[PN] = Old;
00867         break;
00868       }
00869       // Proceed to the next PHI in the list.
00870       OtherPN = I->second;
00871     }
00872   }
00873 
00874   return Changed;
00875 }
00876 
00877 /// enforceKnownAlignment - If the specified pointer points to an object that
00878 /// we control, modify the object's alignment to PrefAlign. This isn't
00879 /// often possible though. If alignment is important, a more reliable approach
00880 /// is to simply align all global variables and allocation instructions to
00881 /// their preferred alignment from the beginning.
00882 ///
00883 static unsigned enforceKnownAlignment(Value *V, unsigned Align,
00884                                       unsigned PrefAlign, const DataLayout *TD) {
00885   V = V->stripPointerCasts();
00886 
00887   if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
00888     // If the preferred alignment is greater than the natural stack alignment
00889     // then don't round up. This avoids dynamic stack realignment.
00890     if (TD && TD->exceedsNaturalStackAlignment(PrefAlign))
00891       return Align;
00892     // If there is a requested alignment and if this is an alloca, round up.
00893     if (AI->getAlignment() >= PrefAlign)
00894       return AI->getAlignment();
00895     AI->setAlignment(PrefAlign);
00896     return PrefAlign;
00897   }
00898 
00899   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
00900     // If there is a large requested alignment and we can, bump up the alignment
00901     // of the global.
00902     if (GV->isDeclaration()) return Align;
00903     // If the memory we set aside for the global may not be the memory used by
00904     // the final program then it is impossible for us to reliably enforce the
00905     // preferred alignment.
00906     if (GV->isWeakForLinker()) return Align;
00907 
00908     if (GV->getAlignment() >= PrefAlign)
00909       return GV->getAlignment();
00910     // We can only increase the alignment of the global if it has no alignment
00911     // specified or if it is not assigned a section.  If it is assigned a
00912     // section, the global could be densely packed with other objects in the
00913     // section, increasing the alignment could cause padding issues.
00914     if (!GV->hasSection() || GV->getAlignment() == 0)
00915       GV->setAlignment(PrefAlign);
00916     return GV->getAlignment();
00917   }
00918 
00919   return Align;
00920 }
00921 
00922 /// getOrEnforceKnownAlignment - If the specified pointer has an alignment that
00923 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
00924 /// and it is more than the alignment of the ultimate object, see if we can
00925 /// increase the alignment of the ultimate object, making this check succeed.
00926 unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
00927                                           const DataLayout *DL) {
00928   assert(V->getType()->isPointerTy() &&
00929          "getOrEnforceKnownAlignment expects a pointer!");
00930   unsigned BitWidth = DL ? DL->getPointerTypeSizeInBits(V->getType()) : 64;
00931 
00932   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
00933   ComputeMaskedBits(V, KnownZero, KnownOne, DL);
00934   unsigned TrailZ = KnownZero.countTrailingOnes();
00935 
00936   // Avoid trouble with ridiculously large TrailZ values, such as
00937   // those computed from a null pointer.
00938   TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
00939 
00940   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
00941 
00942   // LLVM doesn't support alignments larger than this currently.
00943   Align = std::min(Align, +Value::MaximumAlignment);
00944 
00945   if (PrefAlign > Align)
00946     Align = enforceKnownAlignment(V, Align, PrefAlign, DL);
00947 
00948   // We don't need to make any adjustment.
00949   return Align;
00950 }
00951 
00952 ///===---------------------------------------------------------------------===//
00953 ///  Dbg Intrinsic utilities
00954 ///
00955 
00956 /// See if there is a dbg.value intrinsic for DIVar before I.
00957 static bool LdStHasDebugValue(DIVariable &DIVar, Instruction *I) {
00958   // Since we can't guarantee that the original dbg.declare instrinsic
00959   // is removed by LowerDbgDeclare(), we need to make sure that we are
00960   // not inserting the same dbg.value intrinsic over and over.
00961   llvm::BasicBlock::InstListType::iterator PrevI(I);
00962   if (PrevI != I->getParent()->getInstList().begin()) {
00963     --PrevI;
00964     if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(PrevI))
00965       if (DVI->getValue() == I->getOperand(0) &&
00966           DVI->getOffset() == 0 &&
00967           DVI->getVariable() == DIVar)
00968         return true;
00969   }
00970   return false;
00971 }
00972 
00973 /// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
00974 /// that has an associated llvm.dbg.decl intrinsic.
00975 bool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
00976                                            StoreInst *SI, DIBuilder &Builder) {
00977   DIVariable DIVar(DDI->getVariable());
00978   assert((!DIVar || DIVar.isVariable()) &&
00979          "Variable in DbgDeclareInst should be either null or a DIVariable.");
00980   if (!DIVar)
00981     return false;
00982 
00983   if (LdStHasDebugValue(DIVar, SI))
00984     return true;
00985 
00986   Instruction *DbgVal = NULL;
00987   // If an argument is zero extended then use argument directly. The ZExt
00988   // may be zapped by an optimization pass in future.
00989   Argument *ExtendedArg = NULL;
00990   if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
00991     ExtendedArg = dyn_cast<Argument>(ZExt->getOperand(0));
00992   if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
00993     ExtendedArg = dyn_cast<Argument>(SExt->getOperand(0));
00994   if (ExtendedArg)
00995     DbgVal = Builder.insertDbgValueIntrinsic(ExtendedArg, 0, DIVar, SI);
00996   else
00997     DbgVal = Builder.insertDbgValueIntrinsic(SI->getOperand(0), 0, DIVar, SI);
00998 
00999   // Propagate any debug metadata from the store onto the dbg.value.
01000   DebugLoc SIDL = SI->getDebugLoc();
01001   if (!SIDL.isUnknown())
01002     DbgVal->setDebugLoc(SIDL);
01003   // Otherwise propagate debug metadata from dbg.declare.
01004   else
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 
01026   // Propagate any debug metadata from the store onto the dbg.value.
01027   DebugLoc LIDL = LI->getDebugLoc();
01028   if (!LIDL.isUnknown())
01029     DbgVal->setDebugLoc(LIDL);
01030   // Otherwise propagate debug metadata from dbg.declare.
01031   else
01032     DbgVal->setDebugLoc(DDI->getDebugLoc());
01033   return true;
01034 }
01035 
01036 /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
01037 /// of llvm.dbg.value intrinsics.
01038 bool llvm::LowerDbgDeclare(Function &F) {
01039   DIBuilder DIB(*F.getParent());
01040   SmallVector<DbgDeclareInst *, 4> Dbgs;
01041   for (auto &FI : F)
01042     for (BasicBlock::iterator BI : FI)
01043       if (auto DDI = dyn_cast<DbgDeclareInst>(BI))
01044         Dbgs.push_back(DDI);
01045 
01046   if (Dbgs.empty())
01047     return false;
01048 
01049   for (auto &I : Dbgs) {
01050     DbgDeclareInst *DDI = I;
01051     AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
01052     // If this is an alloca for a scalar variable, insert a dbg.value
01053     // at each load and store to the alloca and erase the dbg.declare.
01054     if (AI && !AI->isArrayAllocation()) {
01055 
01056       // We only remove the dbg.declare intrinsic if all uses are
01057       // converted to dbg.value intrinsics.
01058       bool RemoveDDI = true;
01059       for (User *U : AI->users())
01060         if (StoreInst *SI = dyn_cast<StoreInst>(U))
01061           ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
01062         else if (LoadInst *LI = dyn_cast<LoadInst>(U))
01063           ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
01064         else
01065           RemoveDDI = false;
01066       if (RemoveDDI)
01067         DDI->eraseFromParent();
01068     }
01069   }
01070   return true;
01071 }
01072 
01073 /// FindAllocaDbgDeclare - Finds the llvm.dbg.declare intrinsic describing the
01074 /// alloca 'V', if any.
01075 DbgDeclareInst *llvm::FindAllocaDbgDeclare(Value *V) {
01076   if (MDNode *DebugNode = MDNode::getIfExists(V->getContext(), V))
01077     for (User *U : DebugNode->users())
01078       if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
01079         return DDI;
01080 
01081   return 0;
01082 }
01083 
01084 bool llvm::replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
01085                                       DIBuilder &Builder) {
01086   DbgDeclareInst *DDI = FindAllocaDbgDeclare(AI);
01087   if (!DDI)
01088     return false;
01089   DIVariable DIVar(DDI->getVariable());
01090   assert((!DIVar || DIVar.isVariable()) &&
01091          "Variable in DbgDeclareInst should be either null or a DIVariable.");
01092   if (!DIVar)
01093     return false;
01094 
01095   // Create a copy of the original DIDescriptor for user variable, appending
01096   // "deref" operation to a list of address elements, as new llvm.dbg.declare
01097   // will take a value storing address of the memory for variable, not
01098   // alloca itself.
01099   Type *Int64Ty = Type::getInt64Ty(AI->getContext());
01100   SmallVector<Value*, 4> NewDIVarAddress;
01101   if (DIVar.hasComplexAddress()) {
01102     for (unsigned i = 0, n = DIVar.getNumAddrElements(); i < n; ++i) {
01103       NewDIVarAddress.push_back(
01104           ConstantInt::get(Int64Ty, DIVar.getAddrElement(i)));
01105     }
01106   }
01107   NewDIVarAddress.push_back(ConstantInt::get(Int64Ty, DIBuilder::OpDeref));
01108   DIVariable NewDIVar = Builder.createComplexVariable(
01109       DIVar.getTag(), DIVar.getContext(), DIVar.getName(),
01110       DIVar.getFile(), DIVar.getLineNumber(), DIVar.getType(),
01111       NewDIVarAddress, DIVar.getArgNumber());
01112 
01113   // Insert llvm.dbg.declare in the same basic block as the original alloca,
01114   // and remove old llvm.dbg.declare.
01115   BasicBlock *BB = AI->getParent();
01116   Builder.insertDeclare(NewAllocaAddress, NewDIVar, BB);
01117   DDI->eraseFromParent();
01118   return true;
01119 }
01120 
01121 /// changeToUnreachable - Insert an unreachable instruction before the specified
01122 /// instruction, making it and the rest of the code in the block dead.
01123 static void changeToUnreachable(Instruction *I, bool UseLLVMTrap) {
01124   BasicBlock *BB = I->getParent();
01125   // Loop over all of the successors, removing BB's entry from any PHI
01126   // nodes.
01127   for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
01128     (*SI)->removePredecessor(BB);
01129 
01130   // Insert a call to llvm.trap right before this.  This turns the undefined
01131   // behavior into a hard fail instead of falling through into random code.
01132   if (UseLLVMTrap) {
01133     Function *TrapFn =
01134       Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap);
01135     CallInst *CallTrap = CallInst::Create(TrapFn, "", I);
01136     CallTrap->setDebugLoc(I->getDebugLoc());
01137   }
01138   new UnreachableInst(I->getContext(), I);
01139 
01140   // All instructions after this are dead.
01141   BasicBlock::iterator BBI = I, BBE = BB->end();
01142   while (BBI != BBE) {
01143     if (!BBI->use_empty())
01144       BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
01145     BB->getInstList().erase(BBI++);
01146   }
01147 }
01148 
01149 /// changeToCall - Convert the specified invoke into a normal call.
01150 static void changeToCall(InvokeInst *II) {
01151   SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
01152   CallInst *NewCall = CallInst::Create(II->getCalledValue(), Args, "", II);
01153   NewCall->takeName(II);
01154   NewCall->setCallingConv(II->getCallingConv());
01155   NewCall->setAttributes(II->getAttributes());
01156   NewCall->setDebugLoc(II->getDebugLoc());
01157   II->replaceAllUsesWith(NewCall);
01158 
01159   // Follow the call by a branch to the normal destination.
01160   BranchInst::Create(II->getNormalDest(), II);
01161 
01162   // Update PHI nodes in the unwind destination
01163   II->getUnwindDest()->removePredecessor(II->getParent());
01164   II->eraseFromParent();
01165 }
01166 
01167 static bool markAliveBlocks(BasicBlock *BB,
01168                             SmallPtrSet<BasicBlock*, 128> &Reachable) {
01169 
01170   SmallVector<BasicBlock*, 128> Worklist;
01171   Worklist.push_back(BB);
01172   Reachable.insert(BB);
01173   bool Changed = false;
01174   do {
01175     BB = Worklist.pop_back_val();
01176 
01177     // Do a quick scan of the basic block, turning any obviously unreachable
01178     // instructions into LLVM unreachable insts.  The instruction combining pass
01179     // canonicalizes unreachable insts into stores to null or undef.
01180     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E;++BBI){
01181       if (CallInst *CI = dyn_cast<CallInst>(BBI)) {
01182         if (CI->doesNotReturn()) {
01183           // If we found a call to a no-return function, insert an unreachable
01184           // instruction after it.  Make sure there isn't *already* one there
01185           // though.
01186           ++BBI;
01187           if (!isa<UnreachableInst>(BBI)) {
01188             // Don't insert a call to llvm.trap right before the unreachable.
01189             changeToUnreachable(BBI, false);
01190             Changed = true;
01191           }
01192           break;
01193         }
01194       }
01195 
01196       // Store to undef and store to null are undefined and used to signal that
01197       // they should be changed to unreachable by passes that can't modify the
01198       // CFG.
01199       if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
01200         // Don't touch volatile stores.
01201         if (SI->isVolatile()) continue;
01202 
01203         Value *Ptr = SI->getOperand(1);
01204 
01205         if (isa<UndefValue>(Ptr) ||
01206             (isa<ConstantPointerNull>(Ptr) &&
01207              SI->getPointerAddressSpace() == 0)) {
01208           changeToUnreachable(SI, true);
01209           Changed = true;
01210           break;
01211         }
01212       }
01213     }
01214 
01215     // Turn invokes that call 'nounwind' functions into ordinary calls.
01216     if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
01217       Value *Callee = II->getCalledValue();
01218       if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
01219         changeToUnreachable(II, true);
01220         Changed = true;
01221       } else if (II->doesNotThrow()) {
01222         if (II->use_empty() && II->onlyReadsMemory()) {
01223           // jump to the normal destination branch.
01224           BranchInst::Create(II->getNormalDest(), II);
01225           II->getUnwindDest()->removePredecessor(II->getParent());
01226           II->eraseFromParent();
01227         } else
01228           changeToCall(II);
01229         Changed = true;
01230       }
01231     }
01232 
01233     Changed |= ConstantFoldTerminator(BB, true);
01234     for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
01235       if (Reachable.insert(*SI))
01236         Worklist.push_back(*SI);
01237   } while (!Worklist.empty());
01238   return Changed;
01239 }
01240 
01241 /// removeUnreachableBlocksFromFn - Remove blocks that are not reachable, even
01242 /// if they are in a dead cycle.  Return true if a change was made, false
01243 /// otherwise.
01244 bool llvm::removeUnreachableBlocks(Function &F) {
01245   SmallPtrSet<BasicBlock*, 128> Reachable;
01246   bool Changed = markAliveBlocks(F.begin(), Reachable);
01247 
01248   // If there are unreachable blocks in the CFG...
01249   if (Reachable.size() == F.size())
01250     return Changed;
01251 
01252   assert(Reachable.size() < F.size());
01253   NumRemoved += F.size()-Reachable.size();
01254 
01255   // Loop over all of the basic blocks that are not reachable, dropping all of
01256   // their internal references...
01257   for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB) {
01258     if (Reachable.count(BB))
01259       continue;
01260 
01261     for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
01262       if (Reachable.count(*SI))
01263         (*SI)->removePredecessor(BB);
01264     BB->dropAllReferences();
01265   }
01266 
01267   for (Function::iterator I = ++F.begin(); I != F.end();)
01268     if (!Reachable.count(I))
01269       I = F.getBasicBlockList().erase(I);
01270     else
01271       ++I;
01272 
01273   return true;
01274 }