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/Constants.h"
00017 #include "llvm/DerivedTypes.h"
00018 #include "llvm/Instructions.h"
00019 #include "llvm/Intrinsics.h"
00020 #include "llvm/IntrinsicInst.h"
00021 #include "llvm/Analysis/ConstantFolding.h"
00022 #include "llvm/Target/TargetData.h"
00023 #include "llvm/Support/GetElementPtrTypeIterator.h"
00024 #include "llvm/Support/MathExtras.h"
00025 using namespace llvm;
00026 
00027 //===----------------------------------------------------------------------===//
00028 //  Local constant propagation.
00029 //
00030 
00031 // ConstantFoldTerminator - If a terminator instruction is predicated on a
00032 // constant value, convert it into an unconditional branch to the constant
00033 // destination.
00034 //
00035 bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
00036   TerminatorInst *T = BB->getTerminator();
00037 
00038   // Branch - See if we are conditional jumping on constant
00039   if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
00040     if (BI->isUnconditional()) return false;  // Can't optimize uncond branch
00041     BasicBlock *Dest1 = BI->getSuccessor(0);
00042     BasicBlock *Dest2 = BI->getSuccessor(1);
00043 
00044     if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
00045       // Are we branching on constant?
00046       // YES.  Change to unconditional branch...
00047       BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
00048       BasicBlock *OldDest     = Cond->getZExtValue() ? Dest2 : Dest1;
00049 
00050       //cerr << "Function: " << T->getParent()->getParent()
00051       //     << "\nRemoving branch from " << T->getParent()
00052       //     << "\n\nTo: " << OldDest << endl;
00053 
00054       // Let the basic block know that we are letting go of it.  Based on this,
00055       // it will adjust it's PHI nodes.
00056       assert(BI->getParent() && "Terminator not inserted in block!");
00057       OldDest->removePredecessor(BI->getParent());
00058 
00059       // Set the unconditional destination, and change the insn to be an
00060       // unconditional branch.
00061       BI->setUnconditionalDest(Destination);
00062       return true;
00063     } else if (Dest2 == Dest1) {       // Conditional branch to same location?
00064       // This branch matches something like this:
00065       //     br bool %cond, label %Dest, label %Dest
00066       // and changes it into:  br label %Dest
00067 
00068       // Let the basic block know that we are letting go of one copy of it.
00069       assert(BI->getParent() && "Terminator not inserted in block!");
00070       Dest1->removePredecessor(BI->getParent());
00071 
00072       // Change a conditional branch to unconditional.
00073       BI->setUnconditionalDest(Dest1);
00074       return true;
00075     }
00076   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
00077     // If we are switching on a constant, we can convert the switch into a
00078     // single branch instruction!
00079     ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
00080     BasicBlock *TheOnlyDest = SI->getSuccessor(0);  // The default dest
00081     BasicBlock *DefaultDest = TheOnlyDest;
00082     assert(TheOnlyDest == SI->getDefaultDest() &&
00083            "Default destination is not successor #0?");
00084 
00085     // Figure out which case it goes to...
00086     for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
00087       // Found case matching a constant operand?
00088       if (SI->getSuccessorValue(i) == CI) {
00089         TheOnlyDest = SI->getSuccessor(i);
00090         break;
00091       }
00092 
00093       // Check to see if this branch is going to the same place as the default
00094       // dest.  If so, eliminate it as an explicit compare.
00095       if (SI->getSuccessor(i) == DefaultDest) {
00096         // Remove this entry...
00097         DefaultDest->removePredecessor(SI->getParent());
00098         SI->removeCase(i);
00099         --i; --e;  // Don't skip an entry...
00100         continue;
00101       }
00102 
00103       // Otherwise, check to see if the switch only branches to one destination.
00104       // We do this by reseting "TheOnlyDest" to null when we find two non-equal
00105       // destinations.
00106       if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
00107     }
00108 
00109     if (CI && !TheOnlyDest) {
00110       // Branching on a constant, but not any of the cases, go to the default
00111       // successor.
00112       TheOnlyDest = SI->getDefaultDest();
00113     }
00114 
00115     // If we found a single destination that we can fold the switch into, do so
00116     // now.
00117     if (TheOnlyDest) {
00118       // Insert the new branch..
00119       BranchInst::Create(TheOnlyDest, SI);
00120       BasicBlock *BB = SI->getParent();
00121 
00122       // Remove entries from PHI nodes which we no longer branch to...
00123       for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
00124         // Found case matching a constant operand?
00125         BasicBlock *Succ = SI->getSuccessor(i);
00126         if (Succ == TheOnlyDest)
00127           TheOnlyDest = 0;  // Don't modify the first branch to TheOnlyDest
00128         else
00129           Succ->removePredecessor(BB);
00130       }
00131 
00132       // Delete the old switch...
00133       BB->getInstList().erase(SI);
00134       return true;
00135     } else if (SI->getNumSuccessors() == 2) {
00136       // Otherwise, we can fold this switch into a conditional branch
00137       // instruction if it has only one non-default destination.
00138       Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, SI->getCondition(),
00139                                  SI->getSuccessorValue(1), "cond", SI);
00140       // Insert the new branch...
00141       BranchInst::Create(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
00142 
00143       // Delete the old switch...
00144       SI->eraseFromParent();
00145       return true;
00146     }
00147   }
00148   return false;
00149 }
00150 
00151 
00152 //===----------------------------------------------------------------------===//
00153 //  Local dead code elimination...
00154 //
00155 
00156 /// isInstructionTriviallyDead - Return true if the result produced by the
00157 /// instruction is not used, and the instruction has no side effects.
00158 ///
00159 bool llvm::isInstructionTriviallyDead(Instruction *I) {
00160   if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
00161 
00162   if (!I->mayWriteToMemory())
00163     return true;
00164 
00165   // Special case intrinsics that "may write to memory" but can be deleted when
00166   // dead.
00167   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
00168     // Safe to delete llvm.stacksave if dead.
00169     if (II->getIntrinsicID() == Intrinsic::stacksave)
00170       return true;
00171   
00172   return false;
00173 }
00174 
00175 /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
00176 /// trivially dead instruction, delete it.  If that makes any of its operands
00177 /// trivially dead, delete them too, recursively.
00178 ///
00179 /// If DeadInst is specified, the vector is filled with the instructions that
00180 /// are actually deleted.
00181 void llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V,
00182                                       SmallVectorImpl<Instruction*> *DeadInst) {
00183   Instruction *I = dyn_cast<Instruction>(V);
00184   if (!I || !I->use_empty() || !isInstructionTriviallyDead(I))
00185     return;
00186   
00187   SmallVector<Instruction*, 16> DeadInsts;
00188   DeadInsts.push_back(I);
00189   
00190   while (!DeadInsts.empty()) {
00191     I = DeadInsts.back();
00192     DeadInsts.pop_back();
00193 
00194     // If the client wanted to know, tell it about deleted instructions.
00195     if (DeadInst)
00196       DeadInst->push_back(I);
00197     
00198     // Null out all of the instruction's operands to see if any operand becomes
00199     // dead as we go.
00200     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
00201       Value *OpV = I->getOperand(i);
00202       I->setOperand(i, 0);
00203       
00204       if (!OpV->use_empty()) continue;
00205     
00206       // If the operand is an instruction that became dead as we nulled out the
00207       // operand, and if it is 'trivially' dead, delete it in a future loop
00208       // iteration.
00209       if (Instruction *OpI = dyn_cast<Instruction>(OpV))
00210         if (isInstructionTriviallyDead(OpI))
00211           DeadInsts.push_back(OpI);
00212     }
00213     
00214     I->eraseFromParent();
00215   }
00216 }
00217 
00218 
00219 //===----------------------------------------------------------------------===//
00220 //  Control Flow Graph Restructuring...
00221 //
00222 
00223 /// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
00224 /// predecessor is known to have one successor (DestBB!).  Eliminate the edge
00225 /// between them, moving the instructions in the predecessor into DestBB and
00226 /// deleting the predecessor block.
00227 ///
00228 void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB) {
00229   // If BB has single-entry PHI nodes, fold them.
00230   while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
00231     Value *NewVal = PN->getIncomingValue(0);
00232     // Replace self referencing PHI with undef, it must be dead.
00233     if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
00234     PN->replaceAllUsesWith(NewVal);
00235     PN->eraseFromParent();
00236   }
00237   
00238   BasicBlock *PredBB = DestBB->getSinglePredecessor();
00239   assert(PredBB && "Block doesn't have a single predecessor!");
00240   
00241   // Splice all the instructions from PredBB to DestBB.
00242   PredBB->getTerminator()->eraseFromParent();
00243   DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
00244   
00245   // Anything that branched to PredBB now branches to DestBB.
00246   PredBB->replaceAllUsesWith(DestBB);
00247   
00248   // Nuke BB.
00249   PredBB->eraseFromParent();
00250 }