blob: 0191fe33916f5d23c53c24a6a5ccf3615f77dbcb [file] [log] [blame]
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001//===-- PredicateSimplifier.cpp - Path Sensitive Simplifier ---------------===//
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Nick Lewycky and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00008//===----------------------------------------------------------------------===//
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00009//
10// Path-sensitive optimizer. In a branch where x == y, replace uses of
11// x with y. Permits further optimization, such as the elimination of
12// the unreachable call:
13//
14// void test(int *p, int *q)
15// {
16// if (p != q)
17// return;
18//
19// if (*p != *q)
20// foo(); // unreachable
21// }
22//
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000023//===----------------------------------------------------------------------===//
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000024//
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000025// This pass focusses on four properties; equals, not equals, less-than
26// and less-than-or-equals-to. The greater-than forms are also held just
27// to allow walking from a lesser node to a greater one. These properties
28// are stored in a lattice; LE can become LT or EQ, NE can become LT or GT.
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000029//
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000030// These relationships define a graph between values of the same type. Each
31// Value is stored in a map table that retrieves the associated Node. This
32// is how EQ relationships are stored; the map contains pointers to the
33// same node. The node contains a most canonical Value* form and the list of
34// known relationships.
35//
36// If two nodes are known to be inequal, then they will contain pointers to
37// each other with an "NE" relationship. If node getNode(%x) is less than
38// getNode(%y), then the %x node will contain <%y, GT> and %y will contain
39// <%x, LT>. This allows us to tie nodes together into a graph like this:
40//
41// %a < %b < %c < %d
42//
43// with four nodes representing the properties. The InequalityGraph provides
Nick Lewycky2fc338f2007-01-11 02:32:38 +000044// querying with "isRelatedBy" and mutators "addEquality" and "addInequality".
45// To find a relationship, we start with one of the nodes any binary search
46// through its list to find where the relationships with the second node start.
47// Then we iterate through those to find the first relationship that dominates
48// our context node.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000049//
50// To create these properties, we wait until a branch or switch instruction
51// implies that a particular value is true (or false). The VRPSolver is
52// responsible for analyzing the variable and seeing what new inferences
53// can be made from each property. For example:
54//
55// %P = seteq int* %ptr, null
56// %a = or bool %P, %Q
57// br bool %a label %cond_true, label %cond_false
58//
59// For the true branch, the VRPSolver will start with %a EQ true and look at
60// the definition of %a and find that it can infer that %P and %Q are both
61// true. From %P being true, it can infer that %ptr NE null. For the false
62// branch it can't infer anything from the "or" instruction.
63//
64// Besides branches, we can also infer properties from instruction that may
65// have undefined behaviour in certain cases. For example, the dividend of
66// a division may never be zero. After the division instruction, we may assume
67// that the dividend is not equal to zero.
68//
69//===----------------------------------------------------------------------===//
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000070
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000071#define DEBUG_TYPE "predsimplify"
72#include "llvm/Transforms/Scalar.h"
73#include "llvm/Constants.h"
Nick Lewyckyf3450082006-10-22 19:53:27 +000074#include "llvm/DerivedTypes.h"
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000075#include "llvm/Instructions.h"
76#include "llvm/Pass.h"
Nick Lewycky2fc338f2007-01-11 02:32:38 +000077#include "llvm/ADT/DepthFirstIterator.h"
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000078#include "llvm/ADT/SetOperations.h"
79#include "llvm/ADT/SmallVector.h"
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000080#include "llvm/ADT/Statistic.h"
81#include "llvm/ADT/STLExtras.h"
82#include "llvm/Analysis/Dominators.h"
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000083#include "llvm/Analysis/ET-Forest.h"
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000084#include "llvm/Support/CFG.h"
Chris Lattnerf06bb652006-12-06 18:14:47 +000085#include "llvm/Support/Compiler.h"
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000086#include "llvm/Support/Debug.h"
Nick Lewycky77e030b2006-10-12 02:02:44 +000087#include "llvm/Support/InstVisitor.h"
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000088#include "llvm/Transforms/Utils/Local.h"
89#include <algorithm>
90#include <deque>
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000091#include <sstream>
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000092using namespace llvm;
93
Chris Lattner0e5255b2006-12-19 21:49:03 +000094STATISTIC(NumVarsReplaced, "Number of argument substitutions");
95STATISTIC(NumInstruction , "Number of instructions removed");
96STATISTIC(NumSimple , "Number of simple replacements");
Nick Lewycky2fc338f2007-01-11 02:32:38 +000097STATISTIC(NumBlocks , "Number of blocks marked unreachable");
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000098
Chris Lattner0e5255b2006-12-19 21:49:03 +000099namespace {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000100 // SLT SGT ULT UGT EQ
101 // 0 1 0 1 0 -- GT 10
102 // 0 1 0 1 1 -- GE 11
103 // 0 1 1 0 0 -- SGTULT 12
104 // 0 1 1 0 1 -- SGEULE 13
105 // 0 1 1 1 0 -- SGTUNE 14
106 // 0 1 1 1 1 -- SGEUANY 15
107 // 1 0 0 1 0 -- SLTUGT 18
108 // 1 0 0 1 1 -- SLEUGE 19
109 // 1 0 1 0 0 -- LT 20
110 // 1 0 1 0 1 -- LE 21
111 // 1 0 1 1 0 -- SLTUNE 22
112 // 1 0 1 1 1 -- SLEUANY 23
113 // 1 1 0 1 0 -- SNEUGT 26
114 // 1 1 0 1 1 -- SANYUGE 27
115 // 1 1 1 0 0 -- SNEULT 28
116 // 1 1 1 0 1 -- SANYULE 29
117 // 1 1 1 1 0 -- NE 30
118 enum LatticeBits {
119 EQ_BIT = 1, UGT_BIT = 2, ULT_BIT = 4, SGT_BIT = 8, SLT_BIT = 16
120 };
121 enum LatticeVal {
122 GT = SGT_BIT | UGT_BIT,
123 GE = GT | EQ_BIT,
124 LT = SLT_BIT | ULT_BIT,
125 LE = LT | EQ_BIT,
126 NE = SLT_BIT | SGT_BIT | ULT_BIT | UGT_BIT,
127 SGTULT = SGT_BIT | ULT_BIT,
128 SGEULE = SGTULT | EQ_BIT,
129 SLTUGT = SLT_BIT | UGT_BIT,
130 SLEUGE = SLTUGT | EQ_BIT,
131 SNEULT = SLT_BIT | SGT_BIT | ULT_BIT,
132 SNEUGT = SLT_BIT | SGT_BIT | UGT_BIT,
133 SLTUNE = SLT_BIT | ULT_BIT | UGT_BIT,
134 SGTUNE = SGT_BIT | ULT_BIT | UGT_BIT,
135 SLEUANY = SLT_BIT | ULT_BIT | UGT_BIT | EQ_BIT,
136 SGEUANY = SGT_BIT | ULT_BIT | UGT_BIT | EQ_BIT,
137 SANYULE = SLT_BIT | SGT_BIT | ULT_BIT | EQ_BIT,
138 SANYUGE = SLT_BIT | SGT_BIT | UGT_BIT | EQ_BIT
139 };
140
141 static bool validPredicate(LatticeVal LV) {
142 switch (LV) {
143 case GT: case GE: case LT: case LE: case NE:
144 case SGTULT: case SGTUNE: case SGEULE:
145 case SLTUGT: case SLTUNE: case SLEUGE:
146 case SNEULT: case SNEUGT:
147 case SLEUANY: case SGEUANY: case SANYULE: case SANYUGE:
148 return true;
149 default:
150 return false;
151 }
152 }
153
154 /// reversePredicate - reverse the direction of the inequality
155 static LatticeVal reversePredicate(LatticeVal LV) {
156 unsigned reverse = LV ^ (SLT_BIT|SGT_BIT|ULT_BIT|UGT_BIT); //preserve EQ_BIT
157 if ((reverse & (SLT_BIT|SGT_BIT)) == 0)
158 reverse |= (SLT_BIT|SGT_BIT);
159
160 if ((reverse & (ULT_BIT|UGT_BIT)) == 0)
161 reverse |= (ULT_BIT|UGT_BIT);
162
163 LatticeVal Rev = static_cast<LatticeVal>(reverse);
164 assert(validPredicate(Rev) && "Failed reversing predicate.");
165 return Rev;
166 }
167
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000168 /// The InequalityGraph stores the relationships between values.
169 /// Each Value in the graph is assigned to a Node. Nodes are pointer
170 /// comparable for equality. The caller is expected to maintain the logical
171 /// consistency of the system.
172 ///
173 /// The InequalityGraph class may invalidate Node*s after any mutator call.
174 /// @brief The InequalityGraph stores the relationships between values.
175 class VISIBILITY_HIDDEN InequalityGraph {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000176 ETNode *TreeRoot;
177
178 InequalityGraph(); // DO NOT IMPLEMENT
179 InequalityGraph(InequalityGraph &); // DO NOT IMPLEMENT
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000180 public:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000181 explicit InequalityGraph(ETNode *TreeRoot) : TreeRoot(TreeRoot) {}
182
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000183 class Node;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000184
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000185 /// This is a StrictWeakOrdering predicate that sorts ETNodes by how many
186 /// children they have. With this, you can iterate through a list sorted by
187 /// this operation and the first matching entry is the most specific match
188 /// for your basic block. The order provided is total; ETNodes with the
189 /// same number of children are sorted by pointer address.
190 struct VISIBILITY_HIDDEN OrderByDominance {
191 bool operator()(const ETNode *LHS, const ETNode *RHS) const {
192 unsigned LHS_spread = LHS->getDFSNumOut() - LHS->getDFSNumIn();
193 unsigned RHS_spread = RHS->getDFSNumOut() - RHS->getDFSNumIn();
194 if (LHS_spread != RHS_spread) return LHS_spread < RHS_spread;
195 else return LHS < RHS;
196 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000197 };
198
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000199 /// An Edge is contained inside a Node making one end of the edge implicit
200 /// and contains a pointer to the other end. The edge contains a lattice
201 /// value specifying the relationship between the two nodes. Further, there
202 /// is an ETNode specifying which subtree of the dominator the edge applies.
203 class VISIBILITY_HIDDEN Edge {
204 public:
205 Edge(unsigned T, LatticeVal V, ETNode *ST)
206 : To(T), LV(V), Subtree(ST) {}
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000207
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000208 unsigned To;
209 LatticeVal LV;
210 ETNode *Subtree;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000211
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000212 bool operator<(const Edge &edge) const {
213 if (To != edge.To) return To < edge.To;
214 else return OrderByDominance()(Subtree, edge.Subtree);
215 }
216 bool operator<(unsigned to) const {
217 return To < to;
218 }
219 };
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000220
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000221 /// A single node in the InequalityGraph. This stores the canonical Value
222 /// for the node, as well as the relationships with the neighbours.
223 ///
224 /// Because the lists are intended to be used for traversal, it is invalid
225 /// for the node to list itself in LessEqual or GreaterEqual lists. The
226 /// fact that a node is equal to itself is implied, and may be checked
227 /// with pointer comparison.
228 /// @brief A single node in the InequalityGraph.
229 class VISIBILITY_HIDDEN Node {
230 friend class InequalityGraph;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000231
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000232 typedef SmallVector<Edge, 4> RelationsType;
233 RelationsType Relations;
234
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000235 Value *Canonical;
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000236
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000237 // TODO: can this idea improve performance?
238 //friend class std::vector<Node>;
239 //Node(Node &N) { RelationsType.swap(N.RelationsType); }
240
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000241 public:
242 typedef RelationsType::iterator iterator;
243 typedef RelationsType::const_iterator const_iterator;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000244
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000245 Node(Value *V) : Canonical(V) {}
246
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000247 private:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000248#ifndef NDEBUG
249 public:
Nick Lewycky5d6ede52007-01-11 02:38:21 +0000250 virtual ~Node() {}
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000251 virtual void dump() const {
252 dump(*cerr.stream());
253 }
254 private:
255 void dump(std::ostream &os) const {
256 os << *getValue() << ":\n";
257 for (Node::const_iterator NI = begin(), NE = end(); NI != NE; ++NI) {
258 static const std::string names[32] =
259 { "000000", "000001", "000002", "000003", "000004", "000005",
260 "000006", "000007", "000008", "000009", " >", " >=",
261 " s>u<", "s>=u<=", " s>", " s>=", "000016", "000017",
262 " s<u>", "s<=u>=", " <", " <=", " s<", " s<=",
263 "000024", "000025", " u>", " u>=", " u<", " u<=",
264 " !=", "000031" };
265 os << " " << names[NI->LV] << " " << NI->To
266 << "(" << NI->Subtree << ")\n";
267 }
268 }
269#endif
270
271 public:
272 iterator begin() { return Relations.begin(); }
273 iterator end() { return Relations.end(); }
274 const_iterator begin() const { return Relations.begin(); }
275 const_iterator end() const { return Relations.end(); }
276
277 iterator find(unsigned n, ETNode *Subtree) {
278 iterator E = end();
279 for (iterator I = std::lower_bound(begin(), E, n);
280 I != E && I->To == n; ++I) {
281 if (Subtree->DominatedBy(I->Subtree))
282 return I;
283 }
284 return E;
285 }
286
287 const_iterator find(unsigned n, ETNode *Subtree) const {
288 const_iterator E = end();
289 for (const_iterator I = std::lower_bound(begin(), E, n);
290 I != E && I->To == n; ++I) {
291 if (Subtree->DominatedBy(I->Subtree))
292 return I;
293 }
294 return E;
295 }
296
297 Value *getValue() const
298 {
299 return Canonical;
300 }
301
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000302 /// Updates the lattice value for a given node. Create a new entry if
303 /// one doesn't exist, otherwise it merges the values. The new lattice
304 /// value must not be inconsistent with any previously existing value.
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000305 void update(unsigned n, LatticeVal R, ETNode *Subtree) {
306 assert(validPredicate(R) && "Invalid predicate.");
307 iterator I = find(n, Subtree);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000308 if (I == end()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000309 Edge edge(n, R, Subtree);
310 iterator Insert = std::lower_bound(begin(), end(), edge);
311 Relations.insert(Insert, edge);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000312 } else {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000313 LatticeVal LV = static_cast<LatticeVal>(I->LV & R);
314 assert(validPredicate(LV) && "Invalid union of lattice values.");
315 if (LV != I->LV) {
316 if (Subtree == I->Subtree)
317 I->LV = LV;
318 else {
319 assert(Subtree->DominatedBy(I->Subtree) &&
320 "Find returned subtree that doesn't apply.");
321
322 Edge edge(n, R, Subtree);
323 iterator Insert = std::lower_bound(begin(), end(), edge);
324 Relations.insert(Insert, edge);
325 }
326 }
Nick Lewycky51ce8d62006-09-13 19:24:01 +0000327 }
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000328 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000329 };
330
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000331 private:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000332 struct VISIBILITY_HIDDEN NodeMapEdge {
333 Value *V;
334 unsigned index;
335 ETNode *Subtree;
336
337 NodeMapEdge(Value *V, unsigned index, ETNode *Subtree)
338 : V(V), index(index), Subtree(Subtree) {}
339
340 bool operator==(const NodeMapEdge &RHS) const {
341 return V == RHS.V &&
342 Subtree == RHS.Subtree;
343 }
344
345 bool operator<(const NodeMapEdge &RHS) const {
346 if (V != RHS.V) return V < RHS.V;
347 return OrderByDominance()(Subtree, RHS.Subtree);
348 }
349
350 bool operator<(Value *RHS) const {
351 return V < RHS;
352 }
353 };
354
355 typedef std::vector<NodeMapEdge> NodeMapType;
356 NodeMapType NodeMap;
357
358 std::vector<Node> Nodes;
359
Zhou Sheng75b871f2007-01-11 12:24:14 +0000360 std::vector<std::pair<ConstantInt *, unsigned> > Constants;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000361 void initializeConstant(Constant *C, unsigned index) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000362 ConstantInt *CI = dyn_cast<ConstantInt>(C);
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000363 if (!CI) return;
364
365 // XXX: instead of O(n) calls to addInequality, just find the 2, 3 or 4
366 // nodes that are nearest less than or greater than (signed or unsigned).
Zhou Sheng75b871f2007-01-11 12:24:14 +0000367 for (std::vector<std::pair<ConstantInt *, unsigned> >::iterator
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000368 I = Constants.begin(), E = Constants.end(); I != E; ++I) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000369 ConstantInt *Other = I->first;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000370 if (CI->getType() == Other->getType()) {
371 unsigned lv = 0;
372
373 if (CI->getZExtValue() < Other->getZExtValue())
374 lv |= ULT_BIT;
375 else
376 lv |= UGT_BIT;
377
378 if (CI->getSExtValue() < Other->getSExtValue())
379 lv |= SLT_BIT;
380 else
381 lv |= SGT_BIT;
382
383 LatticeVal LV = static_cast<LatticeVal>(lv);
384 assert(validPredicate(LV) && "Not a valid predicate.");
385 if (!isRelatedBy(index, I->second, TreeRoot, LV))
386 addInequality(index, I->second, TreeRoot, LV);
387 }
388 }
389 Constants.push_back(std::make_pair(CI, index));
390 }
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000391
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000392 public:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000393 /// node - returns the node object at a given index retrieved from getNode.
394 /// Index zero is reserved and may not be passed in here. The pointer
395 /// returned is valid until the next call to newNode or getOrInsertNode.
396 Node *node(unsigned index) {
397 assert(index != 0 && "Zero index is reserved for not found.");
398 assert(index <= Nodes.size() && "Index out of range.");
399 return &Nodes[index-1];
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000400 }
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000401
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000402 /// Returns the node currently representing Value V, or zero if no such
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000403 /// node exists.
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000404 unsigned getNode(Value *V, ETNode *Subtree) {
405 NodeMapType::iterator E = NodeMap.end();
406 NodeMapEdge Edge(V, 0, Subtree);
407 NodeMapType::iterator I = std::lower_bound(NodeMap.begin(), E, Edge);
408 while (I != E && I->V == V) {
409 if (Subtree->DominatedBy(I->Subtree))
410 return I->index;
411 ++I;
412 }
413 return 0;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000414 }
415
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000416 /// getOrInsertNode - always returns a valid node index, creating a node
417 /// to match the Value if needed.
418 unsigned getOrInsertNode(Value *V, ETNode *Subtree) {
419 if (unsigned n = getNode(V, Subtree))
420 return n;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000421 else
422 return newNode(V);
423 }
424
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000425 /// newNode - creates a new node for a given Value and returns the index.
426 unsigned newNode(Value *V) {
427 Nodes.push_back(Node(V));
428
429 NodeMapEdge MapEntry = NodeMapEdge(V, Nodes.size(), TreeRoot);
430 assert(!std::binary_search(NodeMap.begin(), NodeMap.end(), MapEntry) &&
431 "Attempt to create a duplicate Node.");
432 NodeMap.insert(std::lower_bound(NodeMap.begin(), NodeMap.end(),
433 MapEntry), MapEntry);
434
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000435 if (Constant *C = dyn_cast<Constant>(V))
436 initializeConstant(C, MapEntry.index);
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000437
438 return MapEntry.index;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000439 }
440
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000441 /// If the Value is in the graph, return the canonical form. Otherwise,
442 /// return the original Value.
443 Value *canonicalize(Value *V, ETNode *Subtree) {
444 if (isa<Constant>(V)) return V;
445
446 if (unsigned n = getNode(V, Subtree))
447 return node(n)->getValue();
448 else
449 return V;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000450 }
451
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000452 /// isRelatedBy - true iff n1 op n2
453 bool isRelatedBy(unsigned n1, unsigned n2, ETNode *Subtree, LatticeVal LV) {
454 if (n1 == n2) return LV & EQ_BIT;
455
456 Node *N1 = node(n1);
457 Node::iterator I = N1->find(n2, Subtree), E = N1->end();
458 if (I != E) return (I->LV & LV) == I->LV;
459
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000460 return false;
461 }
462
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000463 // The add* methods assume that your input is logically valid and may
464 // assertion-fail or infinitely loop if you attempt a contradiction.
Nick Lewycky9d17c822006-10-25 23:48:24 +0000465
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000466 void addEquality(unsigned n, Value *V, ETNode *Subtree) {
467 assert(canonicalize(node(n)->getValue(), Subtree) == node(n)->getValue()
468 && "Node's 'canonical' choice isn't best within this subtree.");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000469
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000470 // Suppose that we are given "%x -> node #1 (%y)". The problem is that
471 // we may already have "%z -> node #2 (%x)" somewhere above us in the
472 // graph. We need to find those edges and add "%z -> node #1 (%y)"
473 // to keep the lookups canonical.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000474
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000475 std::vector<Value *> ToRepoint;
476 ToRepoint.push_back(V);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000477
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000478 if (unsigned Conflict = getNode(V, Subtree)) {
479 // XXX: NodeMap.size() exceeds 68000 entries compiling kimwitu++!
480 // This adds 57 seconds to the otherwise 3 second build. Unacceptable.
481 //
482 // IDEA: could we iterate 1..Nodes.size() calling getNode? It's
483 // O(n log n) but kimwitu++ only has about 300 nodes.
484 for (NodeMapType::iterator I = NodeMap.begin(), E = NodeMap.end();
485 I != E; ++I) {
486 if (I->index == Conflict && Subtree->DominatedBy(I->Subtree))
487 ToRepoint.push_back(I->V);
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000488 }
489 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000490
491 for (std::vector<Value *>::iterator VI = ToRepoint.begin(),
492 VE = ToRepoint.end(); VI != VE; ++VI) {
493 Value *V = *VI;
494
495 // XXX: review this code. This may be doing too many insertions.
496 NodeMapEdge Edge(V, n, Subtree);
497 NodeMapType::iterator E = NodeMap.end();
498 NodeMapType::iterator I = std::lower_bound(NodeMap.begin(), E, Edge);
499 if (I == E || I->V != V || I->Subtree != Subtree) {
500 // New Value
501 NodeMap.insert(I, Edge);
502 } else if (I != E && I->V == V && I->Subtree == Subtree) {
503 // Update best choice
504 I->index = n;
505 }
506
507#ifndef NDEBUG
508 Node *N = node(n);
509 if (isa<Constant>(V)) {
510 if (isa<Constant>(N->getValue())) {
511 assert(V == N->getValue() && "Constant equals different constant?");
512 }
513 }
514#endif
515 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000516 }
517
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000518 /// addInequality - Sets n1 op n2.
519 /// It is also an error to call this on an inequality that is already true.
520 void addInequality(unsigned n1, unsigned n2, ETNode *Subtree,
521 LatticeVal LV1) {
522 assert(n1 != n2 && "A node can't be inequal to itself.");
523
524 if (LV1 != NE)
525 assert(!isRelatedBy(n1, n2, Subtree, reversePredicate(LV1)) &&
526 "Contradictory inequality.");
527
528 Node *N1 = node(n1);
529 Node *N2 = node(n2);
530
531 // Suppose we're adding %n1 < %n2. Find all the %a < %n1 and
532 // add %a < %n2 too. This keeps the graph fully connected.
533 if (LV1 != NE) {
534 // Someone with a head for this sort of logic, please review this.
535 // Given that %x SLTUGT %y and %a SLEUANY %x, what is the relationship
536 // between %a and %y? I believe the below code is correct, but I don't
537 // think it's the most efficient solution.
538
539 unsigned LV1_s = LV1 & (SLT_BIT|SGT_BIT);
540 unsigned LV1_u = LV1 & (ULT_BIT|UGT_BIT);
541 for (Node::iterator I = N1->begin(), E = N1->end(); I != E; ++I) {
542 if (I->LV != NE && I->To != n2) {
543 ETNode *Local_Subtree = NULL;
544 if (Subtree->DominatedBy(I->Subtree))
545 Local_Subtree = Subtree;
546 else if (I->Subtree->DominatedBy(Subtree))
547 Local_Subtree = I->Subtree;
548
549 if (Local_Subtree) {
550 unsigned new_relationship = 0;
551 LatticeVal ILV = reversePredicate(I->LV);
552 unsigned ILV_s = ILV & (SLT_BIT|SGT_BIT);
553 unsigned ILV_u = ILV & (ULT_BIT|UGT_BIT);
554
555 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
556 new_relationship |= ILV_s;
557
558 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
559 new_relationship |= ILV_u;
560
561 if (new_relationship) {
562 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
563 new_relationship |= (SLT_BIT|SGT_BIT);
564 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
565 new_relationship |= (ULT_BIT|UGT_BIT);
566 if ((LV1 & EQ_BIT) && (ILV & EQ_BIT))
567 new_relationship |= EQ_BIT;
568
569 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
570
571 node(I->To)->update(n2, NewLV, Local_Subtree);
572 N2->update(I->To, reversePredicate(NewLV), Local_Subtree);
573 }
574 }
575 }
576 }
577
578 for (Node::iterator I = N2->begin(), E = N2->end(); I != E; ++I) {
579 if (I->LV != NE && I->To != n1) {
580 ETNode *Local_Subtree = NULL;
581 if (Subtree->DominatedBy(I->Subtree))
582 Local_Subtree = Subtree;
583 else if (I->Subtree->DominatedBy(Subtree))
584 Local_Subtree = I->Subtree;
585
586 if (Local_Subtree) {
587 unsigned new_relationship = 0;
588 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
589 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
590
591 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
592 new_relationship |= ILV_s;
593
594 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
595 new_relationship |= ILV_u;
596
597 if (new_relationship) {
598 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
599 new_relationship |= (SLT_BIT|SGT_BIT);
600 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
601 new_relationship |= (ULT_BIT|UGT_BIT);
602 if ((LV1 & EQ_BIT) && (I->LV & EQ_BIT))
603 new_relationship |= EQ_BIT;
604
605 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
606
607 N1->update(I->To, NewLV, Local_Subtree);
608 node(I->To)->update(n1, reversePredicate(NewLV), Local_Subtree);
609 }
610 }
611 }
612 }
613 }
614
615 N1->update(n2, LV1, Subtree);
616 N2->update(n1, reversePredicate(LV1), Subtree);
617 }
Nick Lewycky51ce8d62006-09-13 19:24:01 +0000618
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000619 /// Removes a Value from the graph, but does not delete any nodes. As this
620 /// method does not delete Nodes, V may not be the canonical choice for
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000621 /// a node with any relationships. It is invalid to call newNode on a Value
622 /// that has been removed.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000623 void remove(Value *V) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000624 for (unsigned i = 0; i < NodeMap.size();) {
625 NodeMapType::iterator I = NodeMap.begin()+i;
626 assert((node(I->index)->getValue() != V || node(I->index)->begin() ==
627 node(I->index)->end()) && "Tried to delete in-use node.");
628 if (I->V == V) {
629#ifndef NDEBUG
630 if (node(I->index)->getValue() == V)
631 node(I->index)->Canonical = NULL;
632#endif
633 NodeMap.erase(I);
634 } else ++i;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000635 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000636 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000637
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000638#ifndef NDEBUG
Nick Lewycky5d6ede52007-01-11 02:38:21 +0000639 virtual ~InequalityGraph() {}
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000640 virtual void dump() {
641 dump(*cerr.stream());
642 }
643
644 void dump(std::ostream &os) {
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000645 std::set<Node *> VisitedNodes;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000646 for (NodeMapType::const_iterator I = NodeMap.begin(), E = NodeMap.end();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000647 I != E; ++I) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000648 Node *N = node(I->index);
649 os << *I->V << " == " << I->index << "(" << I->Subtree << ")\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000650 if (VisitedNodes.insert(N).second) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000651 os << I->index << ". ";
652 if (!N->getValue()) os << "(deleted node)\n";
653 else N->dump(os);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000654 }
655 }
656 }
657#endif
658 };
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000659
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000660 /// UnreachableBlocks keeps tracks of blocks that are for one reason or
661 /// another discovered to be unreachable. This is used to cull the graph when
662 /// analyzing instructions, and to mark blocks with the "unreachable"
663 /// terminator instruction after the function has executed.
664 class VISIBILITY_HIDDEN UnreachableBlocks {
665 private:
666 std::vector<BasicBlock *> DeadBlocks;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000667
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000668 public:
669 /// mark - mark a block as dead
670 void mark(BasicBlock *BB) {
671 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
672 std::vector<BasicBlock *>::iterator I =
673 std::lower_bound(DeadBlocks.begin(), E, BB);
674
675 if (I == E || *I != BB) DeadBlocks.insert(I, BB);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000676 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000677
678 /// isDead - returns whether a block is known to be dead already
679 bool isDead(BasicBlock *BB) {
680 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
681 std::vector<BasicBlock *>::iterator I =
682 std::lower_bound(DeadBlocks.begin(), E, BB);
683
684 return I != E && *I == BB;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000685 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000686
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000687 /// kill - replace the dead blocks' terminator with an UnreachableInst.
688 bool kill() {
689 bool modified = false;
690 for (std::vector<BasicBlock *>::iterator I = DeadBlocks.begin(),
691 E = DeadBlocks.end(); I != E; ++I) {
692 BasicBlock *BB = *I;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000693
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000694 DOUT << "unreachable block: " << BB->getName() << "\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000695
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000696 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
697 SI != SE; ++SI) {
698 BasicBlock *Succ = *SI;
699 Succ->removePredecessor(BB);
Nick Lewycky9d17c822006-10-25 23:48:24 +0000700 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000701
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000702 TerminatorInst *TI = BB->getTerminator();
703 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
704 TI->eraseFromParent();
705 new UnreachableInst(BB);
706 ++NumBlocks;
707 modified = true;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000708 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000709 DeadBlocks.clear();
710 return modified;
Nick Lewycky9d17c822006-10-25 23:48:24 +0000711 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000712 };
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000713
714 /// VRPSolver keeps track of how changes to one variable affect other
715 /// variables, and forwards changes along to the InequalityGraph. It
716 /// also maintains the correct choice for "canonical" in the IG.
717 /// @brief VRPSolver calculates inferences from a new relationship.
718 class VISIBILITY_HIDDEN VRPSolver {
719 private:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000720 struct Operation {
721 Value *LHS, *RHS;
722 ICmpInst::Predicate Op;
723
Nick Lewycky42944462007-01-13 02:05:28 +0000724 BasicBlock *ContextBB;
725 Instruction *ContextInst;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000726 };
727 std::deque<Operation> WorkList;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000728
729 InequalityGraph &IG;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000730 UnreachableBlocks &UB;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000731 ETForest *Forest;
732 ETNode *Top;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000733 BasicBlock *TopBB;
734 Instruction *TopInst;
735 bool &modified;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000736
737 typedef InequalityGraph::Node Node;
738
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000739 /// IdomI - Determines whether one Instruction dominates another.
740 bool IdomI(Instruction *I1, Instruction *I2) const {
741 BasicBlock *BB1 = I1->getParent(),
742 *BB2 = I2->getParent();
743 if (BB1 == BB2) {
744 if (isa<TerminatorInst>(I1)) return false;
745 if (isa<TerminatorInst>(I2)) return true;
746 if (isa<PHINode>(I1) && !isa<PHINode>(I2)) return true;
747 if (!isa<PHINode>(I1) && isa<PHINode>(I2)) return false;
748
749 for (BasicBlock::const_iterator I = BB1->begin(), E = BB1->end();
750 I != E; ++I) {
751 if (&*I == I1) return true;
752 if (&*I == I2) return false;
753 }
754 assert(!"Instructions not found in parent BasicBlock?");
755 } else {
756 return Forest->properlyDominates(BB1, BB2);
757 }
758 return false;
759 }
760
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000761 /// Returns true if V1 is a better canonical value than V2.
762 bool compare(Value *V1, Value *V2) const {
763 if (isa<Constant>(V1))
764 return !isa<Constant>(V2);
765 else if (isa<Constant>(V2))
766 return false;
767 else if (isa<Argument>(V1))
768 return !isa<Argument>(V2);
769 else if (isa<Argument>(V2))
770 return false;
771
772 Instruction *I1 = dyn_cast<Instruction>(V1);
773 Instruction *I2 = dyn_cast<Instruction>(V2);
774
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000775 if (!I1 || !I2)
776 return V1->getNumUses() < V2->getNumUses();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000777
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000778 return IdomI(I1, I2);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000779 }
780
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000781 // below - true if the Instruction is dominated by the current context
782 // block or instruction
783 bool below(Instruction *I) {
784 if (TopInst)
785 return IdomI(TopInst, I);
786 else {
787 ETNode *Node = Forest->getNodeForBlock(I->getParent());
788 return Node == Top || Node->DominatedBy(Top);
789 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000790 }
791
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000792 bool makeEqual(Value *V1, Value *V2) {
793 DOUT << "makeEqual(" << *V1 << ", " << *V2 << ")\n";
Nick Lewycky9d17c822006-10-25 23:48:24 +0000794
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000795 if (V1 == V2) return true;
Nick Lewycky9d17c822006-10-25 23:48:24 +0000796
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000797 if (isa<Constant>(V1) && isa<Constant>(V2))
798 return false;
799
800 unsigned n1 = IG.getNode(V1, Top), n2 = IG.getNode(V2, Top);
801
802 if (n1 && n2) {
803 if (n1 == n2) return true;
804 if (IG.isRelatedBy(n1, n2, Top, NE)) return false;
805 }
806
807 if (n1) assert(V1 == IG.node(n1)->getValue() && "Value isn't canonical.");
808 if (n2) assert(V2 == IG.node(n2)->getValue() && "Value isn't canonical.");
809
810 if (compare(V2, V1)) { std::swap(V1, V2); std::swap(n1, n2); }
811
812 assert(!isa<Constant>(V2) && "Tried to remove a constant.");
813
814 SetVector<unsigned> Remove;
815 if (n2) Remove.insert(n2);
816
817 if (n1 && n2) {
818 // Suppose we're being told that %x == %y, and %x <= %z and %y >= %z.
819 // We can't just merge %x and %y because the relationship with %z would
820 // be EQ and that's invalid. What we're doing is looking for any nodes
821 // %z such that %x <= %z and %y >= %z, and vice versa.
822 //
823 // Also handle %a <= %b and %c <= %a when adding %b <= %c.
824
825 Node *N1 = IG.node(n1);
826 Node::iterator end = N1->end();
827 for (unsigned i = 0; i < Remove.size(); ++i) {
828 Node *N = IG.node(Remove[i]);
829 Value *V = N->getValue();
830 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I) {
831 if (I->LV & EQ_BIT) {
832 if (Top == I->Subtree || Top->DominatedBy(I->Subtree)) {
833 Node::iterator NI = N1->find(I->To, Top);
834 if (NI != end) {
835 if (!(NI->LV & EQ_BIT)) return false;
836 if (isRelatedBy(V, IG.node(NI->To)->getValue(),
837 ICmpInst::ICMP_NE))
838 return false;
839 Remove.insert(NI->To);
840 }
841 }
842 }
843 }
844 }
845
846 // See if one of the nodes about to be removed is actually a better
847 // canonical choice than n1.
848 unsigned orig_n1 = n1;
849 std::vector<unsigned>::iterator DontRemove = Remove.end();
850 for (std::vector<unsigned>::iterator I = Remove.begin()+1 /* skip n2 */,
851 E = Remove.end(); I != E; ++I) {
852 unsigned n = *I;
853 Value *V = IG.node(n)->getValue();
854 if (compare(V, V1)) {
855 V1 = V;
856 n1 = n;
857 DontRemove = I;
858 }
859 }
860 if (DontRemove != Remove.end()) {
861 unsigned n = *DontRemove;
862 Remove.remove(n);
863 Remove.insert(orig_n1);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000864 }
865 }
Nick Lewycky9d17c822006-10-25 23:48:24 +0000866
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000867 // We'd like to allow makeEqual on two values to perform a simple
868 // substitution without every creating nodes in the IG whenever possible.
869 //
870 // The first iteration through this loop operates on V2 before going
871 // through the Remove list and operating on those too. If all of the
872 // iterations performed simple replacements then we exit early.
873 bool exitEarly = true;
874 unsigned i = 0;
875 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
876 if (i) R = IG.node(Remove[i])->getValue(); // skip n2.
877
878 // Try to replace the whole instruction. If we can, we're done.
879 Instruction *I2 = dyn_cast<Instruction>(R);
880 if (I2 && below(I2)) {
881 std::vector<Instruction *> ToNotify;
882 for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
883 UI != UE;) {
884 Use &TheUse = UI.getUse();
885 ++UI;
886 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser()))
887 ToNotify.push_back(I);
888 }
889
890 DOUT << "Simply removing " << *I2
891 << ", replacing with " << *V1 << "\n";
892 I2->replaceAllUsesWith(V1);
893 // leave it dead; it'll get erased later.
894 ++NumInstruction;
895 modified = true;
896
897 for (std::vector<Instruction *>::iterator II = ToNotify.begin(),
898 IE = ToNotify.end(); II != IE; ++II) {
899 opsToDef(*II);
900 }
901
902 continue;
903 }
904
905 // Otherwise, replace all dominated uses.
906 for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
907 UI != UE;) {
908 Use &TheUse = UI.getUse();
909 ++UI;
910 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
911 if (below(I)) {
912 TheUse.set(V1);
913 modified = true;
914 ++NumVarsReplaced;
915 opsToDef(I);
916 }
917 }
918 }
919
920 // If that killed the instruction, stop here.
921 if (I2 && isInstructionTriviallyDead(I2)) {
922 DOUT << "Killed all uses of " << *I2
923 << ", replacing with " << *V1 << "\n";
924 continue;
925 }
926
927 // If we make it to here, then we will need to create a node for N1.
928 // Otherwise, we can skip out early!
929 exitEarly = false;
930 }
931
932 if (exitEarly) return true;
933
934 // Create N1.
935 // XXX: this should call newNode, but instead the node might be created
936 // in isRelatedBy. That's also a fixme.
937 if (!n1) n1 = IG.getOrInsertNode(V1, Top);
938
939 // Migrate relationships from removed nodes to N1.
940 Node *N1 = IG.node(n1);
941 for (std::vector<unsigned>::iterator I = Remove.begin(), E = Remove.end();
942 I != E; ++I) {
943 unsigned n = *I;
944 Node *N = IG.node(n);
945 for (Node::iterator NI = N->begin(), NE = N->end(); NI != NE; ++NI) {
946 if (Top == NI->Subtree || NI->Subtree->DominatedBy(Top)) {
947 if (NI->To == n1) {
948 assert((NI->LV & EQ_BIT) && "Node inequal to itself.");
949 continue;
950 }
951 if (Remove.count(NI->To))
952 continue;
953
954 IG.node(NI->To)->update(n1, reversePredicate(NI->LV), Top);
955 N1->update(NI->To, NI->LV, Top);
956 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000957 }
958 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000959
960 // Point V2 (and all items in Remove) to N1.
961 if (!n2)
962 IG.addEquality(n1, V2, Top);
963 else {
964 for (std::vector<unsigned>::iterator I = Remove.begin(),
965 E = Remove.end(); I != E; ++I) {
966 IG.addEquality(n1, IG.node(*I)->getValue(), Top);
967 }
968 }
969
970 // If !Remove.empty() then V2 = Remove[0]->getValue().
971 // Even when Remove is empty, we still want to process V2.
972 i = 0;
973 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
974 if (i) R = IG.node(Remove[i])->getValue(); // skip n2.
975
976 if (Instruction *I2 = dyn_cast<Instruction>(R)) defToOps(I2);
977 for (Value::use_iterator UI = V2->use_begin(), UE = V2->use_end();
978 UI != UE;) {
979 Use &TheUse = UI.getUse();
980 ++UI;
981 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
982 opsToDef(I);
983 }
984 }
985 }
986
987 return true;
988 }
989
990 /// cmpInstToLattice - converts an CmpInst::Predicate to lattice value
991 /// Requires that the lattice value be valid; does not accept ICMP_EQ.
992 static LatticeVal cmpInstToLattice(ICmpInst::Predicate Pred) {
993 switch (Pred) {
994 case ICmpInst::ICMP_EQ:
995 assert(!"No matching lattice value.");
996 return static_cast<LatticeVal>(EQ_BIT);
997 default:
998 assert(!"Invalid 'icmp' predicate.");
999 case ICmpInst::ICMP_NE:
1000 return NE;
1001 case ICmpInst::ICMP_UGT:
1002 return SNEUGT;
1003 case ICmpInst::ICMP_UGE:
1004 return SANYUGE;
1005 case ICmpInst::ICMP_ULT:
1006 return SNEULT;
1007 case ICmpInst::ICMP_ULE:
1008 return SANYULE;
1009 case ICmpInst::ICMP_SGT:
1010 return SGTUNE;
1011 case ICmpInst::ICMP_SGE:
1012 return SGEUANY;
1013 case ICmpInst::ICMP_SLT:
1014 return SLTUNE;
1015 case ICmpInst::ICMP_SLE:
1016 return SLEUANY;
1017 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001018 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001019
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001020 public:
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001021 VRPSolver(InequalityGraph &IG, UnreachableBlocks &UB, ETForest *Forest,
1022 bool &modified, BasicBlock *TopBB)
1023 : IG(IG),
1024 UB(UB),
1025 Forest(Forest),
1026 Top(Forest->getNodeForBlock(TopBB)),
1027 TopBB(TopBB),
1028 TopInst(NULL),
1029 modified(modified) {}
Nick Lewycky9d17c822006-10-25 23:48:24 +00001030
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001031 VRPSolver(InequalityGraph &IG, UnreachableBlocks &UB, ETForest *Forest,
1032 bool &modified, Instruction *TopInst)
1033 : IG(IG),
1034 UB(UB),
1035 Forest(Forest),
1036 TopInst(TopInst),
1037 modified(modified)
1038 {
1039 TopBB = TopInst->getParent();
1040 Top = Forest->getNodeForBlock(TopBB);
1041 }
1042
1043 bool isRelatedBy(Value *V1, Value *V2, ICmpInst::Predicate Pred) const {
1044 if (Constant *C1 = dyn_cast<Constant>(V1))
1045 if (Constant *C2 = dyn_cast<Constant>(V2))
1046 return ConstantExpr::getCompare(Pred, C1, C2) ==
Zhou Sheng75b871f2007-01-11 12:24:14 +00001047 ConstantInt::getTrue();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001048
1049 // XXX: this is lousy. If we're passed a Constant, then we might miss
1050 // some relationships if it isn't in the IG because the relationships
1051 // added by initializeConstant are missing.
1052 if (isa<Constant>(V1)) IG.getOrInsertNode(V1, Top);
1053 if (isa<Constant>(V2)) IG.getOrInsertNode(V2, Top);
1054
1055 if (unsigned n1 = IG.getNode(V1, Top))
1056 if (unsigned n2 = IG.getNode(V2, Top)) {
1057 if (n1 == n2) return Pred == ICmpInst::ICMP_EQ ||
1058 Pred == ICmpInst::ICMP_ULE ||
1059 Pred == ICmpInst::ICMP_UGE ||
1060 Pred == ICmpInst::ICMP_SLE ||
1061 Pred == ICmpInst::ICMP_SGE;
1062 if (Pred == ICmpInst::ICMP_EQ) return false;
1063 return IG.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred));
1064 }
1065
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001066 return false;
1067 }
1068
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001069 /// add - adds a new property to the work queue
1070 void add(Value *V1, Value *V2, ICmpInst::Predicate Pred,
1071 Instruction *I = NULL) {
1072 DOUT << "adding " << *V1 << " " << Pred << " " << *V2;
1073 if (I) DOUT << " context: " << *I;
1074 else DOUT << " default context";
1075 DOUT << "\n";
1076
1077 WorkList.push_back(Operation());
1078 Operation &O = WorkList.back();
Nick Lewycky42944462007-01-13 02:05:28 +00001079 O.LHS = V1, O.RHS = V2, O.Op = Pred, O.ContextInst = I;
1080 O.ContextBB = I ? I->getParent() : TopBB;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001081 }
1082
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001083 /// defToOps - Given an instruction definition that we've learned something
1084 /// new about, find any new relationships between its operands.
1085 void defToOps(Instruction *I) {
1086 Instruction *NewContext = below(I) ? I : TopInst;
1087 Value *Canonical = IG.canonicalize(I, Top);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001088
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001089 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1090 const Type *Ty = BO->getType();
1091 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001092
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001093 Value *Op0 = IG.canonicalize(BO->getOperand(0), Top);
1094 Value *Op1 = IG.canonicalize(BO->getOperand(1), Top);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001095
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001096 // TODO: "and bool true, %x" EQ %y then %x EQ %y.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001097
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001098 switch (BO->getOpcode()) {
1099 case Instruction::And: {
1100 // "and int %a, %b" EQ -1 then %a EQ -1 and %b EQ -1
1101 // "and bool %a, %b" EQ true then %a EQ true and %b EQ true
Zhou Sheng75b871f2007-01-11 12:24:14 +00001102 ConstantInt *CI = ConstantInt::getAllOnesValue(Ty);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001103 if (Canonical == CI) {
1104 add(CI, Op0, ICmpInst::ICMP_EQ, NewContext);
1105 add(CI, Op1, ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001106 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001107 } break;
1108 case Instruction::Or: {
1109 // "or int %a, %b" EQ 0 then %a EQ 0 and %b EQ 0
1110 // "or bool %a, %b" EQ false then %a EQ false and %b EQ false
1111 Constant *Zero = Constant::getNullValue(Ty);
1112 if (Canonical == Zero) {
1113 add(Zero, Op0, ICmpInst::ICMP_EQ, NewContext);
1114 add(Zero, Op1, ICmpInst::ICMP_EQ, NewContext);
1115 }
1116 } break;
1117 case Instruction::Xor: {
1118 // "xor bool true, %a" EQ true then %a EQ false
1119 // "xor bool true, %a" EQ false then %a EQ true
1120 // "xor bool false, %a" EQ true then %a EQ true
1121 // "xor bool false, %a" EQ false then %a EQ false
1122 // "xor int %c, %a" EQ %c then %a EQ 0
1123 // "xor int %c, %a" NE %c then %a NE 0
1124 // 1. Repeat all of the above, with order of operands reversed.
1125 Value *LHS = Op0;
1126 Value *RHS = Op1;
1127 if (!isa<Constant>(LHS)) std::swap(LHS, RHS);
1128
Nick Lewycky4a74a752007-01-12 00:02:12 +00001129 if (ConstantInt *CI = dyn_cast<ConstantInt>(Canonical)) {
1130 if (ConstantInt *Arg = dyn_cast<ConstantInt>(LHS)) {
1131 add(RHS, ConstantInt::get(CI->getType(), CI->getZExtValue() ^
1132 Arg->getZExtValue()),
1133 ICmpInst::ICMP_EQ, NewContext);
1134 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001135 }
1136 if (Canonical == LHS) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001137 if (isa<ConstantInt>(Canonical))
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001138 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_EQ,
1139 NewContext);
1140 } else if (isRelatedBy(LHS, Canonical, ICmpInst::ICMP_NE)) {
1141 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_NE,
1142 NewContext);
1143 }
1144 } break;
1145 default:
1146 break;
1147 }
1148 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
1149 // "icmp ult int %a, int %y" EQ true then %a u< y
1150 // etc.
1151
Zhou Sheng75b871f2007-01-11 12:24:14 +00001152 if (Canonical == ConstantInt::getTrue()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001153 add(IC->getOperand(0), IC->getOperand(1), IC->getPredicate(),
1154 NewContext);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001155 } else if (Canonical == ConstantInt::getFalse()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001156 add(IC->getOperand(0), IC->getOperand(1),
1157 ICmpInst::getInversePredicate(IC->getPredicate()), NewContext);
1158 }
1159 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
1160 if (I->getType()->isFPOrFPVector()) return;
1161
1162 // Given: "%a = select bool %x, int %b, int %c"
1163 // %a EQ %b and %b NE %c then %x EQ true
1164 // %a EQ %c and %b NE %c then %x EQ false
1165
1166 Value *True = SI->getTrueValue();
1167 Value *False = SI->getFalseValue();
1168 if (isRelatedBy(True, False, ICmpInst::ICMP_NE)) {
1169 if (Canonical == IG.canonicalize(True, Top) ||
1170 isRelatedBy(Canonical, False, ICmpInst::ICMP_NE))
Zhou Sheng75b871f2007-01-11 12:24:14 +00001171 add(SI->getCondition(), ConstantInt::getTrue(),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001172 ICmpInst::ICMP_EQ, NewContext);
1173 else if (Canonical == IG.canonicalize(False, Top) ||
1174 isRelatedBy(I, True, ICmpInst::ICMP_NE))
Zhou Sheng75b871f2007-01-11 12:24:14 +00001175 add(SI->getCondition(), ConstantInt::getFalse(),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001176 ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001177 }
1178 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001179 // TODO: CastInst "%a = cast ... %b" where %a is EQ or NE a constant.
1180 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001181
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001182 /// opsToDef - A new relationship was discovered involving one of this
1183 /// instruction's operands. Find any new relationship involving the
1184 /// definition.
1185 void opsToDef(Instruction *I) {
1186 Instruction *NewContext = below(I) ? I : TopInst;
1187
1188 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1189 Value *Op0 = IG.canonicalize(BO->getOperand(0), Top);
1190 Value *Op1 = IG.canonicalize(BO->getOperand(1), Top);
1191
Zhou Sheng75b871f2007-01-11 12:24:14 +00001192 if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0))
1193 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001194 add(BO, ConstantExpr::get(BO->getOpcode(), CI0, CI1),
1195 ICmpInst::ICMP_EQ, NewContext);
1196 return;
1197 }
1198
1199 // "%y = and bool true, %x" then %x EQ %y.
1200 // "%y = or bool false, %x" then %x EQ %y.
1201 if (BO->getOpcode() == Instruction::Or) {
1202 Constant *Zero = Constant::getNullValue(BO->getType());
1203 if (Op0 == Zero) {
1204 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1205 return;
1206 } else if (Op1 == Zero) {
1207 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1208 return;
1209 }
1210 } else if (BO->getOpcode() == Instruction::And) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001211 Constant *AllOnes = ConstantInt::getAllOnesValue(BO->getType());
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001212 if (Op0 == AllOnes) {
1213 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1214 return;
1215 } else if (Op1 == AllOnes) {
1216 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1217 return;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001218 }
1219 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001220
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001221 // "%x = add int %y, %z" and %x EQ %y then %z EQ 0
1222 // "%x = mul int %y, %z" and %x EQ %y then %z EQ 1
1223 // 1. Repeat all of the above, with order of operands reversed.
1224 // "%x = udiv int %y, %z" and %x EQ %y then %z EQ 1
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001225
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001226 Value *Known = Op0, *Unknown = Op1;
1227 if (Known != BO) std::swap(Known, Unknown);
1228 if (Known == BO) {
1229 const Type *Ty = BO->getType();
1230 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001231
1232 switch (BO->getOpcode()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001233 default: break;
1234 case Instruction::Xor:
1235 case Instruction::Or:
1236 case Instruction::Add:
1237 case Instruction::Sub:
Nick Lewycky4a74a752007-01-12 00:02:12 +00001238 add(Unknown, Constant::getNullValue(Ty), ICmpInst::ICMP_EQ,
1239 NewContext);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001240 break;
1241 case Instruction::UDiv:
1242 case Instruction::SDiv:
1243 if (Unknown == Op0) break; // otherwise, fallthrough
1244 case Instruction::And:
1245 case Instruction::Mul:
Nick Lewycky4a74a752007-01-12 00:02:12 +00001246 if (isa<ConstantInt>(Unknown)) {
1247 Constant *One = ConstantInt::get(Ty, 1);
1248 add(Unknown, One, ICmpInst::ICMP_EQ, NewContext);
1249 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001250 break;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001251 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001252 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001253
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001254 // TODO: "%a = add int %b, 1" and %b > %z then %a >= %z.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001255
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001256 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
1257 // "%a = icmp ult %b, %c" and %b u< %c then %a EQ true
1258 // "%a = icmp ult %b, %c" and %b u>= %c then %a EQ false
1259 // etc.
1260
1261 Value *Op0 = IG.canonicalize(IC->getOperand(0), Top);
1262 Value *Op1 = IG.canonicalize(IC->getOperand(1), Top);
1263
1264 ICmpInst::Predicate Pred = IC->getPredicate();
1265 if (isRelatedBy(Op0, Op1, Pred)) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001266 add(IC, ConstantInt::getTrue(), ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001267 } else if (isRelatedBy(Op0, Op1, ICmpInst::getInversePredicate(Pred))) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001268 add(IC, ConstantInt::getFalse(), ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001269 }
1270
Nick Lewycky4a74a752007-01-12 00:02:12 +00001271 // TODO: "bool %x s<u> %y" implies %x = true and %y = false.
1272
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001273 // TODO: make the predicate more strict, if possible.
1274
1275 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
1276 // Given: "%a = select bool %x, int %b, int %c"
1277 // %x EQ true then %a EQ %b
1278 // %x EQ false then %a EQ %c
1279 // %b EQ %c then %a EQ %b
1280
1281 Value *Canonical = IG.canonicalize(SI->getCondition(), Top);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001282 if (Canonical == ConstantInt::getTrue()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001283 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001284 } else if (Canonical == ConstantInt::getFalse()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001285 add(SI, SI->getFalseValue(), ICmpInst::ICMP_EQ, NewContext);
1286 } else if (IG.canonicalize(SI->getTrueValue(), Top) ==
1287 IG.canonicalize(SI->getFalseValue(), Top)) {
1288 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
1289 }
Nick Lewyckyee32ee02007-01-12 01:23:53 +00001290 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
1291 if (CI->getDestTy()->isFPOrFPVector()) return;
1292
1293 if (Constant *C = dyn_cast<Constant>(
1294 IG.canonicalize(CI->getOperand(0), Top))) {
1295 add(CI, ConstantExpr::getCast(CI->getOpcode(), C, CI->getDestTy()),
1296 ICmpInst::ICMP_EQ, NewContext);
1297 }
1298
1299 // TODO: "%a = cast ... %b" where %b is NE/LT/GT a constant.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001300 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001301 }
1302
1303 /// solve - process the work queue
1304 /// Return false if a logical contradiction occurs.
1305 void solve() {
1306 //DOUT << "WorkList entry, size: " << WorkList.size() << "\n";
1307 while (!WorkList.empty()) {
1308 //DOUT << "WorkList size: " << WorkList.size() << "\n";
1309
1310 Operation &O = WorkList.front();
Nick Lewycky42944462007-01-13 02:05:28 +00001311 TopInst = O.ContextInst;
1312 TopBB = O.ContextBB;
1313 Top = Forest->getNodeForBlock(TopBB);
1314
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001315 O.LHS = IG.canonicalize(O.LHS, Top);
1316 O.RHS = IG.canonicalize(O.RHS, Top);
1317
1318 assert(O.LHS == IG.canonicalize(O.LHS, Top) && "Canonicalize isn't.");
1319 assert(O.RHS == IG.canonicalize(O.RHS, Top) && "Canonicalize isn't.");
1320
1321 DOUT << "solving " << *O.LHS << " " << O.Op << " " << *O.RHS;
Nick Lewycky42944462007-01-13 02:05:28 +00001322 if (O.ContextInst) DOUT << " context inst: " << *O.ContextInst;
1323 else DOUT << " context block: " << O.ContextBB->getName();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001324 DOUT << "\n";
1325
1326 DEBUG(IG.dump());
1327
1328 // TODO: actually check the constants and add to UB.
1329 if (isa<Constant>(O.LHS) && isa<Constant>(O.RHS)) {
1330 WorkList.pop_front();
1331 continue;
1332 }
1333
1334 if (O.Op == ICmpInst::ICMP_EQ) {
1335 if (!makeEqual(O.LHS, O.RHS))
1336 UB.mark(TopBB);
1337 } else {
1338 LatticeVal LV = cmpInstToLattice(O.Op);
1339
1340 if ((LV & EQ_BIT) &&
1341 isRelatedBy(O.LHS, O.RHS, ICmpInst::getSwappedPredicate(O.Op))) {
1342 if (!makeEqual(O.LHS, O.RHS))
1343 UB.mark(TopBB);
1344 } else {
1345 if (isRelatedBy(O.LHS, O.RHS, ICmpInst::getInversePredicate(O.Op))){
1346 DOUT << "inequality contradiction!\n";
1347 WorkList.pop_front();
1348 continue;
1349 }
1350
1351 unsigned n1 = IG.getOrInsertNode(O.LHS, Top);
1352 unsigned n2 = IG.getOrInsertNode(O.RHS, Top);
1353
1354 if (n1 == n2) {
1355 if (O.Op != ICmpInst::ICMP_UGE && O.Op != ICmpInst::ICMP_ULE &&
1356 O.Op != ICmpInst::ICMP_SGE && O.Op != ICmpInst::ICMP_SLE)
1357 UB.mark(TopBB);
1358
1359 WorkList.pop_front();
1360 continue;
1361 }
1362
1363 if (IG.isRelatedBy(n1, n2, Top, LV)) {
1364 WorkList.pop_front();
1365 continue;
1366 }
1367
1368 IG.addInequality(n1, n2, Top, LV);
1369
1370 if (Instruction *I1 = dyn_cast<Instruction>(O.LHS)) defToOps(I1);
1371 if (isa<Instruction>(O.LHS) || isa<Argument>(O.LHS)) {
1372 for (Value::use_iterator UI = O.LHS->use_begin(),
1373 UE = O.LHS->use_end(); UI != UE;) {
1374 Use &TheUse = UI.getUse();
1375 ++UI;
1376 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
1377 opsToDef(I);
1378 }
1379 }
1380 }
1381 if (Instruction *I2 = dyn_cast<Instruction>(O.RHS)) defToOps(I2);
1382 if (isa<Instruction>(O.RHS) || isa<Argument>(O.RHS)) {
1383 for (Value::use_iterator UI = O.RHS->use_begin(),
1384 UE = O.RHS->use_end(); UI != UE;) {
1385 Use &TheUse = UI.getUse();
1386 ++UI;
1387 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
1388 opsToDef(I);
1389 }
1390 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001391 }
1392 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001393 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001394 WorkList.pop_front();
Nick Lewycky9d17c822006-10-25 23:48:24 +00001395 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001396 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001397 };
1398
1399 /// PredicateSimplifier - This class is a simplifier that replaces
1400 /// one equivalent variable with another. It also tracks what
1401 /// can't be equal and will solve setcc instructions when possible.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001402 /// @brief Root of the predicate simplifier optimization.
1403 class VISIBILITY_HIDDEN PredicateSimplifier : public FunctionPass {
1404 DominatorTree *DT;
1405 ETForest *Forest;
1406 bool modified;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001407 InequalityGraph *IG;
1408 UnreachableBlocks UB;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001409
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001410 std::vector<DominatorTree::Node *> WorkList;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001411
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001412 public:
1413 bool runOnFunction(Function &F);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001414
1415 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1416 AU.addRequiredID(BreakCriticalEdgesID);
1417 AU.addRequired<DominatorTree>();
1418 AU.addRequired<ETForest>();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001419 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001420
1421 private:
Nick Lewycky77e030b2006-10-12 02:02:44 +00001422 /// Forwards - Adds new properties into PropertySet and uses them to
1423 /// simplify instructions. Because new properties sometimes apply to
1424 /// a transition from one BasicBlock to another, this will use the
1425 /// PredicateSimplifier::proceedToSuccessor(s) interface to enter the
1426 /// basic block with the new PropertySet.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001427 /// @brief Performs abstract execution of the program.
1428 class VISIBILITY_HIDDEN Forwards : public InstVisitor<Forwards> {
Nick Lewycky77e030b2006-10-12 02:02:44 +00001429 friend class InstVisitor<Forwards>;
1430 PredicateSimplifier *PS;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001431 DominatorTree::Node *DTNode;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001432
Nick Lewycky77e030b2006-10-12 02:02:44 +00001433 public:
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001434 InequalityGraph &IG;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001435 UnreachableBlocks &UB;
Nick Lewycky77e030b2006-10-12 02:02:44 +00001436
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001437 Forwards(PredicateSimplifier *PS, DominatorTree::Node *DTNode)
1438 : PS(PS), DTNode(DTNode), IG(*PS->IG), UB(PS->UB) {}
Nick Lewycky77e030b2006-10-12 02:02:44 +00001439
1440 void visitTerminatorInst(TerminatorInst &TI);
1441 void visitBranchInst(BranchInst &BI);
1442 void visitSwitchInst(SwitchInst &SI);
1443
Nick Lewyckyf3450082006-10-22 19:53:27 +00001444 void visitAllocaInst(AllocaInst &AI);
Nick Lewycky77e030b2006-10-12 02:02:44 +00001445 void visitLoadInst(LoadInst &LI);
1446 void visitStoreInst(StoreInst &SI);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001447
Nick Lewycky77e030b2006-10-12 02:02:44 +00001448 void visitBinaryOperator(BinaryOperator &BO);
1449 };
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001450
1451 // Used by terminator instructions to proceed from the current basic
1452 // block to the next. Verifies that "current" dominates "next",
1453 // then calls visitBasicBlock.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001454 void proceedToSuccessors(DominatorTree::Node *Current) {
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001455 for (DominatorTree::Node::iterator I = Current->begin(),
1456 E = Current->end(); I != E; ++I) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001457 WorkList.push_back(*I);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001458 }
1459 }
1460
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001461 void proceedToSuccessor(DominatorTree::Node *Next) {
1462 WorkList.push_back(Next);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001463 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001464
1465 // Visits each instruction in the basic block.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001466 void visitBasicBlock(DominatorTree::Node *Node) {
1467 BasicBlock *BB = Node->getBlock();
1468 ETNode *ET = Forest->getNodeForBlock(BB);
1469 DOUT << "Entering Basic Block: " << BB->getName() << " (" << ET << ")\n";
Bill Wendling22e978a2006-12-07 20:04:42 +00001470 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001471 visitInstruction(I++, Node, ET);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001472 }
1473 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001474
Nick Lewycky9a22d7b2006-09-10 02:27:07 +00001475 // Tries to simplify each Instruction and add new properties to
Nick Lewycky77e030b2006-10-12 02:02:44 +00001476 // the PropertySet.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001477 void visitInstruction(Instruction *I, DominatorTree::Node *DT, ETNode *ET) {
Bill Wendling22e978a2006-12-07 20:04:42 +00001478 DOUT << "Considering instruction " << *I << "\n";
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001479 DEBUG(IG->dump());
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001480
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001481 // Sometimes instructions are killed in earlier analysis.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001482 if (isInstructionTriviallyDead(I)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001483 ++NumSimple;
1484 modified = true;
1485 IG->remove(I);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001486 I->eraseFromParent();
1487 return;
1488 }
1489
Nick Lewycky42944462007-01-13 02:05:28 +00001490#ifndef NDEBUG
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001491 // Try to replace the whole instruction.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001492 Value *V = IG->canonicalize(I, ET);
1493 assert(V == I && "Late instruction canonicalization.");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001494 if (V != I) {
1495 modified = true;
1496 ++NumInstruction;
Bill Wendling22e978a2006-12-07 20:04:42 +00001497 DOUT << "Removing " << *I << ", replacing with " << *V << "\n";
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001498 IG->remove(I);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001499 I->replaceAllUsesWith(V);
1500 I->eraseFromParent();
1501 return;
1502 }
1503
1504 // Try to substitute operands.
1505 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1506 Value *Oper = I->getOperand(i);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001507 Value *V = IG->canonicalize(Oper, ET);
1508 assert(V == Oper && "Late operand canonicalization.");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001509 if (V != Oper) {
1510 modified = true;
1511 ++NumVarsReplaced;
Bill Wendling22e978a2006-12-07 20:04:42 +00001512 DOUT << "Resolving " << *I;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001513 I->setOperand(i, V);
Bill Wendling22e978a2006-12-07 20:04:42 +00001514 DOUT << " into " << *I;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001515 }
1516 }
Nick Lewycky42944462007-01-13 02:05:28 +00001517#endif
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001518
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001519 DOUT << "push (%" << I->getParent()->getName() << ")\n";
1520 Forwards visit(this, DT);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001521 visit.visit(*I);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001522 DOUT << "pop (%" << I->getParent()->getName() << ")\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001523 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001524 };
1525
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001526 bool PredicateSimplifier::runOnFunction(Function &F) {
1527 DT = &getAnalysis<DominatorTree>();
1528 Forest = &getAnalysis<ETForest>();
Nick Lewyckycfff1c32006-09-20 17:04:01 +00001529
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001530 Forest->updateDFSNumbers(); // XXX: should only act when numbers are out of date
1531
Bill Wendling22e978a2006-12-07 20:04:42 +00001532 DOUT << "Entering Function: " << F.getName() << "\n";
Nick Lewyckycfff1c32006-09-20 17:04:01 +00001533
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001534 modified = false;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001535 BasicBlock *RootBlock = &F.getEntryBlock();
1536 IG = new InequalityGraph(Forest->getNodeForBlock(RootBlock));
1537 WorkList.push_back(DT->getRootNode());
Nick Lewyckycfff1c32006-09-20 17:04:01 +00001538
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001539 do {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001540 DominatorTree::Node *DTNode = WorkList.back();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001541 WorkList.pop_back();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001542 if (!UB.isDead(DTNode->getBlock())) visitBasicBlock(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001543 } while (!WorkList.empty());
Nick Lewyckycfff1c32006-09-20 17:04:01 +00001544
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001545 delete IG;
1546
1547 modified |= UB.kill();
Nick Lewyckycfff1c32006-09-20 17:04:01 +00001548
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001549 return modified;
Nick Lewycky8e559932006-09-02 19:40:38 +00001550 }
1551
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001552 void PredicateSimplifier::Forwards::visitTerminatorInst(TerminatorInst &TI) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001553 PS->proceedToSuccessors(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001554 }
1555
1556 void PredicateSimplifier::Forwards::visitBranchInst(BranchInst &BI) {
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001557 if (BI.isUnconditional()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001558 PS->proceedToSuccessors(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001559 return;
1560 }
1561
1562 Value *Condition = BI.getCondition();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001563 BasicBlock *TrueDest = BI.getSuccessor(0);
1564 BasicBlock *FalseDest = BI.getSuccessor(1);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001565
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001566 if (isa<Constant>(Condition) || TrueDest == FalseDest) {
1567 PS->proceedToSuccessors(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001568 return;
1569 }
1570
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001571 for (DominatorTree::Node::iterator I = DTNode->begin(), E = DTNode->end();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001572 I != E; ++I) {
1573 BasicBlock *Dest = (*I)->getBlock();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001574 DOUT << "Branch thinking about %" << Dest->getName()
1575 << "(" << PS->Forest->getNodeForBlock(Dest) << ")\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001576
1577 if (Dest == TrueDest) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001578 DOUT << "(" << DTNode->getBlock()->getName() << ") true set:\n";
1579 VRPSolver VRP(IG, UB, PS->Forest, PS->modified, Dest);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001580 VRP.add(ConstantInt::getTrue(), Condition, ICmpInst::ICMP_EQ);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001581 VRP.solve();
1582 DEBUG(IG.dump());
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001583 } else if (Dest == FalseDest) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001584 DOUT << "(" << DTNode->getBlock()->getName() << ") false set:\n";
1585 VRPSolver VRP(IG, UB, PS->Forest, PS->modified, Dest);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001586 VRP.add(ConstantInt::getFalse(), Condition, ICmpInst::ICMP_EQ);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001587 VRP.solve();
1588 DEBUG(IG.dump());
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001589 }
1590
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001591 PS->proceedToSuccessor(*I);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001592 }
1593 }
1594
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001595 void PredicateSimplifier::Forwards::visitSwitchInst(SwitchInst &SI) {
1596 Value *Condition = SI.getCondition();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001597
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001598 // Set the EQProperty in each of the cases BBs, and the NEProperties
1599 // in the default BB.
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001600
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001601 for (DominatorTree::Node::iterator I = DTNode->begin(), E = DTNode->end();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001602 I != E; ++I) {
1603 BasicBlock *BB = (*I)->getBlock();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001604 DOUT << "Switch thinking about BB %" << BB->getName()
1605 << "(" << PS->Forest->getNodeForBlock(BB) << ")\n";
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001606
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001607 VRPSolver VRP(IG, UB, PS->Forest, PS->modified, BB);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001608 if (BB == SI.getDefaultDest()) {
1609 for (unsigned i = 1, e = SI.getNumCases(); i < e; ++i)
1610 if (SI.getSuccessor(i) != BB)
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001611 VRP.add(Condition, SI.getCaseValue(i), ICmpInst::ICMP_NE);
1612 VRP.solve();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001613 } else if (ConstantInt *CI = SI.findCaseDest(BB)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001614 VRP.add(Condition, CI, ICmpInst::ICMP_EQ);
1615 VRP.solve();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001616 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001617 PS->proceedToSuccessor(*I);
Nick Lewycky1d00f3e2006-10-03 15:19:11 +00001618 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001619 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001620
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001621 void PredicateSimplifier::Forwards::visitAllocaInst(AllocaInst &AI) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001622 VRPSolver VRP(IG, UB, PS->Forest, PS->modified, &AI);
1623 VRP.add(Constant::getNullValue(AI.getType()), &AI, ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001624 VRP.solve();
1625 }
Nick Lewyckyf3450082006-10-22 19:53:27 +00001626
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001627 void PredicateSimplifier::Forwards::visitLoadInst(LoadInst &LI) {
1628 Value *Ptr = LI.getPointerOperand();
1629 // avoid "load uint* null" -> null NE null.
1630 if (isa<Constant>(Ptr)) return;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001631
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001632 VRPSolver VRP(IG, UB, PS->Forest, PS->modified, &LI);
1633 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001634 VRP.solve();
1635 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001636
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001637 void PredicateSimplifier::Forwards::visitStoreInst(StoreInst &SI) {
1638 Value *Ptr = SI.getPointerOperand();
1639 if (isa<Constant>(Ptr)) return;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001640
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001641 VRPSolver VRP(IG, UB, PS->Forest, PS->modified, &SI);
1642 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001643 VRP.solve();
1644 }
1645
1646 void PredicateSimplifier::Forwards::visitBinaryOperator(BinaryOperator &BO) {
1647 Instruction::BinaryOps ops = BO.getOpcode();
1648
1649 switch (ops) {
Reid Spencer7eb55b32006-11-02 01:53:59 +00001650 case Instruction::URem:
1651 case Instruction::SRem:
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001652 case Instruction::UDiv:
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001653 case Instruction::SDiv: {
Nick Lewycky77e030b2006-10-12 02:02:44 +00001654 Value *Divisor = BO.getOperand(1);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001655 VRPSolver VRP(IG, UB, PS->Forest, PS->modified, &BO);
1656 VRP.add(Constant::getNullValue(Divisor->getType()), Divisor,
1657 ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001658 VRP.solve();
Nick Lewycky5f8f9af2006-08-30 02:46:48 +00001659 break;
1660 }
1661 default:
1662 break;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001663 }
Nick Lewycky5f8f9af2006-08-30 02:46:48 +00001664 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001665
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001666 RegisterPass<PredicateSimplifier> X("predsimplify",
1667 "Predicate Simplifier");
1668}
1669
1670FunctionPass *llvm::createPredicateSimplifierPass() {
1671 return new PredicateSimplifier();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00001672}