Add a new SparsePropagation analysis utility, which allows you to do
[oota-llvm.git] / lib / Analysis / SparsePropagation.cpp
1 //===- SparsePropagation.cpp - Sparse Conditional Property Propagation ----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements an abstract sparse conditional propagation algorithm,
11 // modeled after SCCP, but with a customizable lattice function.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "sparseprop"
16 #include "llvm/Analysis/SparsePropagation.h"
17 #include "llvm/Constants.h"
18 #include "llvm/Function.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/Pass.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/Streams.h"
24 using namespace llvm;
25
26 //===----------------------------------------------------------------------===//
27 //                  AbstractLatticeFunction Implementation
28 //===----------------------------------------------------------------------===//
29
30 AbstractLatticeFunction::~AbstractLatticeFunction() {}
31
32 /// PrintValue - Render the specified lattice value to the specified stream.
33 void AbstractLatticeFunction::PrintValue(LatticeVal V, std::ostream &OS) {
34   if (V == UndefVal)
35     OS << "undefined";
36   else if (V == OverdefinedVal)
37     OS << "overdefined";
38   else if (V == UntrackedVal)
39     OS << "untracked";
40   else
41     OS << "unknown lattice value";
42 }
43
44 //===----------------------------------------------------------------------===//
45 //                          SparseSolver Implementation
46 //===----------------------------------------------------------------------===//
47
48 /// getOrInitValueState - Return the LatticeVal object that corresponds to the
49 /// value, initializing the value's state if it hasn't been entered into the
50 /// map yet.   This function is necessary because not all values should start
51 /// out in the underdefined state... Arguments should be overdefined, and
52 /// constants should be marked as constants.
53 ///
54 SparseSolver::LatticeVal SparseSolver::getOrInitValueState(Value *V) {
55   DenseMap<Value*, LatticeVal>::iterator I = ValueState.find(V);
56   if (I != ValueState.end()) return I->second;  // Common case, in the map
57   
58   LatticeVal LV;
59   if (LatticeFunc->IsUntrackedValue(V))
60     return LatticeFunc->getUntrackedVal();
61   else if (Constant *C = dyn_cast<Constant>(V))
62     LV = LatticeFunc->ComputeConstant(C);
63   else if (!isa<Instruction>(V))
64     // Non-instructions (e.g. formal arguments) are overdefined.
65     LV = LatticeFunc->getOverdefinedVal();
66   else
67     // All instructions are underdefined by default.
68     LV = LatticeFunc->getUndefVal();
69   
70   // If this value is untracked, don't add it to the map.
71   if (LV == LatticeFunc->getUntrackedVal())
72     return LV;
73   return ValueState[V] = LV;
74 }
75
76 /// UpdateState - When the state for some instruction is potentially updated,
77 /// this function notices and adds I to the worklist if needed.
78 void SparseSolver::UpdateState(Instruction &Inst, LatticeVal V) {
79   DenseMap<Value*, LatticeVal>::iterator I = ValueState.find(&Inst);
80   if (I != ValueState.end() && I->second == V)
81     return;  // No change.
82   
83   // An update.  Visit uses of I.
84   ValueState[&Inst] = V;
85   InstWorkList.push_back(&Inst);
86 }
87
88 /// MarkBlockExecutable - This method can be used by clients to mark all of
89 /// the blocks that are known to be intrinsically live in the processed unit.
90 void SparseSolver::MarkBlockExecutable(BasicBlock *BB) {
91   DOUT << "Marking Block Executable: " << BB->getNameStart() << "\n";
92   BBExecutable.insert(BB);   // Basic block is executable!
93   BBWorkList.push_back(BB);  // Add the block to the work list!
94 }
95
96 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
97 /// work list if it is not already executable...
98 void SparseSolver::markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
99   if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
100     return;  // This edge is already known to be executable!
101   
102   if (BBExecutable.count(Dest)) {
103     DOUT << "Marking Edge Executable: " << Source->getNameStart()
104     << " -> " << Dest->getNameStart() << "\n";
105     
106     // The destination is already executable, but we just made an edge
107     // feasible that wasn't before.  Revisit the PHI nodes in the block
108     // because they have potentially new operands.
109     for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
110       visitPHINode(*cast<PHINode>(I));
111     
112   } else {
113     MarkBlockExecutable(Dest);
114   }
115 }
116
117
118 /// getFeasibleSuccessors - Return a vector of booleans to indicate which
119 /// successors are reachable from a given terminator instruction.
120 void SparseSolver::getFeasibleSuccessors(TerminatorInst &TI,
121                                          SmallVectorImpl<bool> &Succs) {
122   Succs.resize(TI.getNumSuccessors());
123   if (TI.getNumSuccessors() == 0) return;
124   
125   if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
126     if (BI->isUnconditional()) {
127       Succs[0] = true;
128       return;
129     }
130     
131     LatticeVal BCValue = getOrInitValueState(BI->getCondition());
132     if (BCValue == LatticeFunc->getOverdefinedVal() ||
133         BCValue == LatticeFunc->getUntrackedVal()) {
134       // Overdefined condition variables can branch either way.
135       Succs[0] = Succs[1] = true;
136       return;
137     }
138
139     // If undefined, neither is feasible yet.
140     if (BCValue == LatticeFunc->getUndefVal())
141       return;
142
143     Constant *C = LatticeFunc->GetConstant(BCValue, BI->getCondition(), *this);
144     if (C == 0 || !isa<ConstantInt>(C)) {
145       // Non-constant values can go either way.
146       Succs[0] = Succs[1] = true;
147       return;
148     }
149
150     // Constant condition variables mean the branch can only go a single way
151     Succs[C == ConstantInt::getFalse()] = true;
152     return;
153   }
154   
155   if (isa<InvokeInst>(TI)) {
156     // Invoke instructions successors are always executable.
157     // TODO: Could ask the lattice function if the value can throw.
158     Succs[0] = Succs[1] = true;
159     return;
160   }
161   
162   SwitchInst &SI = cast<SwitchInst>(TI);
163   LatticeVal SCValue = getOrInitValueState(SI.getCondition());
164   if (SCValue == LatticeFunc->getOverdefinedVal() ||
165       SCValue == LatticeFunc->getUntrackedVal()) {
166     // All destinations are executable!
167     Succs.assign(TI.getNumSuccessors(), true);
168     return;
169   }
170   
171   // If undefined, neither is feasible yet.
172   if (SCValue == LatticeFunc->getUndefVal())
173     return;
174   
175   Constant *C = LatticeFunc->GetConstant(SCValue, SI.getCondition(), *this);
176   if (C == 0 || !isa<ConstantInt>(C)) {
177     // All destinations are executable!
178     Succs.assign(TI.getNumSuccessors(), true);
179     return;
180   }
181   
182   Succs[SI.findCaseValue(cast<ConstantInt>(C))] = true;
183 }
184
185
186 /// isEdgeFeasible - Return true if the control flow edge from the 'From'
187 /// basic block to the 'To' basic block is currently feasible...
188 bool SparseSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
189   SmallVector<bool, 16> SuccFeasible;
190   TerminatorInst *TI = From->getTerminator();
191   getFeasibleSuccessors(*TI, SuccFeasible);
192   
193   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
194     if (TI->getSuccessor(i) == To && SuccFeasible[i])
195       return true;
196   
197   return false;
198 }
199
200 void SparseSolver::visitTerminatorInst(TerminatorInst &TI) {
201   SmallVector<bool, 16> SuccFeasible;
202   getFeasibleSuccessors(TI, SuccFeasible);
203   
204   BasicBlock *BB = TI.getParent();
205   
206   // Mark all feasible successors executable...
207   for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
208     if (SuccFeasible[i])
209       markEdgeExecutable(BB, TI.getSuccessor(i));
210 }
211
212 void SparseSolver::visitPHINode(PHINode &PN) {
213   LatticeVal PNIV = getOrInitValueState(&PN);
214   LatticeVal Overdefined = LatticeFunc->getOverdefinedVal();
215   
216   // If this value is already overdefined (common) just return.
217   if (PNIV == Overdefined || PNIV == LatticeFunc->getUntrackedVal())
218     return;  // Quick exit
219   
220   // Super-extra-high-degree PHI nodes are unlikely to ever be interesting,
221   // and slow us down a lot.  Just mark them overdefined.
222   if (PN.getNumIncomingValues() > 64) {
223     UpdateState(PN, Overdefined);
224     return;
225   }
226   
227   // Look at all of the executable operands of the PHI node.  If any of them
228   // are overdefined, the PHI becomes overdefined as well.  Otherwise, ask the
229   // transfer function to give us the merge of the incoming values.
230   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
231     // If the edge is not yet known to be feasible, it doesn't impact the PHI.
232     if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
233       continue;
234     
235     // Merge in this value.
236     LatticeVal OpVal = getOrInitValueState(PN.getIncomingValue(i));
237     if (OpVal != PNIV)
238       PNIV = LatticeFunc->MergeValues(PNIV, OpVal);
239     
240     if (PNIV == Overdefined)
241       break;  // Rest of input values don't matter.
242   }
243
244   // Update the PHI with the compute value, which is the merge of the inputs.
245   UpdateState(PN, PNIV);
246 }
247
248
249 void SparseSolver::visitInst(Instruction &I) {
250   // PHIs are handled by the propagation logic, they are never passed into the
251   // transfer functions.
252   if (PHINode *PN = dyn_cast<PHINode>(&I))
253     return visitPHINode(*PN);
254   
255   // Otherwise, ask the transfer function what the result is.  If this is
256   // something that we care about, remember it.
257   LatticeVal IV = LatticeFunc->ComputeInstructionState(I, *this);
258   if (IV != LatticeFunc->getUntrackedVal())
259     UpdateState(I, IV);
260   
261   if (TerminatorInst *TI = dyn_cast<TerminatorInst>(&I))
262     visitTerminatorInst(*TI);
263 }
264
265 void SparseSolver::Solve(Function &F) {
266   MarkBlockExecutable(F.begin());
267   
268   // Process the work lists until they are empty!
269   while (!BBWorkList.empty() || !InstWorkList.empty()) {
270     // Process the instruction work list.
271     while (!InstWorkList.empty()) {
272       Instruction *I = InstWorkList.back();
273       InstWorkList.pop_back();
274
275       DOUT << "\nPopped off I-WL: " << *I;
276
277       // "I" got into the work list because it made a transition.  See if any
278       // users are both live and in need of updating.
279       for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
280            UI != E; ++UI) {
281         Instruction *U = cast<Instruction>(*UI);
282         if (BBExecutable.count(U->getParent()))   // Inst is executable?
283           visitInst(*U);
284       }
285     }
286
287     // Process the basic block work list.
288     while (!BBWorkList.empty()) {
289       BasicBlock *BB = BBWorkList.back();
290       BBWorkList.pop_back();
291
292       DOUT << "\nPopped off BBWL: " << *BB;
293
294       // Notify all instructions in this basic block that they are newly
295       // executable.
296       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
297         visitInst(*I);
298     }
299   }
300 }
301
302 void SparseSolver::Print(Function &F, std::ostream &OS) {
303   OS << "\nFUNCTION: " << F.getNameStr() << "\n";
304   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
305     if (!BBExecutable.count(BB))
306       OS << "INFEASIBLE: ";
307     OS << "\t";
308     if (BB->hasName())
309       OS << BB->getNameStr() << ":\n";
310     else
311       OS << "; anon bb\n";
312     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
313       LatticeFunc->PrintValue(getLatticeState(I), OS);
314       OS << *I;
315     }
316     
317     OS << "\n";
318   }
319 }
320