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