LLVM API Documentation

SparsePropagation.cpp
Go to the documentation of this file.
00001 //===- SparsePropagation.cpp - Sparse Conditional Property Propagation ----===//
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 file implements an abstract sparse conditional propagation algorithm,
00011 // modeled after SCCP, but with a customizable lattice function.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/Analysis/SparsePropagation.h"
00016 #include "llvm/IR/Constants.h"
00017 #include "llvm/IR/Function.h"
00018 #include "llvm/IR/Instructions.h"
00019 #include "llvm/Support/Debug.h"
00020 #include "llvm/Support/raw_ostream.h"
00021 using namespace llvm;
00022 
00023 #define DEBUG_TYPE "sparseprop"
00024 
00025 //===----------------------------------------------------------------------===//
00026 //                  AbstractLatticeFunction Implementation
00027 //===----------------------------------------------------------------------===//
00028 
00029 AbstractLatticeFunction::~AbstractLatticeFunction() {}
00030 
00031 /// PrintValue - Render the specified lattice value to the specified stream.
00032 void AbstractLatticeFunction::PrintValue(LatticeVal V, raw_ostream &OS) {
00033   if (V == UndefVal)
00034     OS << "undefined";
00035   else if (V == OverdefinedVal)
00036     OS << "overdefined";
00037   else if (V == UntrackedVal)
00038     OS << "untracked";
00039   else
00040     OS << "unknown lattice value";
00041 }
00042 
00043 //===----------------------------------------------------------------------===//
00044 //                          SparseSolver Implementation
00045 //===----------------------------------------------------------------------===//
00046 
00047 /// getOrInitValueState - Return the LatticeVal object that corresponds to the
00048 /// value, initializing the value's state if it hasn't been entered into the
00049 /// map yet.   This function is necessary because not all values should start
00050 /// out in the underdefined state... Arguments should be overdefined, and
00051 /// constants should be marked as constants.
00052 ///
00053 SparseSolver::LatticeVal SparseSolver::getOrInitValueState(Value *V) {
00054   DenseMap<Value*, LatticeVal>::iterator I = ValueState.find(V);
00055   if (I != ValueState.end()) return I->second;  // Common case, in the map
00056   
00057   LatticeVal LV;
00058   if (LatticeFunc->IsUntrackedValue(V))
00059     return LatticeFunc->getUntrackedVal();
00060   else if (Constant *C = dyn_cast<Constant>(V))
00061     LV = LatticeFunc->ComputeConstant(C);
00062   else if (Argument *A = dyn_cast<Argument>(V))
00063     LV = LatticeFunc->ComputeArgument(A);
00064   else if (!isa<Instruction>(V))
00065     // All other non-instructions are overdefined.
00066     LV = LatticeFunc->getOverdefinedVal();
00067   else
00068     // All instructions are underdefined by default.
00069     LV = LatticeFunc->getUndefVal();
00070   
00071   // If this value is untracked, don't add it to the map.
00072   if (LV == LatticeFunc->getUntrackedVal())
00073     return LV;
00074   return ValueState[V] = LV;
00075 }
00076 
00077 /// UpdateState - When the state for some instruction is potentially updated,
00078 /// this function notices and adds I to the worklist if needed.
00079 void SparseSolver::UpdateState(Instruction &Inst, LatticeVal V) {
00080   DenseMap<Value*, LatticeVal>::iterator I = ValueState.find(&Inst);
00081   if (I != ValueState.end() && I->second == V)
00082     return;  // No change.
00083   
00084   // An update.  Visit uses of I.
00085   ValueState[&Inst] = V;
00086   InstWorkList.push_back(&Inst);
00087 }
00088 
00089 /// MarkBlockExecutable - This method can be used by clients to mark all of
00090 /// the blocks that are known to be intrinsically live in the processed unit.
00091 void SparseSolver::MarkBlockExecutable(BasicBlock *BB) {
00092   DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << "\n");
00093   BBExecutable.insert(BB);   // Basic block is executable!
00094   BBWorkList.push_back(BB);  // Add the block to the work list!
00095 }
00096 
00097 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
00098 /// work list if it is not already executable...
00099 void SparseSolver::markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
00100   if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
00101     return;  // This edge is already known to be executable!
00102   
00103   DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
00104         << " -> " << Dest->getName() << "\n");
00105 
00106   if (BBExecutable.count(Dest)) {
00107     // The destination is already executable, but we just made an edge
00108     // feasible that wasn't before.  Revisit the PHI nodes in the block
00109     // because they have potentially new operands.
00110     for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
00111       visitPHINode(*cast<PHINode>(I));
00112     
00113   } else {
00114     MarkBlockExecutable(Dest);
00115   }
00116 }
00117 
00118 
00119 /// getFeasibleSuccessors - Return a vector of booleans to indicate which
00120 /// successors are reachable from a given terminator instruction.
00121 void SparseSolver::getFeasibleSuccessors(TerminatorInst &TI,
00122                                          SmallVectorImpl<bool> &Succs,
00123                                          bool AggressiveUndef) {
00124   Succs.resize(TI.getNumSuccessors());
00125   if (TI.getNumSuccessors() == 0) return;
00126   
00127   if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
00128     if (BI->isUnconditional()) {
00129       Succs[0] = true;
00130       return;
00131     }
00132     
00133     LatticeVal BCValue;
00134     if (AggressiveUndef)
00135       BCValue = getOrInitValueState(BI->getCondition());
00136     else
00137       BCValue = getLatticeState(BI->getCondition());
00138     
00139     if (BCValue == LatticeFunc->getOverdefinedVal() ||
00140         BCValue == LatticeFunc->getUntrackedVal()) {
00141       // Overdefined condition variables can branch either way.
00142       Succs[0] = Succs[1] = true;
00143       return;
00144     }
00145 
00146     // If undefined, neither is feasible yet.
00147     if (BCValue == LatticeFunc->getUndefVal())
00148       return;
00149 
00150     Constant *C = LatticeFunc->GetConstant(BCValue, BI->getCondition(), *this);
00151     if (!C || !isa<ConstantInt>(C)) {
00152       // Non-constant values can go either way.
00153       Succs[0] = Succs[1] = true;
00154       return;
00155     }
00156 
00157     // Constant condition variables mean the branch can only go a single way
00158     Succs[C->isNullValue()] = true;
00159     return;
00160   }
00161   
00162   if (isa<InvokeInst>(TI)) {
00163     // Invoke instructions successors are always executable.
00164     // TODO: Could ask the lattice function if the value can throw.
00165     Succs[0] = Succs[1] = true;
00166     return;
00167   }
00168   
00169   if (isa<IndirectBrInst>(TI)) {
00170     Succs.assign(Succs.size(), true);
00171     return;
00172   }
00173   
00174   SwitchInst &SI = cast<SwitchInst>(TI);
00175   LatticeVal SCValue;
00176   if (AggressiveUndef)
00177     SCValue = getOrInitValueState(SI.getCondition());
00178   else
00179     SCValue = getLatticeState(SI.getCondition());
00180   
00181   if (SCValue == LatticeFunc->getOverdefinedVal() ||
00182       SCValue == LatticeFunc->getUntrackedVal()) {
00183     // All destinations are executable!
00184     Succs.assign(TI.getNumSuccessors(), true);
00185     return;
00186   }
00187   
00188   // If undefined, neither is feasible yet.
00189   if (SCValue == LatticeFunc->getUndefVal())
00190     return;
00191   
00192   Constant *C = LatticeFunc->GetConstant(SCValue, SI.getCondition(), *this);
00193   if (!C || !isa<ConstantInt>(C)) {
00194     // All destinations are executable!
00195     Succs.assign(TI.getNumSuccessors(), true);
00196     return;
00197   }
00198   SwitchInst::CaseIt Case = SI.findCaseValue(cast<ConstantInt>(C));
00199   Succs[Case.getSuccessorIndex()] = true;
00200 }
00201 
00202 
00203 /// isEdgeFeasible - Return true if the control flow edge from the 'From'
00204 /// basic block to the 'To' basic block is currently feasible...
00205 bool SparseSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To,
00206                                   bool AggressiveUndef) {
00207   SmallVector<bool, 16> SuccFeasible;
00208   TerminatorInst *TI = From->getTerminator();
00209   getFeasibleSuccessors(*TI, SuccFeasible, AggressiveUndef);
00210   
00211   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
00212     if (TI->getSuccessor(i) == To && SuccFeasible[i])
00213       return true;
00214   
00215   return false;
00216 }
00217 
00218 void SparseSolver::visitTerminatorInst(TerminatorInst &TI) {
00219   SmallVector<bool, 16> SuccFeasible;
00220   getFeasibleSuccessors(TI, SuccFeasible, true);
00221   
00222   BasicBlock *BB = TI.getParent();
00223   
00224   // Mark all feasible successors executable...
00225   for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
00226     if (SuccFeasible[i])
00227       markEdgeExecutable(BB, TI.getSuccessor(i));
00228 }
00229 
00230 void SparseSolver::visitPHINode(PHINode &PN) {
00231   // The lattice function may store more information on a PHINode than could be
00232   // computed from its incoming values.  For example, SSI form stores its sigma
00233   // functions as PHINodes with a single incoming value.
00234   if (LatticeFunc->IsSpecialCasedPHI(&PN)) {
00235     LatticeVal IV = LatticeFunc->ComputeInstructionState(PN, *this);
00236     if (IV != LatticeFunc->getUntrackedVal())
00237       UpdateState(PN, IV);
00238     return;
00239   }
00240 
00241   LatticeVal PNIV = getOrInitValueState(&PN);
00242   LatticeVal Overdefined = LatticeFunc->getOverdefinedVal();
00243   
00244   // If this value is already overdefined (common) just return.
00245   if (PNIV == Overdefined || PNIV == LatticeFunc->getUntrackedVal())
00246     return;  // Quick exit
00247   
00248   // Super-extra-high-degree PHI nodes are unlikely to ever be interesting,
00249   // and slow us down a lot.  Just mark them overdefined.
00250   if (PN.getNumIncomingValues() > 64) {
00251     UpdateState(PN, Overdefined);
00252     return;
00253   }
00254   
00255   // Look at all of the executable operands of the PHI node.  If any of them
00256   // are overdefined, the PHI becomes overdefined as well.  Otherwise, ask the
00257   // transfer function to give us the merge of the incoming values.
00258   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
00259     // If the edge is not yet known to be feasible, it doesn't impact the PHI.
00260     if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent(), true))
00261       continue;
00262     
00263     // Merge in this value.
00264     LatticeVal OpVal = getOrInitValueState(PN.getIncomingValue(i));
00265     if (OpVal != PNIV)
00266       PNIV = LatticeFunc->MergeValues(PNIV, OpVal);
00267     
00268     if (PNIV == Overdefined)
00269       break;  // Rest of input values don't matter.
00270   }
00271 
00272   // Update the PHI with the compute value, which is the merge of the inputs.
00273   UpdateState(PN, PNIV);
00274 }
00275 
00276 
00277 void SparseSolver::visitInst(Instruction &I) {
00278   // PHIs are handled by the propagation logic, they are never passed into the
00279   // transfer functions.
00280   if (PHINode *PN = dyn_cast<PHINode>(&I))
00281     return visitPHINode(*PN);
00282   
00283   // Otherwise, ask the transfer function what the result is.  If this is
00284   // something that we care about, remember it.
00285   LatticeVal IV = LatticeFunc->ComputeInstructionState(I, *this);
00286   if (IV != LatticeFunc->getUntrackedVal())
00287     UpdateState(I, IV);
00288   
00289   if (TerminatorInst *TI = dyn_cast<TerminatorInst>(&I))
00290     visitTerminatorInst(*TI);
00291 }
00292 
00293 void SparseSolver::Solve(Function &F) {
00294   MarkBlockExecutable(&F.getEntryBlock());
00295   
00296   // Process the work lists until they are empty!
00297   while (!BBWorkList.empty() || !InstWorkList.empty()) {
00298     // Process the instruction work list.
00299     while (!InstWorkList.empty()) {
00300       Instruction *I = InstWorkList.back();
00301       InstWorkList.pop_back();
00302 
00303       DEBUG(dbgs() << "\nPopped off I-WL: " << *I << "\n");
00304 
00305       // "I" got into the work list because it made a transition.  See if any
00306       // users are both live and in need of updating.
00307       for (User *U : I->users()) {
00308         Instruction *UI = cast<Instruction>(U);
00309         if (BBExecutable.count(UI->getParent()))   // Inst is executable?
00310           visitInst(*UI);
00311       }
00312     }
00313 
00314     // Process the basic block work list.
00315     while (!BBWorkList.empty()) {
00316       BasicBlock *BB = BBWorkList.back();
00317       BBWorkList.pop_back();
00318 
00319       DEBUG(dbgs() << "\nPopped off BBWL: " << *BB);
00320 
00321       // Notify all instructions in this basic block that they are newly
00322       // executable.
00323       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
00324         visitInst(*I);
00325     }
00326   }
00327 }
00328 
00329 void SparseSolver::Print(Function &F, raw_ostream &OS) const {
00330   OS << "\nFUNCTION: " << F.getName() << "\n";
00331   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
00332     if (!BBExecutable.count(BB))
00333       OS << "INFEASIBLE: ";
00334     OS << "\t";
00335     if (BB->hasName())
00336       OS << BB->getName() << ":\n";
00337     else
00338       OS << "; anon bb\n";
00339     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
00340       LatticeFunc->PrintValue(getLatticeState(I), OS);
00341       OS << *I << "\n";
00342     }
00343     
00344     OS << "\n";
00345   }
00346 }
00347