1 //===- SparsePropagation.cpp - Sparse Conditional Property Propagation ----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements an abstract sparse conditional propagation algorithm,
11 // modeled after SCCP, but with a customizable lattice function.
13 //===----------------------------------------------------------------------===//
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"
23 //===----------------------------------------------------------------------===//
24 // AbstractLatticeFunction Implementation
25 //===----------------------------------------------------------------------===//
27 AbstractLatticeFunction::~AbstractLatticeFunction() {}
29 /// PrintValue - Render the specified lattice value to the specified stream.
30 void AbstractLatticeFunction::PrintValue(LatticeVal V, std::ostream &OS) {
33 else if (V == OverdefinedVal)
35 else if (V == UntrackedVal)
38 OS << "unknown lattice value";
41 //===----------------------------------------------------------------------===//
42 // SparseSolver Implementation
43 //===----------------------------------------------------------------------===//
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.
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
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();
64 // All instructions are underdefined by default.
65 LV = LatticeFunc->getUndefVal();
67 // If this value is untracked, don't add it to the map.
68 if (LV == LatticeFunc->getUntrackedVal())
70 return ValueState[V] = LV;
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)
80 // An update. Visit uses of I.
81 ValueState[&Inst] = V;
82 InstWorkList.push_back(&Inst);
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!
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!
99 if (BBExecutable.count(Dest)) {
100 DOUT << "Marking Edge Executable: " << Source->getNameStart()
101 << " -> " << Dest->getNameStart() << "\n";
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));
110 MarkBlockExecutable(Dest);
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;
122 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
123 if (BI->isUnconditional()) {
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;
136 // If undefined, neither is feasible yet.
137 if (BCValue == LatticeFunc->getUndefVal())
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;
147 // Constant condition variables mean the branch can only go a single way
148 Succs[C == ConstantInt::getFalse()] = true;
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;
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);
168 // If undefined, neither is feasible yet.
169 if (SCValue == LatticeFunc->getUndefVal())
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);
179 Succs[SI.findCaseValue(cast<ConstantInt>(C))] = true;
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);
190 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
191 if (TI->getSuccessor(i) == To && SuccFeasible[i])
197 void SparseSolver::visitTerminatorInst(TerminatorInst &TI) {
198 SmallVector<bool, 16> SuccFeasible;
199 getFeasibleSuccessors(TI, SuccFeasible);
201 BasicBlock *BB = TI.getParent();
203 // Mark all feasible successors executable...
204 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
206 markEdgeExecutable(BB, TI.getSuccessor(i));
209 void SparseSolver::visitPHINode(PHINode &PN) {
210 LatticeVal PNIV = getOrInitValueState(&PN);
211 LatticeVal Overdefined = LatticeFunc->getOverdefinedVal();
213 // If this value is already overdefined (common) just return.
214 if (PNIV == Overdefined || PNIV == LatticeFunc->getUntrackedVal())
215 return; // Quick exit
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);
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()))
232 // Merge in this value.
233 LatticeVal OpVal = getOrInitValueState(PN.getIncomingValue(i));
235 PNIV = LatticeFunc->MergeValues(PNIV, OpVal);
237 if (PNIV == Overdefined)
238 break; // Rest of input values don't matter.
241 // Update the PHI with the compute value, which is the merge of the inputs.
242 UpdateState(PN, PNIV);
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);
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())
258 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(&I))
259 visitTerminatorInst(*TI);
262 void SparseSolver::Solve(Function &F) {
263 MarkBlockExecutable(F.begin());
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();
272 DOUT << "\nPopped off I-WL: " << *I;
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();
278 Instruction *U = cast<Instruction>(*UI);
279 if (BBExecutable.count(U->getParent())) // Inst is executable?
284 // Process the basic block work list.
285 while (!BBWorkList.empty()) {
286 BasicBlock *BB = BBWorkList.back();
287 BBWorkList.pop_back();
289 DOUT << "\nPopped off BBWL: " << *BB;
291 // Notify all instructions in this basic block that they are newly
293 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
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: ";
306 OS << BB->getNameStr() << ":\n";
309 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
310 LatticeFunc->PrintValue(getLatticeState(I), OS);