LLVM  6.0.0svn
SparsePropagation.cpp
Go to the documentation of this file.
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 
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/IR/Argument.h"
19 #include "llvm/IR/BasicBlock.h"
20 #include "llvm/IR/Constant.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/Function.h"
23 #include "llvm/IR/InstrTypes.h"
24 #include "llvm/IR/Instruction.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/User.h"
27 #include "llvm/Support/Casting.h"
28 #include "llvm/Support/Debug.h"
30 
31 using namespace llvm;
32 
33 #define DEBUG_TYPE "sparseprop"
34 
35 //===----------------------------------------------------------------------===//
36 // AbstractLatticeFunction Implementation
37 //===----------------------------------------------------------------------===//
38 
39 template <class LatticeVal>
41 
42 /// PrintValue - Render the specified lattice value to the specified stream.
43 template <class LatticeVal>
45  raw_ostream &OS) {
46  if (V == UndefVal)
47  OS << "undefined";
48  else if (V == OverdefinedVal)
49  OS << "overdefined";
50  else if (V == UntrackedVal)
51  OS << "untracked";
52  else
53  OS << "unknown lattice value";
54 }
55 
56 //===----------------------------------------------------------------------===//
57 // SparseSolver Implementation
58 //===----------------------------------------------------------------------===//
59 
60 /// getValueState - Return the LatticeVal object that corresponds to the
61 /// value, initializing the value's state if it hasn't been entered into the
62 /// map yet. This function is necessary because not all values should start
63 /// out in the underdefined state... Arguments should be overdefined, and
64 /// constants should be marked as constants.
65 template <class LatticeVal>
67  auto I = ValueState.find(V);
68  if (I != ValueState.end()) return I->second; // Common case, in the map
69 
70  LatticeVal LV;
71  if (LatticeFunc->IsUntrackedValue(V))
72  return LatticeFunc->getUntrackedVal();
73  else if (Constant *C = dyn_cast<Constant>(V))
74  LV = LatticeFunc->ComputeConstant(C);
75  else if (Argument *A = dyn_cast<Argument>(V))
76  LV = LatticeFunc->ComputeArgument(A);
77  else if (!isa<Instruction>(V))
78  // All other non-instructions are overdefined.
79  LV = LatticeFunc->getOverdefinedVal();
80  else
81  // All instructions are underdefined by default.
82  LV = LatticeFunc->getUndefVal();
83 
84  // If this value is untracked, don't add it to the map.
85  if (LV == LatticeFunc->getUntrackedVal())
86  return LV;
87  return ValueState[V] = LV;
88 }
89 
90 /// UpdateState - When the state for some instruction is potentially updated,
91 /// this function notices and adds I to the worklist if needed.
92 template <class LatticeVal>
93 void SparseSolver<LatticeVal>::UpdateState(Instruction &Inst, LatticeVal V) {
94  auto I = ValueState.find(&Inst);
95  if (I != ValueState.end() && I->second == V)
96  return; // No change.
97 
98  // An update. Visit uses of I.
99  ValueState[&Inst] = V;
100  InstWorkList.push_back(&Inst);
101 }
102 
103 /// MarkBlockExecutable - This method can be used by clients to mark all of
104 /// the blocks that are known to be intrinsically live in the processed unit.
105 template <class LatticeVal>
107  DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << "\n");
108  BBExecutable.insert(BB); // Basic block is executable!
109  BBWorkList.push_back(BB); // Add the block to the work list!
110 }
111 
112 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
113 /// work list if it is not already executable...
114 template <class LatticeVal>
116  BasicBlock *Dest) {
117  if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
118  return; // This edge is already known to be executable!
119 
120  DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
121  << " -> " << Dest->getName() << "\n");
122 
123  if (BBExecutable.count(Dest)) {
124  // The destination is already executable, but we just made an edge
125  // feasible that wasn't before. Revisit the PHI nodes in the block
126  // because they have potentially new operands.
127  for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
128  visitPHINode(*cast<PHINode>(I));
129  } else {
130  MarkBlockExecutable(Dest);
131  }
132 }
133 
134 /// getFeasibleSuccessors - Return a vector of booleans to indicate which
135 /// successors are reachable from a given terminator instruction.
136 template <class LatticeVal>
138  TerminatorInst &TI, SmallVectorImpl<bool> &Succs, bool AggressiveUndef) {
139  Succs.resize(TI.getNumSuccessors());
140  if (TI.getNumSuccessors() == 0) return;
141 
142  if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
143  if (BI->isUnconditional()) {
144  Succs[0] = true;
145  return;
146  }
147 
148  LatticeVal BCValue;
149  if (AggressiveUndef)
150  BCValue = getValueState(BI->getCondition());
151  else
152  BCValue = getLatticeState(BI->getCondition());
153 
154  if (BCValue == LatticeFunc->getOverdefinedVal() ||
155  BCValue == LatticeFunc->getUntrackedVal()) {
156  // Overdefined condition variables can branch either way.
157  Succs[0] = Succs[1] = true;
158  return;
159  }
160 
161  // If undefined, neither is feasible yet.
162  if (BCValue == LatticeFunc->getUndefVal())
163  return;
164 
165  Constant *C = LatticeFunc->GetConstant(BCValue, BI->getCondition(), *this);
166  if (!C || !isa<ConstantInt>(C)) {
167  // Non-constant values can go either way.
168  Succs[0] = Succs[1] = true;
169  return;
170  }
171 
172  // Constant condition variables mean the branch can only go a single way
173  Succs[C->isNullValue()] = true;
174  return;
175  }
176 
177  if (isa<InvokeInst>(TI)) {
178  // Invoke instructions successors are always executable.
179  // TODO: Could ask the lattice function if the value can throw.
180  Succs[0] = Succs[1] = true;
181  return;
182  }
183 
184  if (isa<IndirectBrInst>(TI)) {
185  Succs.assign(Succs.size(), true);
186  return;
187  }
188 
189  SwitchInst &SI = cast<SwitchInst>(TI);
190  LatticeVal SCValue;
191  if (AggressiveUndef)
192  SCValue = getValueState(SI.getCondition());
193  else
194  SCValue = getLatticeState(SI.getCondition());
195 
196  if (SCValue == LatticeFunc->getOverdefinedVal() ||
197  SCValue == LatticeFunc->getUntrackedVal()) {
198  // All destinations are executable!
199  Succs.assign(TI.getNumSuccessors(), true);
200  return;
201  }
202 
203  // If undefined, neither is feasible yet.
204  if (SCValue == LatticeFunc->getUndefVal())
205  return;
206 
207  Constant *C = LatticeFunc->GetConstant(SCValue, SI.getCondition(), *this);
208  if (!C || !isa<ConstantInt>(C)) {
209  // All destinations are executable!
210  Succs.assign(TI.getNumSuccessors(), true);
211  return;
212  }
213  SwitchInst::CaseHandle Case = *SI.findCaseValue(cast<ConstantInt>(C));
214  Succs[Case.getSuccessorIndex()] = true;
215 }
216 
217 /// isEdgeFeasible - Return true if the control flow edge from the 'From'
218 /// basic block to the 'To' basic block is currently feasible...
219 template <class LatticeVal>
221  bool AggressiveUndef) {
222  SmallVector<bool, 16> SuccFeasible;
223  TerminatorInst *TI = From->getTerminator();
224  getFeasibleSuccessors(*TI, SuccFeasible, AggressiveUndef);
225 
226  for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
227  if (TI->getSuccessor(i) == To && SuccFeasible[i])
228  return true;
229 
230  return false;
231 }
232 
233 template <class LatticeVal>
235  SmallVector<bool, 16> SuccFeasible;
236  getFeasibleSuccessors(TI, SuccFeasible, true);
237 
238  BasicBlock *BB = TI.getParent();
239 
240  // Mark all feasible successors executable...
241  for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
242  if (SuccFeasible[i])
243  markEdgeExecutable(BB, TI.getSuccessor(i));
244 }
245 
246 template <class LatticeVal>
248  // The lattice function may store more information on a PHINode than could be
249  // computed from its incoming values. For example, SSI form stores its sigma
250  // functions as PHINodes with a single incoming value.
251  if (LatticeFunc->IsSpecialCasedPHI(&PN)) {
252  LatticeVal IV = LatticeFunc->ComputeInstructionState(PN, *this);
253  if (IV != LatticeFunc->getUntrackedVal())
254  UpdateState(PN, IV);
255  return;
256  }
257 
258  LatticeVal PNIV = getValueState(&PN);
259  LatticeVal Overdefined = LatticeFunc->getOverdefinedVal();
260 
261  // If this value is already overdefined (common) just return.
262  if (PNIV == Overdefined || PNIV == LatticeFunc->getUntrackedVal())
263  return; // Quick exit
264 
265  // Super-extra-high-degree PHI nodes are unlikely to ever be interesting,
266  // and slow us down a lot. Just mark them overdefined.
267  if (PN.getNumIncomingValues() > 64) {
268  UpdateState(PN, Overdefined);
269  return;
270  }
271 
272  // Look at all of the executable operands of the PHI node. If any of them
273  // are overdefined, the PHI becomes overdefined as well. Otherwise, ask the
274  // transfer function to give us the merge of the incoming values.
275  for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
276  // If the edge is not yet known to be feasible, it doesn't impact the PHI.
277  if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent(), true))
278  continue;
279 
280  // Merge in this value.
281  LatticeVal OpVal = getValueState(PN.getIncomingValue(i));
282  if (OpVal != PNIV)
283  PNIV = LatticeFunc->MergeValues(PNIV, OpVal);
284 
285  if (PNIV == Overdefined)
286  break; // Rest of input values don't matter.
287  }
288 
289  // Update the PHI with the compute value, which is the merge of the inputs.
290  UpdateState(PN, PNIV);
291 }
292 
293 template <class LatticeVal>
295  // PHIs are handled by the propagation logic, they are never passed into the
296  // transfer functions.
297  if (PHINode *PN = dyn_cast<PHINode>(&I))
298  return visitPHINode(*PN);
299 
300  // Otherwise, ask the transfer function what the result is. If this is
301  // something that we care about, remember it.
302  LatticeVal IV = LatticeFunc->ComputeInstructionState(I, *this);
303  if (IV != LatticeFunc->getUntrackedVal())
304  UpdateState(I, IV);
305 
306  if (TerminatorInst *TI = dyn_cast<TerminatorInst>(&I))
307  visitTerminatorInst(*TI);
308 }
309 
310 template <class LatticeVal> void SparseSolver<LatticeVal>::Solve(Function &F) {
311  MarkBlockExecutable(&F.getEntryBlock());
312 
313  // Process the work lists until they are empty!
314  while (!BBWorkList.empty() || !InstWorkList.empty()) {
315  // Process the instruction work list.
316  while (!InstWorkList.empty()) {
317  Instruction *I = InstWorkList.back();
318  InstWorkList.pop_back();
319 
320  DEBUG(dbgs() << "\nPopped off I-WL: " << *I << "\n");
321 
322  // "I" got into the work list because it made a transition. See if any
323  // users are both live and in need of updating.
324  for (User *U : I->users()) {
325  Instruction *UI = cast<Instruction>(U);
326  if (BBExecutable.count(UI->getParent())) // Inst is executable?
327  visitInst(*UI);
328  }
329  }
330 
331  // Process the basic block work list.
332  while (!BBWorkList.empty()) {
333  BasicBlock *BB = BBWorkList.back();
334  BBWorkList.pop_back();
335 
336  DEBUG(dbgs() << "\nPopped off BBWL: " << *BB);
337 
338  // Notify all instructions in this basic block that they are newly
339  // executable.
340  for (Instruction &I : *BB)
341  visitInst(I);
342  }
343  }
344 }
345 
346 template <class LatticeVal>
348  OS << "\nFUNCTION: " << F.getName() << "\n";
349  for (auto &BB : F) {
350  if (!BBExecutable.count(&BB))
351  OS << "INFEASIBLE: ";
352  OS << "\t";
353  if (BB.hasName())
354  OS << BB.getName() << ":\n";
355  else
356  OS << "; anon bb\n";
357  for (auto &I : BB) {
358  LatticeFunc->PrintValue(getLatticeState(&I), OS);
359  OS << I << "\n";
360  }
361 
362  OS << "\n";
363  }
364 }
uint64_t CallInst * C
This class represents an incoming formal argument to a Function.
Definition: Argument.h:30
void Solve(Function &F)
Solve - Solve for constants and executable blocks.
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
bool isEdgeFeasible(BasicBlock *From, BasicBlock *To, bool AggressiveUndef=false)
isEdgeFeasible - Return true if the control flow edge from the &#39;From&#39; basic block to the &#39;To&#39; basic b...
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:136
Value * getCondition() const
F(f)
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:252
void assign(size_type NumElts, const T &Elt)
Definition: SmallVector.h:427
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition: Constants.cpp:86
const BasicBlock & getEntryBlock() const
Definition: Function.h:572
Subclasses of this class are all able to terminate a basic block.
Definition: InstrTypes.h:54
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
bool hasName() const
Definition: Value.h:251
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
Conditional or Unconditional Branch instruction.
This is an important base class in LLVM.
Definition: Constant.h:42
This file contains the declarations for the subclasses of Constant, which represent the different fla...
const Instruction & back() const
Definition: BasicBlock.h:266
SparseSolver - This class is a general purpose solver for Sparse Conditional Propagation with a progr...
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
Iterator for intrusive lists based on ilist_node.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:864
unsigned getNumIncomingValues() const
Return the number of incoming edges.
CaseIt findCaseValue(const ConstantInt *C)
Search all of the case values for the specified constant.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
virtual void PrintValue(LatticeVal V, raw_ostream &OS)
PrintValue - Render the specified lattice value to the specified stream.
iterator_range< user_iterator > users()
Definition: Value.h:395
unsigned getSuccessorIndex() const
Returns TerminatorInst&#39;s successor index for current case successor.
void Print(Function &F, raw_ostream &OS) const
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:218
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
#define I(x, y, z)
Definition: MD5.cpp:58
Multiway switch.
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
LLVM Value Representation.
Definition: Value.h:73
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:44
#define DEBUG(X)
Definition: Debug.h:118
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:120
const BasicBlock * getParent() const
Definition: Instruction.h:66
LatticeVal getValueState(Value *V)
getValueState - Return the LatticeVal object that corresponds to the value, initializing the value&#39;s ...
void resize(size_type N)
Definition: SmallVector.h:355