blob: 85cec561072c9a1d47cebd2a44766acb6f2018bb [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 Lewycky4f73de22007-03-16 02:37:39 +000025// The InequalityGraph focusses on four properties; equals, not equals,
26// less-than and less-than-or-equals-to. The greater-than forms are also held
27// just to allow walking from a lesser node to a greater one. These properties
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000028// 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
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +000032// is how EQ relationships are stored; the map contains pointers from equal
33// Value to the same node. The node contains a most canonical Value* form
34// and the list of known relationships with other nodes.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000035//
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//
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +000055// %P = icmp ne i32* %ptr, null
56// %a = and i1 %P, %Q
57// br i1 %a label %cond_true, label %cond_false
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000058//
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
Nick Lewycky56639802007-01-29 02:56:54 +000062// branch it can't infer anything from the "and" instruction.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000063//
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 Lewycky4f73de22007-03-16 02:37:39 +000070//
71// The ValueRanges class stores the known integer bounds of a Value. When we
72// encounter i8 %a u< %b, the ValueRanges stores that %a = [1, 255] and
73// %b = [0, 254]. Because we store these by Value*, you should always
74// canonicalize through the InequalityGraph first.
75//
76// It never stores an empty range, because that means that the code is
77// unreachable. It never stores a single-element range since that's an equality
Nick Lewycky12d44ab2007-04-07 03:16:12 +000078// relationship and better stored in the InequalityGraph, nor an empty range
79// since that is better stored in UnreachableBlocks.
Nick Lewycky4f73de22007-03-16 02:37:39 +000080//
81//===----------------------------------------------------------------------===//
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000082
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000083#define DEBUG_TYPE "predsimplify"
84#include "llvm/Transforms/Scalar.h"
85#include "llvm/Constants.h"
Nick Lewyckyf3450082006-10-22 19:53:27 +000086#include "llvm/DerivedTypes.h"
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000087#include "llvm/Instructions.h"
88#include "llvm/Pass.h"
Nick Lewycky2fc338f2007-01-11 02:32:38 +000089#include "llvm/ADT/DepthFirstIterator.h"
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000090#include "llvm/ADT/SetOperations.h"
Reid Spencer3f4e6e82007-02-04 00:40:42 +000091#include "llvm/ADT/SetVector.h"
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000092#include "llvm/ADT/Statistic.h"
93#include "llvm/ADT/STLExtras.h"
94#include "llvm/Analysis/Dominators.h"
95#include "llvm/Support/CFG.h"
Chris Lattnerf06bb652006-12-06 18:14:47 +000096#include "llvm/Support/Compiler.h"
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +000097#include "llvm/Support/ConstantRange.h"
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000098#include "llvm/Support/Debug.h"
Nick Lewycky77e030b2006-10-12 02:02:44 +000099#include "llvm/Support/InstVisitor.h"
Nick Lewycky12d44ab2007-04-07 03:16:12 +0000100#include "llvm/Target/TargetData.h"
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000101#include "llvm/Transforms/Utils/Local.h"
102#include <algorithm>
103#include <deque>
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000104#include <sstream>
Nick Lewycky26e25d32007-06-24 04:36:20 +0000105#include <stack>
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000106using namespace llvm;
107
Chris Lattner0e5255b2006-12-19 21:49:03 +0000108STATISTIC(NumVarsReplaced, "Number of argument substitutions");
109STATISTIC(NumInstruction , "Number of instructions removed");
110STATISTIC(NumSimple , "Number of simple replacements");
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000111STATISTIC(NumBlocks , "Number of blocks marked unreachable");
Nick Lewycky4f73de22007-03-16 02:37:39 +0000112STATISTIC(NumSnuggle , "Number of comparisons snuggled");
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000113
Chris Lattner0e5255b2006-12-19 21:49:03 +0000114namespace {
Nick Lewycky26e25d32007-06-24 04:36:20 +0000115 class DomTreeDFS {
116 public:
117 class Node {
118 friend class DomTreeDFS;
119 public:
120 typedef std::vector<Node *>::iterator iterator;
121 typedef std::vector<Node *>::const_iterator const_iterator;
122
123 unsigned getDFSNumIn() const { return DFSin; }
124 unsigned getDFSNumOut() const { return DFSout; }
125
126 BasicBlock *getBlock() const { return BB; }
127
128 iterator begin() { return Children.begin(); }
129 iterator end() { return Children.end(); }
130
131 const_iterator begin() const { return Children.begin(); }
132 const_iterator end() const { return Children.end(); }
133
134 bool dominates(const Node *N) const {
135 return DFSin <= N->DFSin && DFSout >= N->DFSout;
136 }
137
138 bool DominatedBy(const Node *N) const {
139 return N->dominates(this);
140 }
141
142 /// Sorts by the number of descendants. With this, you can iterate
143 /// through a sorted list and the first matching entry is the most
144 /// specific match for your basic block. The order provided is stable;
145 /// DomTreeDFS::Nodes with the same number of descendants are sorted by
146 /// DFS in number.
147 bool operator<(const Node &N) const {
148 unsigned spread = DFSout - DFSin;
149 unsigned N_spread = N.DFSout - N.DFSin;
150 if (spread == N_spread) return DFSin < N.DFSin;
151 else return DFSout - DFSin < N.DFSout - N.DFSin;
152 }
153 bool operator>(const Node &N) const { return N < *this; }
154
155 private:
156 unsigned DFSin, DFSout;
157 BasicBlock *BB;
158
159 std::vector<Node *> Children;
160 };
161
162 // XXX: this may be slow. Instead of using "new" for each node, consider
163 // putting them in a vector to keep them contiguous.
164 explicit DomTreeDFS(DominatorTree *DT) {
165 std::stack<std::pair<Node *, DomTreeNode *> > S;
166
167 Entry = new Node;
168 Entry->BB = DT->getRootNode()->getBlock();
169 S.push(std::make_pair(Entry, DT->getRootNode()));
170
171 NodeMap[Entry->BB] = Entry;
172
173 while (!S.empty()) {
174 std::pair<Node *, DomTreeNode *> &Pair = S.top();
175 Node *N = Pair.first;
176 DomTreeNode *DTNode = Pair.second;
177 S.pop();
178
179 for (DomTreeNode::iterator I = DTNode->begin(), E = DTNode->end();
180 I != E; ++I) {
181 Node *NewNode = new Node;
182 NewNode->BB = (*I)->getBlock();
183 N->Children.push_back(NewNode);
184 S.push(std::make_pair(NewNode, *I));
185
186 NodeMap[NewNode->BB] = NewNode;
187 }
188 }
189
190 renumber();
191
192#ifndef NDEBUG
193 DEBUG(dump());
194#endif
195 }
196
197#ifndef NDEBUG
198 virtual
199#endif
200 ~DomTreeDFS() {
201 std::stack<Node *> S;
202
203 S.push(Entry);
204 while (!S.empty()) {
205 Node *N = S.top(); S.pop();
206
207 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I)
208 S.push(*I);
209
210 delete N;
211 }
212 }
213
214 Node *getRootNode() const { return Entry; }
215
216 Node *getNodeForBlock(BasicBlock *BB) const {
217 if (!NodeMap.count(BB)) return 0;
218 else return const_cast<DomTreeDFS*>(this)->NodeMap[BB];
219 }
220
221 bool dominates(Instruction *I1, Instruction *I2) {
222 BasicBlock *BB1 = I1->getParent(),
223 *BB2 = I2->getParent();
224 if (BB1 == BB2) {
225 if (isa<TerminatorInst>(I1)) return false;
226 if (isa<TerminatorInst>(I2)) return true;
227 if ( isa<PHINode>(I1) && !isa<PHINode>(I2)) return true;
228 if (!isa<PHINode>(I1) && isa<PHINode>(I2)) return false;
229
230 for (BasicBlock::const_iterator I = BB2->begin(), E = BB2->end();
231 I != E; ++I) {
232 if (&*I == I1) return true;
233 else if (&*I == I2) return false;
234 }
235 assert(!"Instructions not found in parent BasicBlock?");
236 } else {
237 Node *Node1 = getNodeForBlock(BB1),
238 *Node2 = getNodeForBlock(BB2);
239 if (!Node1 || !Node2) return false;
240 return Node1->dominates(Node2);
241 }
242 }
243 private:
244 void renumber() {
245 std::stack<std::pair<Node *, Node::iterator> > S;
246 unsigned n = 0;
247
248 Entry->DFSin = ++n;
249 S.push(std::make_pair(Entry, Entry->begin()));
250
251 while (!S.empty()) {
252 std::pair<Node *, Node::iterator> &Pair = S.top();
253 Node *N = Pair.first;
254 Node::iterator &I = Pair.second;
255
256 if (I == N->end()) {
257 N->DFSout = ++n;
258 S.pop();
259 } else {
260 Node *Next = *I++;
261 Next->DFSin = ++n;
262 S.push(std::make_pair(Next, Next->begin()));
263 }
264 }
265 }
266
267#ifndef NDEBUG
268 virtual void dump() const {
269 dump(*cerr.stream());
270 }
271
272 void dump(std::ostream &os) const {
273 os << "Predicate simplifier DomTreeDFS: \n";
274 dump(Entry, 0, os);
275 os << "\n\n";
276 }
277
278 void dump(Node *N, int depth, std::ostream &os) const {
279 ++depth;
280 for (int i = 0; i < depth; ++i) { os << " "; }
281 os << "[" << depth << "] ";
282
283 os << N->getBlock()->getName() << " (" << N->getDFSNumIn()
284 << ", " << N->getDFSNumOut() << ")\n";
285
286 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I)
287 dump(*I, depth, os);
288 }
289#endif
290
291 Node *Entry;
292 std::map<BasicBlock *, Node *> NodeMap;
293 };
294
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000295 // SLT SGT ULT UGT EQ
296 // 0 1 0 1 0 -- GT 10
297 // 0 1 0 1 1 -- GE 11
298 // 0 1 1 0 0 -- SGTULT 12
299 // 0 1 1 0 1 -- SGEULE 13
Nick Lewycky56639802007-01-29 02:56:54 +0000300 // 0 1 1 1 0 -- SGT 14
301 // 0 1 1 1 1 -- SGE 15
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000302 // 1 0 0 1 0 -- SLTUGT 18
303 // 1 0 0 1 1 -- SLEUGE 19
304 // 1 0 1 0 0 -- LT 20
305 // 1 0 1 0 1 -- LE 21
Nick Lewycky56639802007-01-29 02:56:54 +0000306 // 1 0 1 1 0 -- SLT 22
307 // 1 0 1 1 1 -- SLE 23
308 // 1 1 0 1 0 -- UGT 26
309 // 1 1 0 1 1 -- UGE 27
310 // 1 1 1 0 0 -- ULT 28
311 // 1 1 1 0 1 -- ULE 29
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000312 // 1 1 1 1 0 -- NE 30
313 enum LatticeBits {
314 EQ_BIT = 1, UGT_BIT = 2, ULT_BIT = 4, SGT_BIT = 8, SLT_BIT = 16
315 };
316 enum LatticeVal {
317 GT = SGT_BIT | UGT_BIT,
318 GE = GT | EQ_BIT,
319 LT = SLT_BIT | ULT_BIT,
320 LE = LT | EQ_BIT,
321 NE = SLT_BIT | SGT_BIT | ULT_BIT | UGT_BIT,
322 SGTULT = SGT_BIT | ULT_BIT,
323 SGEULE = SGTULT | EQ_BIT,
324 SLTUGT = SLT_BIT | UGT_BIT,
325 SLEUGE = SLTUGT | EQ_BIT,
Nick Lewycky56639802007-01-29 02:56:54 +0000326 ULT = SLT_BIT | SGT_BIT | ULT_BIT,
327 UGT = SLT_BIT | SGT_BIT | UGT_BIT,
328 SLT = SLT_BIT | ULT_BIT | UGT_BIT,
329 SGT = SGT_BIT | ULT_BIT | UGT_BIT,
330 SLE = SLT | EQ_BIT,
331 SGE = SGT | EQ_BIT,
332 ULE = ULT | EQ_BIT,
333 UGE = UGT | EQ_BIT
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000334 };
335
336 static bool validPredicate(LatticeVal LV) {
337 switch (LV) {
Nick Lewycky15245952007-02-04 23:43:05 +0000338 case GT: case GE: case LT: case LE: case NE:
339 case SGTULT: case SGT: case SGEULE:
340 case SLTUGT: case SLT: case SLEUGE:
341 case ULT: case UGT:
342 case SLE: case SGE: case ULE: case UGE:
343 return true;
344 default:
345 return false;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000346 }
347 }
348
349 /// reversePredicate - reverse the direction of the inequality
350 static LatticeVal reversePredicate(LatticeVal LV) {
351 unsigned reverse = LV ^ (SLT_BIT|SGT_BIT|ULT_BIT|UGT_BIT); //preserve EQ_BIT
Nick Lewycky4f73de22007-03-16 02:37:39 +0000352
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000353 if ((reverse & (SLT_BIT|SGT_BIT)) == 0)
354 reverse |= (SLT_BIT|SGT_BIT);
355
356 if ((reverse & (ULT_BIT|UGT_BIT)) == 0)
357 reverse |= (ULT_BIT|UGT_BIT);
358
359 LatticeVal Rev = static_cast<LatticeVal>(reverse);
360 assert(validPredicate(Rev) && "Failed reversing predicate.");
361 return Rev;
362 }
363
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000364 /// The InequalityGraph stores the relationships between values.
365 /// Each Value in the graph is assigned to a Node. Nodes are pointer
366 /// comparable for equality. The caller is expected to maintain the logical
367 /// consistency of the system.
368 ///
369 /// The InequalityGraph class may invalidate Node*s after any mutator call.
370 /// @brief The InequalityGraph stores the relationships between values.
371 class VISIBILITY_HIDDEN InequalityGraph {
Nick Lewycky26e25d32007-06-24 04:36:20 +0000372 DomTreeDFS::Node *TreeRoot;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000373
374 InequalityGraph(); // DO NOT IMPLEMENT
375 InequalityGraph(InequalityGraph &); // DO NOT IMPLEMENT
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000376 public:
Nick Lewycky26e25d32007-06-24 04:36:20 +0000377 explicit InequalityGraph(DomTreeDFS::Node *TreeRoot) : TreeRoot(TreeRoot){}
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000378
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000379 class Node;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000380
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000381 /// An Edge is contained inside a Node making one end of the edge implicit
382 /// and contains a pointer to the other end. The edge contains a lattice
Nick Lewycky26e25d32007-06-24 04:36:20 +0000383 /// value specifying the relationship and an DomTreeDFS::Node specifying
384 /// the root in the dominator tree to which this edge applies.
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000385 class VISIBILITY_HIDDEN Edge {
386 public:
Nick Lewycky26e25d32007-06-24 04:36:20 +0000387 Edge(unsigned T, LatticeVal V, DomTreeDFS::Node *ST)
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000388 : To(T), LV(V), Subtree(ST) {}
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000389
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000390 unsigned To;
391 LatticeVal LV;
Nick Lewycky26e25d32007-06-24 04:36:20 +0000392 DomTreeDFS::Node *Subtree;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000393
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000394 bool operator<(const Edge &edge) const {
395 if (To != edge.To) return To < edge.To;
Nick Lewycky26e25d32007-06-24 04:36:20 +0000396 else return *Subtree < *edge.Subtree;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000397 }
Nick Lewycky26e25d32007-06-24 04:36:20 +0000398
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000399 bool operator<(unsigned to) const {
400 return To < to;
401 }
Nick Lewycky26e25d32007-06-24 04:36:20 +0000402
Bill Wendling6357bf22007-06-04 23:52:59 +0000403 bool operator>(unsigned to) const {
404 return To > to;
405 }
406
407 friend bool operator<(unsigned to, const Edge &edge) {
408 return edge.operator>(to);
409 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000410 };
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000411
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000412 /// A single node in the InequalityGraph. This stores the canonical Value
413 /// for the node, as well as the relationships with the neighbours.
414 ///
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000415 /// @brief A single node in the InequalityGraph.
416 class VISIBILITY_HIDDEN Node {
417 friend class InequalityGraph;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000418
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000419 typedef SmallVector<Edge, 4> RelationsType;
420 RelationsType Relations;
421
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000422 Value *Canonical;
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000423
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000424 // TODO: can this idea improve performance?
425 //friend class std::vector<Node>;
426 //Node(Node &N) { RelationsType.swap(N.RelationsType); }
427
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000428 public:
429 typedef RelationsType::iterator iterator;
430 typedef RelationsType::const_iterator const_iterator;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000431
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000432 Node(Value *V) : Canonical(V) {}
433
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000434 private:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000435#ifndef NDEBUG
436 public:
Nick Lewycky5d6ede52007-01-11 02:38:21 +0000437 virtual ~Node() {}
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000438 virtual void dump() const {
439 dump(*cerr.stream());
440 }
441 private:
442 void dump(std::ostream &os) const {
443 os << *getValue() << ":\n";
444 for (Node::const_iterator NI = begin(), NE = end(); NI != NE; ++NI) {
445 static const std::string names[32] =
446 { "000000", "000001", "000002", "000003", "000004", "000005",
447 "000006", "000007", "000008", "000009", " >", " >=",
448 " s>u<", "s>=u<=", " s>", " s>=", "000016", "000017",
449 " s<u>", "s<=u>=", " <", " <=", " s<", " s<=",
450 "000024", "000025", " u>", " u>=", " u<", " u<=",
451 " !=", "000031" };
452 os << " " << names[NI->LV] << " " << NI->To
Nick Lewycky6ce36cf2007-01-15 14:30:07 +0000453 << " (" << NI->Subtree->getDFSNumIn() << ")\n";
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000454 }
455 }
456#endif
457
458 public:
459 iterator begin() { return Relations.begin(); }
460 iterator end() { return Relations.end(); }
461 const_iterator begin() const { return Relations.begin(); }
462 const_iterator end() const { return Relations.end(); }
463
Nick Lewycky26e25d32007-06-24 04:36:20 +0000464 iterator find(unsigned n, DomTreeDFS::Node *Subtree) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000465 iterator E = end();
466 for (iterator I = std::lower_bound(begin(), E, n);
467 I != E && I->To == n; ++I) {
468 if (Subtree->DominatedBy(I->Subtree))
469 return I;
470 }
471 return E;
472 }
473
Nick Lewycky26e25d32007-06-24 04:36:20 +0000474 const_iterator find(unsigned n, DomTreeDFS::Node *Subtree) const {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000475 const_iterator E = end();
476 for (const_iterator I = std::lower_bound(begin(), E, n);
477 I != E && I->To == n; ++I) {
478 if (Subtree->DominatedBy(I->Subtree))
479 return I;
480 }
481 return E;
482 }
483
484 Value *getValue() const
485 {
486 return Canonical;
487 }
488
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000489 /// Updates the lattice value for a given node. Create a new entry if
490 /// one doesn't exist, otherwise it merges the values. The new lattice
491 /// value must not be inconsistent with any previously existing value.
Nick Lewycky26e25d32007-06-24 04:36:20 +0000492 void update(unsigned n, LatticeVal R, DomTreeDFS::Node *Subtree) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000493 assert(validPredicate(R) && "Invalid predicate.");
494 iterator I = find(n, Subtree);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000495 if (I == end()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000496 Edge edge(n, R, Subtree);
497 iterator Insert = std::lower_bound(begin(), end(), edge);
498 Relations.insert(Insert, edge);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000499 } else {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000500 LatticeVal LV = static_cast<LatticeVal>(I->LV & R);
501 assert(validPredicate(LV) && "Invalid union of lattice values.");
502 if (LV != I->LV) {
Nick Lewycky6ce36cf2007-01-15 14:30:07 +0000503 if (Subtree != I->Subtree) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000504 assert(Subtree->DominatedBy(I->Subtree) &&
505 "Find returned subtree that doesn't apply.");
506
507 Edge edge(n, R, Subtree);
508 iterator Insert = std::lower_bound(begin(), end(), edge);
Nick Lewycky6ce36cf2007-01-15 14:30:07 +0000509 Relations.insert(Insert, edge); // invalidates I
510 I = find(n, Subtree);
511 }
512
513 // Also, we have to tighten any edge that Subtree dominates.
514 for (iterator B = begin(); I->To == n; --I) {
515 if (I->Subtree->DominatedBy(Subtree)) {
516 LatticeVal LV = static_cast<LatticeVal>(I->LV & R);
Chris Lattner28d921d2007-04-14 23:32:02 +0000517 assert(validPredicate(LV) && "Invalid union of lattice values");
Nick Lewycky6ce36cf2007-01-15 14:30:07 +0000518 I->LV = LV;
519 }
520 if (I == B) break;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000521 }
522 }
Nick Lewycky51ce8d62006-09-13 19:24:01 +0000523 }
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000524 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000525 };
526
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000527 private:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000528 struct VISIBILITY_HIDDEN NodeMapEdge {
529 Value *V;
530 unsigned index;
Nick Lewycky26e25d32007-06-24 04:36:20 +0000531 DomTreeDFS::Node *Subtree;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000532
Nick Lewycky26e25d32007-06-24 04:36:20 +0000533 NodeMapEdge(Value *V, unsigned index, DomTreeDFS::Node *Subtree)
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000534 : V(V), index(index), Subtree(Subtree) {}
535
536 bool operator==(const NodeMapEdge &RHS) const {
537 return V == RHS.V &&
538 Subtree == RHS.Subtree;
539 }
540
541 bool operator<(const NodeMapEdge &RHS) const {
542 if (V != RHS.V) return V < RHS.V;
Nick Lewycky26e25d32007-06-24 04:36:20 +0000543 else return *Subtree < *RHS.Subtree;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000544 }
545
546 bool operator<(Value *RHS) const {
547 return V < RHS;
548 }
549 };
550
551 typedef std::vector<NodeMapEdge> NodeMapType;
552 NodeMapType NodeMap;
553
554 std::vector<Node> Nodes;
555
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000556 public:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000557 /// node - returns the node object at a given index retrieved from getNode.
558 /// Index zero is reserved and may not be passed in here. The pointer
559 /// returned is valid until the next call to newNode or getOrInsertNode.
560 Node *node(unsigned index) {
561 assert(index != 0 && "Zero index is reserved for not found.");
562 assert(index <= Nodes.size() && "Index out of range.");
563 return &Nodes[index-1];
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000564 }
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000565
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000566 /// Returns the node currently representing Value V, or zero if no such
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000567 /// node exists.
Nick Lewycky26e25d32007-06-24 04:36:20 +0000568 unsigned getNode(Value *V, DomTreeDFS::Node *Subtree) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000569 NodeMapType::iterator E = NodeMap.end();
570 NodeMapEdge Edge(V, 0, Subtree);
571 NodeMapType::iterator I = std::lower_bound(NodeMap.begin(), E, Edge);
572 while (I != E && I->V == V) {
573 if (Subtree->DominatedBy(I->Subtree))
574 return I->index;
575 ++I;
576 }
577 return 0;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000578 }
579
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000580 /// getOrInsertNode - always returns a valid node index, creating a node
581 /// to match the Value if needed.
Nick Lewycky26e25d32007-06-24 04:36:20 +0000582 unsigned getOrInsertNode(Value *V, DomTreeDFS::Node *Subtree) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000583 if (unsigned n = getNode(V, Subtree))
584 return n;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000585 else
586 return newNode(V);
587 }
588
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000589 /// newNode - creates a new node for a given Value and returns the index.
590 unsigned newNode(Value *V) {
Nick Lewycky26e25d32007-06-24 04:36:20 +0000591 assert(!isa<BasicBlock>(V) && "BBs may not be nodes.");
592 assert(V->getType() != Type::VoidTy && "Void node?");
593
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000594 Nodes.push_back(Node(V));
595
596 NodeMapEdge MapEntry = NodeMapEdge(V, Nodes.size(), TreeRoot);
597 assert(!std::binary_search(NodeMap.begin(), NodeMap.end(), MapEntry) &&
598 "Attempt to create a duplicate Node.");
599 NodeMap.insert(std::lower_bound(NodeMap.begin(), NodeMap.end(),
600 MapEntry), MapEntry);
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000601 return MapEntry.index;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000602 }
603
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000604 /// If the Value is in the graph, return the canonical form. Otherwise,
605 /// return the original Value.
Nick Lewycky26e25d32007-06-24 04:36:20 +0000606 Value *canonicalize(Value *V, DomTreeDFS::Node *Subtree) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000607 if (isa<Constant>(V)) return V;
608
609 if (unsigned n = getNode(V, Subtree))
610 return node(n)->getValue();
611 else
612 return V;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000613 }
614
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000615 /// isRelatedBy - true iff n1 op n2
Nick Lewycky26e25d32007-06-24 04:36:20 +0000616 bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
617 LatticeVal LV) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000618 if (n1 == n2) return LV & EQ_BIT;
619
620 Node *N1 = node(n1);
621 Node::iterator I = N1->find(n2, Subtree), E = N1->end();
622 if (I != E) return (I->LV & LV) == I->LV;
623
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000624 return false;
625 }
626
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000627 // The add* methods assume that your input is logically valid and may
628 // assertion-fail or infinitely loop if you attempt a contradiction.
Nick Lewycky9d17c822006-10-25 23:48:24 +0000629
Nick Lewycky26e25d32007-06-24 04:36:20 +0000630 void addEquality(unsigned n, Value *V, DomTreeDFS::Node *Subtree) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000631 assert(canonicalize(node(n)->getValue(), Subtree) == node(n)->getValue()
632 && "Node's 'canonical' choice isn't best within this subtree.");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000633
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000634 // Suppose that we are given "%x -> node #1 (%y)". The problem is that
635 // we may already have "%z -> node #2 (%x)" somewhere above us in the
636 // graph. We need to find those edges and add "%z -> node #1 (%y)"
637 // to keep the lookups canonical.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000638
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000639 std::vector<Value *> ToRepoint;
640 ToRepoint.push_back(V);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000641
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000642 if (unsigned Conflict = getNode(V, Subtree)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000643 for (NodeMapType::iterator I = NodeMap.begin(), E = NodeMap.end();
644 I != E; ++I) {
645 if (I->index == Conflict && Subtree->DominatedBy(I->Subtree))
646 ToRepoint.push_back(I->V);
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000647 }
648 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000649
650 for (std::vector<Value *>::iterator VI = ToRepoint.begin(),
651 VE = ToRepoint.end(); VI != VE; ++VI) {
652 Value *V = *VI;
653
654 // XXX: review this code. This may be doing too many insertions.
655 NodeMapEdge Edge(V, n, Subtree);
656 NodeMapType::iterator E = NodeMap.end();
657 NodeMapType::iterator I = std::lower_bound(NodeMap.begin(), E, Edge);
658 if (I == E || I->V != V || I->Subtree != Subtree) {
659 // New Value
660 NodeMap.insert(I, Edge);
661 } else if (I != E && I->V == V && I->Subtree == Subtree) {
662 // Update best choice
663 I->index = n;
664 }
665
666#ifndef NDEBUG
667 Node *N = node(n);
668 if (isa<Constant>(V)) {
669 if (isa<Constant>(N->getValue())) {
670 assert(V == N->getValue() && "Constant equals different constant?");
671 }
672 }
673#endif
674 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000675 }
676
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000677 /// addInequality - Sets n1 op n2.
678 /// It is also an error to call this on an inequality that is already true.
Nick Lewycky26e25d32007-06-24 04:36:20 +0000679 void addInequality(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000680 LatticeVal LV1) {
681 assert(n1 != n2 && "A node can't be inequal to itself.");
682
683 if (LV1 != NE)
684 assert(!isRelatedBy(n1, n2, Subtree, reversePredicate(LV1)) &&
685 "Contradictory inequality.");
686
687 Node *N1 = node(n1);
688 Node *N2 = node(n2);
689
690 // Suppose we're adding %n1 < %n2. Find all the %a < %n1 and
691 // add %a < %n2 too. This keeps the graph fully connected.
692 if (LV1 != NE) {
Nick Lewycky3bb6de82007-04-07 03:36:51 +0000693 // Break up the relationship into signed and unsigned comparison parts.
694 // If the signed parts of %a op1 %n1 match that of %n1 op2 %n2, and
695 // op1 and op2 aren't NE, then add %a op3 %n2. The new relationship
696 // should have the EQ_BIT iff it's set for both op1 and op2.
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000697
698 unsigned LV1_s = LV1 & (SLT_BIT|SGT_BIT);
699 unsigned LV1_u = LV1 & (ULT_BIT|UGT_BIT);
Nick Lewycky3bb6de82007-04-07 03:36:51 +0000700
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000701 for (Node::iterator I = N1->begin(), E = N1->end(); I != E; ++I) {
702 if (I->LV != NE && I->To != n2) {
Nick Lewycky3bb6de82007-04-07 03:36:51 +0000703
Nick Lewycky26e25d32007-06-24 04:36:20 +0000704 DomTreeDFS::Node *Local_Subtree = NULL;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000705 if (Subtree->DominatedBy(I->Subtree))
706 Local_Subtree = Subtree;
707 else if (I->Subtree->DominatedBy(Subtree))
708 Local_Subtree = I->Subtree;
709
710 if (Local_Subtree) {
711 unsigned new_relationship = 0;
712 LatticeVal ILV = reversePredicate(I->LV);
713 unsigned ILV_s = ILV & (SLT_BIT|SGT_BIT);
714 unsigned ILV_u = ILV & (ULT_BIT|UGT_BIT);
715
716 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
717 new_relationship |= ILV_s;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000718 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
719 new_relationship |= ILV_u;
720
721 if (new_relationship) {
722 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
723 new_relationship |= (SLT_BIT|SGT_BIT);
724 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
725 new_relationship |= (ULT_BIT|UGT_BIT);
726 if ((LV1 & EQ_BIT) && (ILV & EQ_BIT))
727 new_relationship |= EQ_BIT;
728
729 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
730
731 node(I->To)->update(n2, NewLV, Local_Subtree);
732 N2->update(I->To, reversePredicate(NewLV), Local_Subtree);
733 }
734 }
735 }
736 }
737
738 for (Node::iterator I = N2->begin(), E = N2->end(); I != E; ++I) {
739 if (I->LV != NE && I->To != n1) {
Nick Lewycky26e25d32007-06-24 04:36:20 +0000740 DomTreeDFS::Node *Local_Subtree = NULL;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000741 if (Subtree->DominatedBy(I->Subtree))
742 Local_Subtree = Subtree;
743 else if (I->Subtree->DominatedBy(Subtree))
744 Local_Subtree = I->Subtree;
745
746 if (Local_Subtree) {
747 unsigned new_relationship = 0;
748 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
749 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
750
751 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
752 new_relationship |= ILV_s;
753
754 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
755 new_relationship |= ILV_u;
756
757 if (new_relationship) {
758 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
759 new_relationship |= (SLT_BIT|SGT_BIT);
760 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
761 new_relationship |= (ULT_BIT|UGT_BIT);
762 if ((LV1 & EQ_BIT) && (I->LV & EQ_BIT))
763 new_relationship |= EQ_BIT;
764
765 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
766
767 N1->update(I->To, NewLV, Local_Subtree);
768 node(I->To)->update(n1, reversePredicate(NewLV), Local_Subtree);
769 }
770 }
771 }
772 }
773 }
774
775 N1->update(n2, LV1, Subtree);
776 N2->update(n1, reversePredicate(LV1), Subtree);
777 }
Nick Lewycky51ce8d62006-09-13 19:24:01 +0000778
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000779 /// remove - Removes a Value from the graph. If the value is the canonical
780 /// choice for a Node, destroys the Node from the graph deleting all edges
781 /// to and from it. This method does not renumber the nodes.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000782 void remove(Value *V) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000783 for (unsigned i = 0; i < NodeMap.size();) {
784 NodeMapType::iterator I = NodeMap.begin()+i;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000785 if (I->V == V) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000786 Node *N = node(I->index);
787 if (node(I->index)->getValue() == V) {
788 for (Node::iterator NI = N->begin(), NE = N->end(); NI != NE; ++NI){
789 Node::iterator Iter = node(NI->To)->find(I->index, TreeRoot);
790 do {
791 node(NI->To)->Relations.erase(Iter);
792 Iter = node(NI->To)->find(I->index, TreeRoot);
793 } while (Iter != node(NI->To)->end());
794 }
795 N->Canonical = NULL;
796 }
797 N->Relations.clear();
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000798 NodeMap.erase(I);
799 } else ++i;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000800 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000801 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000802
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000803#ifndef NDEBUG
Nick Lewycky5d6ede52007-01-11 02:38:21 +0000804 virtual ~InequalityGraph() {}
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000805 virtual void dump() {
806 dump(*cerr.stream());
807 }
808
809 void dump(std::ostream &os) {
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000810 std::set<Node *> VisitedNodes;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000811 for (NodeMapType::const_iterator I = NodeMap.begin(), E = NodeMap.end();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000812 I != E; ++I) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000813 Node *N = node(I->index);
Nick Lewycky6ce36cf2007-01-15 14:30:07 +0000814 os << *I->V << " == " << I->index
815 << "(" << I->Subtree->getDFSNumIn() << ")\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000816 if (VisitedNodes.insert(N).second) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000817 os << I->index << ". ";
818 if (!N->getValue()) os << "(deleted node)\n";
819 else N->dump(os);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000820 }
821 }
822 }
823#endif
824 };
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000825
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000826 class VRPSolver;
827
828 /// ValueRanges tracks the known integer ranges and anti-ranges of the nodes
829 /// in the InequalityGraph.
830 class VISIBILITY_HIDDEN ValueRanges {
831
832 /// A ScopedRange ties an InequalityGraph node with a ConstantRange under
833 /// the scope of a rooted subtree in the dominator tree.
834 class VISIBILITY_HIDDEN ScopedRange {
835 public:
Nick Lewycky26e25d32007-06-24 04:36:20 +0000836 ScopedRange(Value *V, ConstantRange CR, DomTreeDFS::Node *ST)
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000837 : V(V), CR(CR), Subtree(ST) {}
838
839 Value *V;
840 ConstantRange CR;
Nick Lewycky26e25d32007-06-24 04:36:20 +0000841 DomTreeDFS::Node *Subtree;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000842
843 bool operator<(const ScopedRange &range) const {
844 if (V != range.V) return V < range.V;
Nick Lewycky26e25d32007-06-24 04:36:20 +0000845 else return Subtree < range.Subtree;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000846 }
847
848 bool operator<(const Value *value) const {
849 return V < value;
850 }
Bill Wendling6357bf22007-06-04 23:52:59 +0000851
852 bool operator>(const Value *value) const {
853 return V > value;
854 }
855
856 friend bool operator<(const Value *value, const ScopedRange &range) {
857 return range.operator>(value);
858 }
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000859 };
860
Nick Lewycky12d44ab2007-04-07 03:16:12 +0000861 TargetData *TD;
862
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000863 std::vector<ScopedRange> Ranges;
864 typedef std::vector<ScopedRange>::iterator iterator;
865
866 // XXX: this is a copy of the code in InequalityGraph::Node. Perhaps a
867 // intrusive domtree-scoped container is in order?
868
869 iterator begin() { return Ranges.begin(); }
870 iterator end() { return Ranges.end(); }
871
Nick Lewycky26e25d32007-06-24 04:36:20 +0000872 iterator find(Value *V, DomTreeDFS::Node *Subtree) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000873 iterator E = end();
874 for (iterator I = std::lower_bound(begin(), E, V);
875 I != E && I->V == V; ++I) {
876 if (Subtree->DominatedBy(I->Subtree))
877 return I;
878 }
879 return E;
880 }
881
Nick Lewycky26e25d32007-06-24 04:36:20 +0000882 void update(Value *V, ConstantRange CR, DomTreeDFS::Node *Subtree) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000883 assert(!CR.isEmptySet() && "Empty ConstantRange!");
884 if (CR.isFullSet()) return;
885
886 iterator I = find(V, Subtree);
887 if (I == end()) {
888 ScopedRange range(V, CR, Subtree);
889 iterator Insert = std::lower_bound(begin(), end(), range);
890 Ranges.insert(Insert, range);
891 } else {
892 CR = CR.intersectWith(I->CR);
893 assert(!CR.isEmptySet() && "Empty intersection of ConstantRanges!");
894
895 if (CR != I->CR) {
896 if (Subtree != I->Subtree) {
897 assert(Subtree->DominatedBy(I->Subtree) &&
898 "Find returned subtree that doesn't apply.");
899
900 ScopedRange range(V, CR, Subtree);
901 iterator Insert = std::lower_bound(begin(), end(), range);
902 Ranges.insert(Insert, range); // invalidates I
903 I = find(V, Subtree);
904 }
905
906 // Also, we have to tighten any edge that Subtree dominates.
907 for (iterator B = begin(); I->V == V; --I) {
908 if (I->Subtree->DominatedBy(Subtree)) {
Nick Lewycky3bb6de82007-04-07 03:36:51 +0000909 I->CR = CR.intersectWith(I->CR);
910 assert(!I->CR.isEmptySet() &&
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000911 "Empty intersection of ConstantRanges!");
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000912 }
913 if (I == B) break;
914 }
915 }
916 }
917 }
918
919 /// range - Creates a ConstantRange representing the set of all values
920 /// that match the ICmpInst::Predicate with any of the values in CR.
921 ConstantRange range(ICmpInst::Predicate ICmpOpcode,
922 const ConstantRange &CR) {
923 uint32_t W = CR.getBitWidth();
924 switch (ICmpOpcode) {
925 default: assert(!"Invalid ICmp opcode to range()");
926 case ICmpInst::ICMP_EQ:
927 return ConstantRange(CR.getLower(), CR.getUpper());
928 case ICmpInst::ICMP_NE:
929 if (CR.isSingleElement())
930 return ConstantRange(CR.getUpper(), CR.getLower());
931 return ConstantRange(W);
932 case ICmpInst::ICMP_ULT:
933 return ConstantRange(APInt::getMinValue(W), CR.getUnsignedMax());
934 case ICmpInst::ICMP_SLT:
935 return ConstantRange(APInt::getSignedMinValue(W), CR.getSignedMax());
936 case ICmpInst::ICMP_ULE: {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +0000937 APInt UMax(CR.getUnsignedMax());
Zhou Sheng31787362007-04-26 16:42:07 +0000938 if (UMax.isMaxValue())
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000939 return ConstantRange(W);
940 return ConstantRange(APInt::getMinValue(W), UMax + 1);
941 }
942 case ICmpInst::ICMP_SLE: {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +0000943 APInt SMax(CR.getSignedMax());
Zhou Sheng31787362007-04-26 16:42:07 +0000944 if (SMax.isMaxSignedValue() || (SMax+1).isMaxSignedValue())
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000945 return ConstantRange(W);
946 return ConstantRange(APInt::getSignedMinValue(W), SMax + 1);
947 }
948 case ICmpInst::ICMP_UGT:
Zhou Sheng82fcf3c2007-04-19 05:35:00 +0000949 return ConstantRange(CR.getUnsignedMin() + 1, APInt::getNullValue(W));
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000950 case ICmpInst::ICMP_SGT:
951 return ConstantRange(CR.getSignedMin() + 1,
Zhou Sheng82fcf3c2007-04-19 05:35:00 +0000952 APInt::getSignedMinValue(W));
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000953 case ICmpInst::ICMP_UGE: {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +0000954 APInt UMin(CR.getUnsignedMin());
Zhou Sheng31787362007-04-26 16:42:07 +0000955 if (UMin.isMinValue())
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000956 return ConstantRange(W);
Zhou Sheng82fcf3c2007-04-19 05:35:00 +0000957 return ConstantRange(UMin, APInt::getNullValue(W));
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000958 }
959 case ICmpInst::ICMP_SGE: {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +0000960 APInt SMin(CR.getSignedMin());
Zhou Sheng31787362007-04-26 16:42:07 +0000961 if (SMin.isMinSignedValue())
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000962 return ConstantRange(W);
Zhou Sheng82fcf3c2007-04-19 05:35:00 +0000963 return ConstantRange(SMin, APInt::getSignedMinValue(W));
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000964 }
965 }
966 }
967
968 /// create - Creates a ConstantRange that matches the given LatticeVal
969 /// relation with a given integer.
970 ConstantRange create(LatticeVal LV, const ConstantRange &CR) {
971 assert(!CR.isEmptySet() && "Can't deal with empty set.");
972
973 if (LV == NE)
974 return range(ICmpInst::ICMP_NE, CR);
975
976 unsigned LV_s = LV & (SGT_BIT|SLT_BIT);
977 unsigned LV_u = LV & (UGT_BIT|ULT_BIT);
978 bool hasEQ = LV & EQ_BIT;
979
980 ConstantRange Range(CR.getBitWidth());
981
982 if (LV_s == SGT_BIT) {
983 Range = Range.intersectWith(range(
984 hasEQ ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_SGT, CR));
985 } else if (LV_s == SLT_BIT) {
986 Range = Range.intersectWith(range(
987 hasEQ ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_SLT, CR));
988 }
989
990 if (LV_u == UGT_BIT) {
991 Range = Range.intersectWith(range(
992 hasEQ ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_UGT, CR));
993 } else if (LV_u == ULT_BIT) {
994 Range = Range.intersectWith(range(
995 hasEQ ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT, CR));
996 }
997
998 return Range;
999 }
1000
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001001#ifndef NDEBUG
Nick Lewycky26e25d32007-06-24 04:36:20 +00001002 bool isCanonical(Value *V, DomTreeDFS::Node *Subtree, VRPSolver *VRP);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001003#endif
1004
1005 public:
1006
1007 explicit ValueRanges(TargetData *TD) : TD(TD) {}
1008
Nick Lewycky12d44ab2007-04-07 03:16:12 +00001009 // rangeFromValue - converts a Value into a range. If the value is a
1010 // constant it constructs the single element range, otherwise it performs
1011 // a lookup. The width W must be retrieved from typeToWidth and may not
1012 // be zero.
Nick Lewycky26e25d32007-06-24 04:36:20 +00001013 ConstantRange rangeFromValue(Value *V, DomTreeDFS::Node *Subtree,
1014 uint32_t W) {
Nick Lewycky12d44ab2007-04-07 03:16:12 +00001015 if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001016 return ConstantRange(C->getValue());
Nick Lewycky12d44ab2007-04-07 03:16:12 +00001017 } else if (isa<ConstantPointerNull>(V)) {
1018 return ConstantRange(APInt::getNullValue(W));
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001019 } else {
1020 iterator I = find(V, Subtree);
1021 if (I != end())
1022 return I->CR;
1023 }
1024 return ConstantRange(W);
1025 }
1026
Nick Lewycky12d44ab2007-04-07 03:16:12 +00001027 // typeToWidth - returns the number of bits necessary to store a value of
1028 // this type, or zero if unknown.
1029 uint32_t typeToWidth(const Type *Ty) const {
1030 if (TD)
1031 return TD->getTypeSizeInBits(Ty);
1032
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001033 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
1034 return ITy->getBitWidth();
1035
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001036 return 0;
1037 }
1038
Nick Lewycky26e25d32007-06-24 04:36:20 +00001039 bool isRelatedBy(Value *V1, Value *V2, DomTreeDFS::Node *Subtree,
1040 LatticeVal LV) {
Nick Lewycky12d44ab2007-04-07 03:16:12 +00001041 uint32_t W = typeToWidth(V1->getType());
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001042 if (!W) return false;
1043
1044 ConstantRange CR1 = rangeFromValue(V1, Subtree, W);
1045 ConstantRange CR2 = rangeFromValue(V2, Subtree, W);
1046
1047 // True iff all values in CR1 are LV to all values in CR2.
Nick Lewycky4f73de22007-03-16 02:37:39 +00001048 switch (LV) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001049 default: assert(!"Impossible lattice value!");
1050 case NE:
1051 return CR1.intersectWith(CR2).isEmptySet();
1052 case ULT:
1053 return CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
1054 case ULE:
1055 return CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
1056 case UGT:
1057 return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
1058 case UGE:
1059 return CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
1060 case SLT:
1061 return CR1.getSignedMax().slt(CR2.getSignedMin());
1062 case SLE:
1063 return CR1.getSignedMax().sle(CR2.getSignedMin());
1064 case SGT:
1065 return CR1.getSignedMin().sgt(CR2.getSignedMax());
1066 case SGE:
1067 return CR1.getSignedMin().sge(CR2.getSignedMax());
1068 case LT:
1069 return CR1.getUnsignedMax().ult(CR2.getUnsignedMin()) &&
1070 CR1.getSignedMax().slt(CR2.getUnsignedMin());
1071 case LE:
1072 return CR1.getUnsignedMax().ule(CR2.getUnsignedMin()) &&
1073 CR1.getSignedMax().sle(CR2.getUnsignedMin());
1074 case GT:
1075 return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax()) &&
1076 CR1.getSignedMin().sgt(CR2.getSignedMax());
1077 case GE:
1078 return CR1.getUnsignedMin().uge(CR2.getUnsignedMax()) &&
1079 CR1.getSignedMin().sge(CR2.getSignedMax());
1080 case SLTUGT:
1081 return CR1.getSignedMax().slt(CR2.getSignedMin()) &&
1082 CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
1083 case SLEUGE:
1084 return CR1.getSignedMax().sle(CR2.getSignedMin()) &&
1085 CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
1086 case SGTULT:
1087 return CR1.getSignedMin().sgt(CR2.getSignedMax()) &&
1088 CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
1089 case SGEULE:
1090 return CR1.getSignedMin().sge(CR2.getSignedMax()) &&
1091 CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
1092 }
1093 }
1094
Nick Lewycky3bb6de82007-04-07 03:36:51 +00001095 void addToWorklist(Value *V, Constant *C, ICmpInst::Predicate Pred,
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001096 VRPSolver *VRP);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001097 void markBlock(VRPSolver *VRP);
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001098
Nick Lewycky26e25d32007-06-24 04:36:20 +00001099 void mergeInto(Value **I, unsigned n, Value *New,
1100 DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001101 assert(isCanonical(New, Subtree, VRP) && "Best choice not canonical?");
1102
Nick Lewycky12d44ab2007-04-07 03:16:12 +00001103 uint32_t W = typeToWidth(New->getType());
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001104 if (!W) return;
1105
1106 ConstantRange CR_New = rangeFromValue(New, Subtree, W);
1107 ConstantRange Merged = CR_New;
1108
1109 for (; n != 0; ++I, --n) {
1110 ConstantRange CR_Kill = rangeFromValue(*I, Subtree, W);
1111 if (CR_Kill.isFullSet()) continue;
1112 Merged = Merged.intersectWith(CR_Kill);
1113 }
1114
1115 if (Merged.isFullSet() || Merged == CR_New) return;
1116
Nick Lewycky3bb6de82007-04-07 03:36:51 +00001117 applyRange(New, Merged, Subtree, VRP);
1118 }
1119
Nick Lewycky26e25d32007-06-24 04:36:20 +00001120 void applyRange(Value *V, const ConstantRange &CR,
1121 DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
Nick Lewycky3bb6de82007-04-07 03:36:51 +00001122 assert(isCanonical(V, Subtree, VRP) && "Value not canonical.");
1123
1124 if (const APInt *I = CR.getSingleElement()) {
1125 const Type *Ty = V->getType();
1126 if (Ty->isInteger()) {
1127 addToWorklist(V, ConstantInt::get(*I), ICmpInst::ICMP_EQ, VRP);
1128 return;
1129 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1130 assert(*I == 0 && "Pointer is null but not zero?");
1131 addToWorklist(V, ConstantPointerNull::get(PTy),
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001132 ICmpInst::ICMP_EQ, VRP);
Nick Lewycky3bb6de82007-04-07 03:36:51 +00001133 return;
1134 }
1135 }
1136
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001137 ConstantRange Merged = CR.intersectWith(
1138 rangeFromValue(V, Subtree, CR.getBitWidth()));
1139 if (Merged.isEmptySet()) {
1140 markBlock(VRP);
1141 return;
1142 }
1143
1144 update(V, Merged, Subtree);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001145 }
1146
Nick Lewycky26e25d32007-06-24 04:36:20 +00001147 void addNotEquals(Value *V1, Value *V2, DomTreeDFS::Node *Subtree,
1148 VRPSolver *VRP) {
Nick Lewycky93f54102007-04-07 04:49:12 +00001149 uint32_t W = typeToWidth(V1->getType());
1150 if (!W) return;
1151
1152 ConstantRange CR1 = rangeFromValue(V1, Subtree, W);
1153 ConstantRange CR2 = rangeFromValue(V2, Subtree, W);
1154
1155 if (const APInt *I = CR1.getSingleElement()) {
1156 if (CR2.isFullSet()) {
1157 ConstantRange NewCR2(CR1.getUpper(), CR1.getLower());
1158 applyRange(V2, NewCR2, Subtree, VRP);
1159 } else if (*I == CR2.getLower()) {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001160 APInt NewLower(CR2.getLower() + 1),
1161 NewUpper(CR2.getUpper());
Nick Lewycky93f54102007-04-07 04:49:12 +00001162 if (NewLower == NewUpper)
1163 NewLower = NewUpper = APInt::getMinValue(W);
1164
1165 ConstantRange NewCR2(NewLower, NewUpper);
1166 applyRange(V2, NewCR2, Subtree, VRP);
1167 } else if (*I == CR2.getUpper() - 1) {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001168 APInt NewLower(CR2.getLower()),
1169 NewUpper(CR2.getUpper() - 1);
Nick Lewycky93f54102007-04-07 04:49:12 +00001170 if (NewLower == NewUpper)
1171 NewLower = NewUpper = APInt::getMinValue(W);
1172
1173 ConstantRange NewCR2(NewLower, NewUpper);
1174 applyRange(V2, NewCR2, Subtree, VRP);
1175 }
1176 }
1177
1178 if (const APInt *I = CR2.getSingleElement()) {
1179 if (CR1.isFullSet()) {
1180 ConstantRange NewCR1(CR2.getUpper(), CR2.getLower());
1181 applyRange(V1, NewCR1, Subtree, VRP);
1182 } else if (*I == CR1.getLower()) {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001183 APInt NewLower(CR1.getLower() + 1),
1184 NewUpper(CR1.getUpper());
Nick Lewycky93f54102007-04-07 04:49:12 +00001185 if (NewLower == NewUpper)
1186 NewLower = NewUpper = APInt::getMinValue(W);
1187
1188 ConstantRange NewCR1(NewLower, NewUpper);
1189 applyRange(V1, NewCR1, Subtree, VRP);
1190 } else if (*I == CR1.getUpper() - 1) {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001191 APInt NewLower(CR1.getLower()),
1192 NewUpper(CR1.getUpper() - 1);
Nick Lewycky93f54102007-04-07 04:49:12 +00001193 if (NewLower == NewUpper)
1194 NewLower = NewUpper = APInt::getMinValue(W);
1195
1196 ConstantRange NewCR1(NewLower, NewUpper);
1197 applyRange(V1, NewCR1, Subtree, VRP);
1198 }
1199 }
1200 }
1201
Nick Lewycky26e25d32007-06-24 04:36:20 +00001202 void addInequality(Value *V1, Value *V2, DomTreeDFS::Node *Subtree,
1203 LatticeVal LV, VRPSolver *VRP) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001204 assert(!isRelatedBy(V1, V2, Subtree, LV) && "Asked to do useless work.");
1205
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001206 assert(isCanonical(V1, Subtree, VRP) && "Value not canonical.");
1207 assert(isCanonical(V2, Subtree, VRP) && "Value not canonical.");
1208
Nick Lewycky93f54102007-04-07 04:49:12 +00001209 if (LV == NE) {
1210 addNotEquals(V1, V2, Subtree, VRP);
1211 return;
1212 }
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001213
Nick Lewycky12d44ab2007-04-07 03:16:12 +00001214 uint32_t W = typeToWidth(V1->getType());
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001215 if (!W) return;
1216
1217 ConstantRange CR1 = rangeFromValue(V1, Subtree, W);
1218 ConstantRange CR2 = rangeFromValue(V2, Subtree, W);
1219
1220 if (!CR1.isSingleElement()) {
1221 ConstantRange NewCR1 = CR1.intersectWith(create(LV, CR2));
Nick Lewycky3bb6de82007-04-07 03:36:51 +00001222 if (NewCR1 != CR1)
1223 applyRange(V1, NewCR1, Subtree, VRP);
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001224 }
1225
1226 if (!CR2.isSingleElement()) {
1227 ConstantRange NewCR2 = CR2.intersectWith(create(reversePredicate(LV),
1228 CR1));
Nick Lewycky3bb6de82007-04-07 03:36:51 +00001229 if (NewCR2 != CR2)
1230 applyRange(V2, NewCR2, Subtree, VRP);
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001231 }
1232 }
1233 };
1234
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001235 /// UnreachableBlocks keeps tracks of blocks that are for one reason or
1236 /// another discovered to be unreachable. This is used to cull the graph when
1237 /// analyzing instructions, and to mark blocks with the "unreachable"
1238 /// terminator instruction after the function has executed.
1239 class VISIBILITY_HIDDEN UnreachableBlocks {
1240 private:
1241 std::vector<BasicBlock *> DeadBlocks;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001242
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001243 public:
1244 /// mark - mark a block as dead
1245 void mark(BasicBlock *BB) {
1246 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
1247 std::vector<BasicBlock *>::iterator I =
1248 std::lower_bound(DeadBlocks.begin(), E, BB);
1249
1250 if (I == E || *I != BB) DeadBlocks.insert(I, BB);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001251 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001252
1253 /// isDead - returns whether a block is known to be dead already
1254 bool isDead(BasicBlock *BB) {
1255 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
1256 std::vector<BasicBlock *>::iterator I =
1257 std::lower_bound(DeadBlocks.begin(), E, BB);
1258
1259 return I != E && *I == BB;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001260 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001261
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001262 /// kill - replace the dead blocks' terminator with an UnreachableInst.
1263 bool kill() {
1264 bool modified = false;
1265 for (std::vector<BasicBlock *>::iterator I = DeadBlocks.begin(),
1266 E = DeadBlocks.end(); I != E; ++I) {
1267 BasicBlock *BB = *I;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001268
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001269 DOUT << "unreachable block: " << BB->getName() << "\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001270
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001271 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
1272 SI != SE; ++SI) {
1273 BasicBlock *Succ = *SI;
1274 Succ->removePredecessor(BB);
Nick Lewycky9d17c822006-10-25 23:48:24 +00001275 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001276
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001277 TerminatorInst *TI = BB->getTerminator();
1278 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1279 TI->eraseFromParent();
1280 new UnreachableInst(BB);
1281 ++NumBlocks;
1282 modified = true;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001283 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001284 DeadBlocks.clear();
1285 return modified;
Nick Lewycky9d17c822006-10-25 23:48:24 +00001286 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001287 };
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001288
1289 /// VRPSolver keeps track of how changes to one variable affect other
1290 /// variables, and forwards changes along to the InequalityGraph. It
1291 /// also maintains the correct choice for "canonical" in the IG.
1292 /// @brief VRPSolver calculates inferences from a new relationship.
1293 class VISIBILITY_HIDDEN VRPSolver {
1294 private:
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001295 friend class ValueRanges;
1296
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001297 struct Operation {
1298 Value *LHS, *RHS;
1299 ICmpInst::Predicate Op;
1300
Nick Lewycky26e25d32007-06-24 04:36:20 +00001301 BasicBlock *ContextBB; // XXX use a DomTreeDFS::Node instead
Nick Lewycky42944462007-01-13 02:05:28 +00001302 Instruction *ContextInst;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001303 };
1304 std::deque<Operation> WorkList;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001305
1306 InequalityGraph &IG;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001307 UnreachableBlocks &UB;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001308 ValueRanges &VR;
Nick Lewycky26e25d32007-06-24 04:36:20 +00001309 DomTreeDFS *DTDFS;
1310 DomTreeDFS::Node *Top;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001311 BasicBlock *TopBB;
1312 Instruction *TopInst;
1313 bool &modified;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001314
1315 typedef InequalityGraph::Node Node;
1316
1317 /// Returns true if V1 is a better canonical value than V2.
1318 bool compare(Value *V1, Value *V2) const {
1319 if (isa<Constant>(V1))
1320 return !isa<Constant>(V2);
1321 else if (isa<Constant>(V2))
1322 return false;
1323 else if (isa<Argument>(V1))
1324 return !isa<Argument>(V2);
1325 else if (isa<Argument>(V2))
1326 return false;
1327
1328 Instruction *I1 = dyn_cast<Instruction>(V1);
1329 Instruction *I2 = dyn_cast<Instruction>(V2);
1330
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001331 if (!I1 || !I2)
1332 return V1->getNumUses() < V2->getNumUses();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001333
Nick Lewycky26e25d32007-06-24 04:36:20 +00001334 return DTDFS->dominates(I1, I2);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001335 }
1336
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001337 // below - true if the Instruction is dominated by the current context
1338 // block or instruction
1339 bool below(Instruction *I) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00001340 BasicBlock *BB = I->getParent();
1341 if (TopInst && TopInst->getParent() == BB) {
1342 if (isa<TerminatorInst>(TopInst)) return false;
1343 if (isa<TerminatorInst>(I)) return true;
1344 if ( isa<PHINode>(TopInst) && !isa<PHINode>(I)) return true;
1345 if (!isa<PHINode>(TopInst) && isa<PHINode>(I)) return false;
1346
1347 for (BasicBlock::const_iterator Iter = BB->begin(), E = BB->end();
1348 Iter != E; ++Iter) {
1349 if (&*Iter == TopInst) return true;
1350 else if (&*Iter == I) return false;
1351 }
1352 assert(!"Instructions not found in parent BasicBlock?");
1353 } else {
1354 DomTreeDFS::Node *Node = DTDFS->getNodeForBlock(BB);
1355 if (!Node) return false;
1356 return Top->dominates(Node);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001357 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001358 }
1359
Nick Lewycky26e25d32007-06-24 04:36:20 +00001360 // aboveOrBelow - true if the Instruction either dominates or is dominated
1361 // by the current context block or instruction
1362 bool aboveOrBelow(Instruction *I) {
1363 BasicBlock *BB = I->getParent();
1364 DomTreeDFS::Node *Node = DTDFS->getNodeForBlock(BB);
1365 if (!Node) return false;
1366
1367 return Top == Node || Top->dominates(Node) || Node->dominates(Top);
1368 }
1369
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001370 bool makeEqual(Value *V1, Value *V2) {
1371 DOUT << "makeEqual(" << *V1 << ", " << *V2 << ")\n";
Nick Lewycky26e25d32007-06-24 04:36:20 +00001372 DOUT << "context is ";
1373 if (TopInst) DOUT << "I: " << *TopInst << "\n";
1374 else DOUT << "BB: " << TopBB->getName()
1375 << "(" << Top->getDFSNumIn() << ")\n";
Nick Lewycky9d17c822006-10-25 23:48:24 +00001376
Nick Lewycky12d44ab2007-04-07 03:16:12 +00001377 assert(V1->getType() == V2->getType() &&
1378 "Can't make two values with different types equal.");
1379
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001380 if (V1 == V2) return true;
Nick Lewycky9d17c822006-10-25 23:48:24 +00001381
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001382 if (isa<Constant>(V1) && isa<Constant>(V2))
1383 return false;
1384
1385 unsigned n1 = IG.getNode(V1, Top), n2 = IG.getNode(V2, Top);
1386
1387 if (n1 && n2) {
1388 if (n1 == n2) return true;
1389 if (IG.isRelatedBy(n1, n2, Top, NE)) return false;
1390 }
1391
1392 if (n1) assert(V1 == IG.node(n1)->getValue() && "Value isn't canonical.");
1393 if (n2) assert(V2 == IG.node(n2)->getValue() && "Value isn't canonical.");
1394
Nick Lewycky15245952007-02-04 23:43:05 +00001395 assert(!compare(V2, V1) && "Please order parameters to makeEqual.");
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001396
1397 assert(!isa<Constant>(V2) && "Tried to remove a constant.");
1398
1399 SetVector<unsigned> Remove;
1400 if (n2) Remove.insert(n2);
1401
1402 if (n1 && n2) {
1403 // Suppose we're being told that %x == %y, and %x <= %z and %y >= %z.
1404 // We can't just merge %x and %y because the relationship with %z would
1405 // be EQ and that's invalid. What we're doing is looking for any nodes
1406 // %z such that %x <= %z and %y >= %z, and vice versa.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001407
1408 Node *N1 = IG.node(n1);
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001409 Node *N2 = IG.node(n2);
1410 Node::iterator end = N2->end();
1411
1412 // Find the intersection between N1 and N2 which is dominated by
1413 // Top. If we find %x where N1 <= %x <= N2 (or >=) then add %x to
1414 // Remove.
1415 for (Node::iterator I = N1->begin(), E = N1->end(); I != E; ++I) {
1416 if (!(I->LV & EQ_BIT) || !Top->DominatedBy(I->Subtree)) continue;
1417
1418 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
1419 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
1420 Node::iterator NI = N2->find(I->To, Top);
1421 if (NI != end) {
1422 LatticeVal NILV = reversePredicate(NI->LV);
1423 unsigned NILV_s = NILV & (SLT_BIT|SGT_BIT);
1424 unsigned NILV_u = NILV & (ULT_BIT|UGT_BIT);
1425
1426 if ((ILV_s != (SLT_BIT|SGT_BIT) && ILV_s == NILV_s) ||
1427 (ILV_u != (ULT_BIT|UGT_BIT) && ILV_u == NILV_u))
1428 Remove.insert(I->To);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001429 }
1430 }
1431
1432 // See if one of the nodes about to be removed is actually a better
1433 // canonical choice than n1.
1434 unsigned orig_n1 = n1;
Reid Spencera8a15472007-01-17 02:23:37 +00001435 SetVector<unsigned>::iterator DontRemove = Remove.end();
1436 for (SetVector<unsigned>::iterator I = Remove.begin()+1 /* skip n2 */,
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001437 E = Remove.end(); I != E; ++I) {
1438 unsigned n = *I;
1439 Value *V = IG.node(n)->getValue();
1440 if (compare(V, V1)) {
1441 V1 = V;
1442 n1 = n;
1443 DontRemove = I;
1444 }
1445 }
1446 if (DontRemove != Remove.end()) {
1447 unsigned n = *DontRemove;
1448 Remove.remove(n);
1449 Remove.insert(orig_n1);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001450 }
1451 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001452
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001453 // We'd like to allow makeEqual on two values to perform a simple
1454 // substitution without every creating nodes in the IG whenever possible.
1455 //
1456 // The first iteration through this loop operates on V2 before going
1457 // through the Remove list and operating on those too. If all of the
1458 // iterations performed simple replacements then we exit early.
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001459 bool mergeIGNode = false;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001460 unsigned i = 0;
1461 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
1462 if (i) R = IG.node(Remove[i])->getValue(); // skip n2.
1463
1464 // Try to replace the whole instruction. If we can, we're done.
1465 Instruction *I2 = dyn_cast<Instruction>(R);
1466 if (I2 && below(I2)) {
1467 std::vector<Instruction *> ToNotify;
1468 for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
1469 UI != UE;) {
1470 Use &TheUse = UI.getUse();
1471 ++UI;
1472 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser()))
1473 ToNotify.push_back(I);
1474 }
1475
1476 DOUT << "Simply removing " << *I2
1477 << ", replacing with " << *V1 << "\n";
1478 I2->replaceAllUsesWith(V1);
1479 // leave it dead; it'll get erased later.
1480 ++NumInstruction;
1481 modified = true;
1482
1483 for (std::vector<Instruction *>::iterator II = ToNotify.begin(),
1484 IE = ToNotify.end(); II != IE; ++II) {
1485 opsToDef(*II);
1486 }
1487
1488 continue;
1489 }
1490
1491 // Otherwise, replace all dominated uses.
1492 for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
1493 UI != UE;) {
1494 Use &TheUse = UI.getUse();
1495 ++UI;
1496 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
1497 if (below(I)) {
1498 TheUse.set(V1);
1499 modified = true;
1500 ++NumVarsReplaced;
1501 opsToDef(I);
1502 }
1503 }
1504 }
1505
1506 // If that killed the instruction, stop here.
1507 if (I2 && isInstructionTriviallyDead(I2)) {
1508 DOUT << "Killed all uses of " << *I2
1509 << ", replacing with " << *V1 << "\n";
1510 continue;
1511 }
1512
1513 // If we make it to here, then we will need to create a node for N1.
1514 // Otherwise, we can skip out early!
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001515 mergeIGNode = true;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001516 }
1517
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001518 if (!isa<Constant>(V1)) {
1519 if (Remove.empty()) {
1520 VR.mergeInto(&V2, 1, V1, Top, this);
1521 } else {
1522 std::vector<Value*> RemoveVals;
1523 RemoveVals.reserve(Remove.size());
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001524
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001525 for (SetVector<unsigned>::iterator I = Remove.begin(),
1526 E = Remove.end(); I != E; ++I) {
1527 Value *V = IG.node(*I)->getValue();
1528 if (!V->use_empty())
1529 RemoveVals.push_back(V);
1530 }
1531 VR.mergeInto(&RemoveVals[0], RemoveVals.size(), V1, Top, this);
1532 }
1533 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001534
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001535 if (mergeIGNode) {
1536 // Create N1.
1537 if (!n1) n1 = IG.newNode(V1);
1538
1539 // Migrate relationships from removed nodes to N1.
1540 Node *N1 = IG.node(n1);
1541 for (SetVector<unsigned>::iterator I = Remove.begin(), E = Remove.end();
1542 I != E; ++I) {
1543 unsigned n = *I;
1544 Node *N = IG.node(n);
1545 for (Node::iterator NI = N->begin(), NE = N->end(); NI != NE; ++NI) {
1546 if (NI->Subtree->DominatedBy(Top)) {
1547 if (NI->To == n1) {
1548 assert((NI->LV & EQ_BIT) && "Node inequal to itself.");
1549 continue;
1550 }
1551 if (Remove.count(NI->To))
1552 continue;
1553
1554 IG.node(NI->To)->update(n1, reversePredicate(NI->LV), Top);
1555 N1->update(NI->To, NI->LV, Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001556 }
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001557 }
1558 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001559
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001560 // Point V2 (and all items in Remove) to N1.
1561 if (!n2)
1562 IG.addEquality(n1, V2, Top);
1563 else {
1564 for (SetVector<unsigned>::iterator I = Remove.begin(),
1565 E = Remove.end(); I != E; ++I) {
1566 IG.addEquality(n1, IG.node(*I)->getValue(), Top);
1567 }
1568 }
1569
1570 // If !Remove.empty() then V2 = Remove[0]->getValue().
1571 // Even when Remove is empty, we still want to process V2.
1572 i = 0;
1573 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
1574 if (i) R = IG.node(Remove[i])->getValue(); // skip n2.
1575
1576 if (Instruction *I2 = dyn_cast<Instruction>(R)) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00001577 if (aboveOrBelow(I2))
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001578 defToOps(I2);
1579 }
1580 for (Value::use_iterator UI = V2->use_begin(), UE = V2->use_end();
1581 UI != UE;) {
1582 Use &TheUse = UI.getUse();
1583 ++UI;
1584 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00001585 if (aboveOrBelow(I))
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001586 opsToDef(I);
1587 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001588 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001589 }
1590 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001591
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001592 // re-opsToDef all dominated users of V1.
1593 if (Instruction *I = dyn_cast<Instruction>(V1)) {
1594 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001595 UI != UE;) {
1596 Use &TheUse = UI.getUse();
1597 ++UI;
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001598 Value *V = TheUse.getUser();
1599 if (!V->use_empty()) {
1600 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00001601 if (aboveOrBelow(Inst))
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001602 opsToDef(Inst);
1603 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001604 }
1605 }
1606 }
1607
1608 return true;
1609 }
1610
1611 /// cmpInstToLattice - converts an CmpInst::Predicate to lattice value
1612 /// Requires that the lattice value be valid; does not accept ICMP_EQ.
1613 static LatticeVal cmpInstToLattice(ICmpInst::Predicate Pred) {
1614 switch (Pred) {
1615 case ICmpInst::ICMP_EQ:
1616 assert(!"No matching lattice value.");
1617 return static_cast<LatticeVal>(EQ_BIT);
1618 default:
1619 assert(!"Invalid 'icmp' predicate.");
1620 case ICmpInst::ICMP_NE:
1621 return NE;
1622 case ICmpInst::ICMP_UGT:
Nick Lewycky56639802007-01-29 02:56:54 +00001623 return UGT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001624 case ICmpInst::ICMP_UGE:
Nick Lewycky56639802007-01-29 02:56:54 +00001625 return UGE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001626 case ICmpInst::ICMP_ULT:
Nick Lewycky56639802007-01-29 02:56:54 +00001627 return ULT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001628 case ICmpInst::ICMP_ULE:
Nick Lewycky56639802007-01-29 02:56:54 +00001629 return ULE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001630 case ICmpInst::ICMP_SGT:
Nick Lewycky56639802007-01-29 02:56:54 +00001631 return SGT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001632 case ICmpInst::ICMP_SGE:
Nick Lewycky56639802007-01-29 02:56:54 +00001633 return SGE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001634 case ICmpInst::ICMP_SLT:
Nick Lewycky56639802007-01-29 02:56:54 +00001635 return SLT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001636 case ICmpInst::ICMP_SLE:
Nick Lewycky56639802007-01-29 02:56:54 +00001637 return SLE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001638 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001639 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001640
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001641 public:
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001642 VRPSolver(InequalityGraph &IG, UnreachableBlocks &UB, ValueRanges &VR,
Nick Lewycky26e25d32007-06-24 04:36:20 +00001643 DomTreeDFS *DTDFS, bool &modified, BasicBlock *TopBB)
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001644 : IG(IG),
1645 UB(UB),
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001646 VR(VR),
Nick Lewycky26e25d32007-06-24 04:36:20 +00001647 DTDFS(DTDFS),
1648 Top(DTDFS->getNodeForBlock(TopBB)),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001649 TopBB(TopBB),
1650 TopInst(NULL),
Nick Lewycky26e25d32007-06-24 04:36:20 +00001651 modified(modified)
1652 {
1653 assert(Top && "VRPSolver created for unreachable basic block.");
1654 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001655
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001656 VRPSolver(InequalityGraph &IG, UnreachableBlocks &UB, ValueRanges &VR,
Nick Lewycky26e25d32007-06-24 04:36:20 +00001657 DomTreeDFS *DTDFS, bool &modified, Instruction *TopInst)
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001658 : IG(IG),
1659 UB(UB),
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001660 VR(VR),
Nick Lewycky26e25d32007-06-24 04:36:20 +00001661 DTDFS(DTDFS),
1662 Top(DTDFS->getNodeForBlock(TopInst->getParent())),
1663 TopBB(TopInst->getParent()),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001664 TopInst(TopInst),
1665 modified(modified)
1666 {
Nick Lewycky26e25d32007-06-24 04:36:20 +00001667 assert(Top && "VRPSolver created for unreachable basic block.");
1668 assert(Top->getBlock() == TopInst->getParent() && "Context mismatch.");
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001669 }
1670
1671 bool isRelatedBy(Value *V1, Value *V2, ICmpInst::Predicate Pred) const {
1672 if (Constant *C1 = dyn_cast<Constant>(V1))
1673 if (Constant *C2 = dyn_cast<Constant>(V2))
1674 return ConstantExpr::getCompare(Pred, C1, C2) ==
Zhou Sheng75b871f2007-01-11 12:24:14 +00001675 ConstantInt::getTrue();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001676
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001677 if (unsigned n1 = IG.getNode(V1, Top))
1678 if (unsigned n2 = IG.getNode(V2, Top)) {
1679 if (n1 == n2) return Pred == ICmpInst::ICMP_EQ ||
1680 Pred == ICmpInst::ICMP_ULE ||
1681 Pred == ICmpInst::ICMP_UGE ||
1682 Pred == ICmpInst::ICMP_SLE ||
1683 Pred == ICmpInst::ICMP_SGE;
1684 if (Pred == ICmpInst::ICMP_EQ) return false;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001685 if (IG.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001686 }
1687
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001688 if (Pred == ICmpInst::ICMP_EQ) return V1 == V2;
1689 return VR.isRelatedBy(V1, V2, Top, cmpInstToLattice(Pred));
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001690 }
1691
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001692 /// add - adds a new property to the work queue
1693 void add(Value *V1, Value *V2, ICmpInst::Predicate Pred,
1694 Instruction *I = NULL) {
1695 DOUT << "adding " << *V1 << " " << Pred << " " << *V2;
1696 if (I) DOUT << " context: " << *I;
Nick Lewycky26e25d32007-06-24 04:36:20 +00001697 else DOUT << " default context (" << Top->getDFSNumIn() << ")";
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001698 DOUT << "\n";
1699
Nick Lewycky12d44ab2007-04-07 03:16:12 +00001700 assert(V1->getType() == V2->getType() &&
1701 "Can't relate two values with different types.");
1702
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001703 WorkList.push_back(Operation());
1704 Operation &O = WorkList.back();
Nick Lewycky42944462007-01-13 02:05:28 +00001705 O.LHS = V1, O.RHS = V2, O.Op = Pred, O.ContextInst = I;
1706 O.ContextBB = I ? I->getParent() : TopBB;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001707 }
1708
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001709 /// defToOps - Given an instruction definition that we've learned something
1710 /// new about, find any new relationships between its operands.
1711 void defToOps(Instruction *I) {
1712 Instruction *NewContext = below(I) ? I : TopInst;
1713 Value *Canonical = IG.canonicalize(I, Top);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001714
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001715 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1716 const Type *Ty = BO->getType();
1717 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001718
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001719 Value *Op0 = IG.canonicalize(BO->getOperand(0), Top);
1720 Value *Op1 = IG.canonicalize(BO->getOperand(1), Top);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001721
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001722 // TODO: "and i32 -1, %x" EQ %y then %x EQ %y.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001723
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001724 switch (BO->getOpcode()) {
1725 case Instruction::And: {
Nick Lewycky4f73de22007-03-16 02:37:39 +00001726 // "and i32 %a, %b" EQ -1 then %a EQ -1 and %b EQ -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00001727 ConstantInt *CI = ConstantInt::getAllOnesValue(Ty);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001728 if (Canonical == CI) {
1729 add(CI, Op0, ICmpInst::ICMP_EQ, NewContext);
1730 add(CI, Op1, ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001731 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001732 } break;
1733 case Instruction::Or: {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001734 // "or i32 %a, %b" EQ 0 then %a EQ 0 and %b EQ 0
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001735 Constant *Zero = Constant::getNullValue(Ty);
1736 if (Canonical == Zero) {
1737 add(Zero, Op0, ICmpInst::ICMP_EQ, NewContext);
1738 add(Zero, Op1, ICmpInst::ICMP_EQ, NewContext);
1739 }
1740 } break;
1741 case Instruction::Xor: {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001742 // "xor i32 %c, %a" EQ %b then %a EQ %c ^ %b
1743 // "xor i32 %c, %a" EQ %c then %a EQ 0
1744 // "xor i32 %c, %a" NE %c then %a NE 0
1745 // Repeat the above, with order of operands reversed.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001746 Value *LHS = Op0;
1747 Value *RHS = Op1;
1748 if (!isa<Constant>(LHS)) std::swap(LHS, RHS);
1749
Nick Lewycky4a74a752007-01-12 00:02:12 +00001750 if (ConstantInt *CI = dyn_cast<ConstantInt>(Canonical)) {
1751 if (ConstantInt *Arg = dyn_cast<ConstantInt>(LHS)) {
Reid Spencerc34dedf2007-03-03 00:48:31 +00001752 add(RHS, ConstantInt::get(CI->getValue() ^ Arg->getValue()),
Nick Lewycky4a74a752007-01-12 00:02:12 +00001753 ICmpInst::ICMP_EQ, NewContext);
1754 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001755 }
1756 if (Canonical == LHS) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001757 if (isa<ConstantInt>(Canonical))
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001758 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_EQ,
1759 NewContext);
1760 } else if (isRelatedBy(LHS, Canonical, ICmpInst::ICMP_NE)) {
1761 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_NE,
1762 NewContext);
1763 }
1764 } break;
1765 default:
1766 break;
1767 }
1768 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001769 // "icmp ult i32 %a, %y" EQ true then %a u< y
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001770 // etc.
1771
Zhou Sheng75b871f2007-01-11 12:24:14 +00001772 if (Canonical == ConstantInt::getTrue()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001773 add(IC->getOperand(0), IC->getOperand(1), IC->getPredicate(),
1774 NewContext);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001775 } else if (Canonical == ConstantInt::getFalse()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001776 add(IC->getOperand(0), IC->getOperand(1),
1777 ICmpInst::getInversePredicate(IC->getPredicate()), NewContext);
1778 }
1779 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
1780 if (I->getType()->isFPOrFPVector()) return;
1781
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001782 // Given: "%a = select i1 %x, i32 %b, i32 %c"
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001783 // %a EQ %b and %b NE %c then %x EQ true
1784 // %a EQ %c and %b NE %c then %x EQ false
1785
1786 Value *True = SI->getTrueValue();
1787 Value *False = SI->getFalseValue();
1788 if (isRelatedBy(True, False, ICmpInst::ICMP_NE)) {
1789 if (Canonical == IG.canonicalize(True, Top) ||
1790 isRelatedBy(Canonical, False, ICmpInst::ICMP_NE))
Zhou Sheng75b871f2007-01-11 12:24:14 +00001791 add(SI->getCondition(), ConstantInt::getTrue(),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001792 ICmpInst::ICMP_EQ, NewContext);
1793 else if (Canonical == IG.canonicalize(False, Top) ||
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001794 isRelatedBy(Canonical, True, ICmpInst::ICMP_NE))
Zhou Sheng75b871f2007-01-11 12:24:14 +00001795 add(SI->getCondition(), ConstantInt::getFalse(),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001796 ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001797 }
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001798 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1799 for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
1800 OE = GEPI->idx_end(); OI != OE; ++OI) {
1801 ConstantInt *Op = dyn_cast<ConstantInt>(IG.canonicalize(*OI, Top));
1802 if (!Op || !Op->isZero()) return;
1803 }
1804 // TODO: The GEPI indices are all zero. Copy from definition to operand,
1805 // jumping the type plane as needed.
1806 if (isRelatedBy(GEPI, Constant::getNullValue(GEPI->getType()),
1807 ICmpInst::ICMP_NE)) {
1808 Value *Ptr = GEPI->getPointerOperand();
1809 add(Ptr, Constant::getNullValue(Ptr->getType()), ICmpInst::ICMP_NE,
1810 NewContext);
1811 }
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001812 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
1813 const Type *SrcTy = CI->getSrcTy();
1814
1815 Value *TheCI = IG.canonicalize(CI, Top);
1816 uint32_t W = VR.typeToWidth(SrcTy);
1817 if (!W) return;
1818 ConstantRange CR = VR.rangeFromValue(TheCI, Top, W);
1819
1820 if (CR.isFullSet()) return;
1821
1822 switch (CI->getOpcode()) {
1823 default: break;
1824 case Instruction::ZExt:
1825 case Instruction::SExt:
1826 VR.applyRange(IG.canonicalize(CI->getOperand(0), Top),
1827 CR.truncate(W), Top, this);
1828 break;
1829 case Instruction::BitCast:
1830 VR.applyRange(IG.canonicalize(CI->getOperand(0), Top),
1831 CR, Top, this);
1832 break;
1833 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001834 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001835 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001836
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001837 /// opsToDef - A new relationship was discovered involving one of this
1838 /// instruction's operands. Find any new relationship involving the
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001839 /// definition, or another operand.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001840 void opsToDef(Instruction *I) {
1841 Instruction *NewContext = below(I) ? I : TopInst;
1842
1843 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1844 Value *Op0 = IG.canonicalize(BO->getOperand(0), Top);
1845 Value *Op1 = IG.canonicalize(BO->getOperand(1), Top);
1846
Zhou Sheng75b871f2007-01-11 12:24:14 +00001847 if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0))
1848 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001849 add(BO, ConstantExpr::get(BO->getOpcode(), CI0, CI1),
1850 ICmpInst::ICMP_EQ, NewContext);
1851 return;
1852 }
1853
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001854 // "%y = and i1 true, %x" then %x EQ %y
1855 // "%y = or i1 false, %x" then %x EQ %y
1856 // "%x = add i32 %y, 0" then %x EQ %y
1857 // "%x = mul i32 %y, 0" then %x EQ 0
1858
1859 Instruction::BinaryOps Opcode = BO->getOpcode();
Nick Lewyckydb204ec2007-03-18 22:58:46 +00001860 const Type *Ty = BO->getType();
1861 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
1862
1863 Constant *Zero = Constant::getNullValue(Ty);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001864 ConstantInt *AllOnes = ConstantInt::getAllOnesValue(Ty);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001865
1866 switch (Opcode) {
1867 default: break;
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001868 case Instruction::LShr:
1869 case Instruction::AShr:
1870 case Instruction::Shl:
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001871 case Instruction::Sub:
Nick Lewyckydb204ec2007-03-18 22:58:46 +00001872 if (Op1 == Zero) {
1873 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1874 return;
1875 }
1876 break;
1877 case Instruction::Or:
1878 if (Op0 == AllOnes || Op1 == AllOnes) {
1879 add(BO, AllOnes, ICmpInst::ICMP_EQ, NewContext);
1880 return;
1881 } // fall-through
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001882 case Instruction::Xor:
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001883 case Instruction::Add:
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001884 if (Op0 == Zero) {
1885 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1886 return;
1887 } else if (Op1 == Zero) {
1888 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1889 return;
1890 }
Nick Lewyckydb204ec2007-03-18 22:58:46 +00001891 break;
1892 case Instruction::And:
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001893 if (Op0 == AllOnes) {
1894 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1895 return;
1896 } else if (Op1 == AllOnes) {
1897 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1898 return;
1899 }
Nick Lewyckydb204ec2007-03-18 22:58:46 +00001900 // fall-through
1901 case Instruction::Mul:
1902 if (Op0 == Zero || Op1 == Zero) {
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001903 add(BO, Zero, ICmpInst::ICMP_EQ, NewContext);
1904 return;
1905 }
Nick Lewyckydb204ec2007-03-18 22:58:46 +00001906 break;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001907 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001908
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001909 // "%x = add i32 %y, %z" and %x EQ %y then %z EQ 0
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001910 // "%x = add i32 %y, %z" and %x EQ %z then %y EQ 0
1911 // "%x = shl i32 %y, %z" and %x EQ %y and %y NE 0 then %z EQ 0
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001912 // "%x = udiv i32 %y, %z" and %x EQ %y then %z EQ 1
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001913
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001914 Value *Known = Op0, *Unknown = Op1,
1915 *TheBO = IG.canonicalize(BO, Top);
1916 if (Known != TheBO) std::swap(Known, Unknown);
1917 if (Known == TheBO) {
Nick Lewycky4f73de22007-03-16 02:37:39 +00001918 switch (Opcode) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001919 default: break;
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001920 case Instruction::LShr:
1921 case Instruction::AShr:
1922 case Instruction::Shl:
1923 if (!isRelatedBy(Known, Zero, ICmpInst::ICMP_NE)) break;
1924 // otherwise, fall-through.
1925 case Instruction::Sub:
1926 if (Unknown == Op1) break;
1927 // otherwise, fall-through.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001928 case Instruction::Xor:
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001929 case Instruction::Add:
Nick Lewyckydb204ec2007-03-18 22:58:46 +00001930 add(Unknown, Zero, ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001931 break;
1932 case Instruction::UDiv:
1933 case Instruction::SDiv:
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001934 if (Unknown == Op1) break;
1935 if (isRelatedBy(Known, Zero, ICmpInst::ICMP_NE)) {
Nick Lewycky4a74a752007-01-12 00:02:12 +00001936 Constant *One = ConstantInt::get(Ty, 1);
1937 add(Unknown, One, ICmpInst::ICMP_EQ, NewContext);
1938 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001939 break;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001940 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001941 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001942
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001943 // TODO: "%a = add i32 %b, 1" and %b > %z then %a >= %z.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001944
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001945 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
Nick Lewycky4f73de22007-03-16 02:37:39 +00001946 // "%a = icmp ult i32 %b, %c" and %b u< %c then %a EQ true
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001947 // "%a = icmp ult i32 %b, %c" and %b u>= %c then %a EQ false
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001948 // etc.
1949
1950 Value *Op0 = IG.canonicalize(IC->getOperand(0), Top);
1951 Value *Op1 = IG.canonicalize(IC->getOperand(1), Top);
1952
1953 ICmpInst::Predicate Pred = IC->getPredicate();
1954 if (isRelatedBy(Op0, Op1, Pred)) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001955 add(IC, ConstantInt::getTrue(), ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001956 } else if (isRelatedBy(Op0, Op1, ICmpInst::getInversePredicate(Pred))) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001957 add(IC, ConstantInt::getFalse(), ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001958 }
1959
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001960 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001961 if (I->getType()->isFPOrFPVector()) return;
1962
Nick Lewycky4f73de22007-03-16 02:37:39 +00001963 // Given: "%a = select i1 %x, i32 %b, i32 %c"
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001964 // %x EQ true then %a EQ %b
1965 // %x EQ false then %a EQ %c
1966 // %b EQ %c then %a EQ %b
1967
1968 Value *Canonical = IG.canonicalize(SI->getCondition(), Top);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001969 if (Canonical == ConstantInt::getTrue()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001970 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001971 } else if (Canonical == ConstantInt::getFalse()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001972 add(SI, SI->getFalseValue(), ICmpInst::ICMP_EQ, NewContext);
1973 } else if (IG.canonicalize(SI->getTrueValue(), Top) ==
1974 IG.canonicalize(SI->getFalseValue(), Top)) {
1975 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
1976 }
Nick Lewyckyee32ee02007-01-12 01:23:53 +00001977 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001978 const Type *DestTy = CI->getDestTy();
1979 if (DestTy->isFPOrFPVector()) return;
Nick Lewyckyee32ee02007-01-12 01:23:53 +00001980
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001981 Value *Op = IG.canonicalize(CI->getOperand(0), Top);
1982 Instruction::CastOps Opcode = CI->getOpcode();
1983
1984 if (Constant *C = dyn_cast<Constant>(Op)) {
1985 add(CI, ConstantExpr::getCast(Opcode, C, DestTy),
Nick Lewyckyee32ee02007-01-12 01:23:53 +00001986 ICmpInst::ICMP_EQ, NewContext);
1987 }
1988
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001989 uint32_t W = VR.typeToWidth(DestTy);
1990 Value *TheCI = IG.canonicalize(CI, Top);
1991 ConstantRange CR = VR.rangeFromValue(Op, Top, W);
1992
1993 if (!CR.isFullSet()) {
1994 switch (Opcode) {
1995 default: break;
1996 case Instruction::ZExt:
1997 VR.applyRange(TheCI, CR.zeroExtend(W), Top, this);
1998 break;
1999 case Instruction::SExt:
2000 VR.applyRange(TheCI, CR.signExtend(W), Top, this);
2001 break;
2002 case Instruction::Trunc: {
2003 ConstantRange Result = CR.truncate(W);
2004 if (!Result.isFullSet())
2005 VR.applyRange(TheCI, Result, Top, this);
2006 } break;
2007 case Instruction::BitCast:
2008 VR.applyRange(TheCI, CR, Top, this);
2009 break;
2010 // TODO: other casts?
2011 }
2012 }
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00002013 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
2014 for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
2015 OE = GEPI->idx_end(); OI != OE; ++OI) {
2016 ConstantInt *Op = dyn_cast<ConstantInt>(IG.canonicalize(*OI, Top));
2017 if (!Op || !Op->isZero()) return;
2018 }
2019 // TODO: The GEPI indices are all zero. Copy from operand to definition,
2020 // jumping the type plane as needed.
2021 Value *Ptr = GEPI->getPointerOperand();
2022 if (isRelatedBy(Ptr, Constant::getNullValue(Ptr->getType()),
2023 ICmpInst::ICMP_NE)) {
2024 add(GEPI, Constant::getNullValue(GEPI->getType()), ICmpInst::ICMP_NE,
2025 NewContext);
2026 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002027 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002028 }
2029
2030 /// solve - process the work queue
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002031 void solve() {
2032 //DOUT << "WorkList entry, size: " << WorkList.size() << "\n";
2033 while (!WorkList.empty()) {
2034 //DOUT << "WorkList size: " << WorkList.size() << "\n";
2035
2036 Operation &O = WorkList.front();
Nick Lewycky42944462007-01-13 02:05:28 +00002037 TopInst = O.ContextInst;
2038 TopBB = O.ContextBB;
Nick Lewycky26e25d32007-06-24 04:36:20 +00002039 Top = DTDFS->getNodeForBlock(TopBB); // XXX move this into Context
Nick Lewycky42944462007-01-13 02:05:28 +00002040
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002041 O.LHS = IG.canonicalize(O.LHS, Top);
2042 O.RHS = IG.canonicalize(O.RHS, Top);
2043
2044 assert(O.LHS == IG.canonicalize(O.LHS, Top) && "Canonicalize isn't.");
2045 assert(O.RHS == IG.canonicalize(O.RHS, Top) && "Canonicalize isn't.");
2046
2047 DOUT << "solving " << *O.LHS << " " << O.Op << " " << *O.RHS;
Nick Lewycky42944462007-01-13 02:05:28 +00002048 if (O.ContextInst) DOUT << " context inst: " << *O.ContextInst;
2049 else DOUT << " context block: " << O.ContextBB->getName();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002050 DOUT << "\n";
2051
2052 DEBUG(IG.dump());
2053
Nick Lewycky15245952007-02-04 23:43:05 +00002054 // If they're both Constant, skip it. Check for contradiction and mark
2055 // the BB as unreachable if so.
2056 if (Constant *CI_L = dyn_cast<Constant>(O.LHS)) {
2057 if (Constant *CI_R = dyn_cast<Constant>(O.RHS)) {
2058 if (ConstantExpr::getCompare(O.Op, CI_L, CI_R) ==
2059 ConstantInt::getFalse())
2060 UB.mark(TopBB);
2061
2062 WorkList.pop_front();
2063 continue;
2064 }
2065 }
2066
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002067 if (compare(O.LHS, O.RHS)) {
Nick Lewycky15245952007-02-04 23:43:05 +00002068 std::swap(O.LHS, O.RHS);
2069 O.Op = ICmpInst::getSwappedPredicate(O.Op);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002070 }
2071
2072 if (O.Op == ICmpInst::ICMP_EQ) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002073 if (!makeEqual(O.RHS, O.LHS))
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002074 UB.mark(TopBB);
2075 } else {
2076 LatticeVal LV = cmpInstToLattice(O.Op);
2077
2078 if ((LV & EQ_BIT) &&
2079 isRelatedBy(O.LHS, O.RHS, ICmpInst::getSwappedPredicate(O.Op))) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002080 if (!makeEqual(O.RHS, O.LHS))
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002081 UB.mark(TopBB);
2082 } else {
2083 if (isRelatedBy(O.LHS, O.RHS, ICmpInst::getInversePredicate(O.Op))){
Nick Lewycky15245952007-02-04 23:43:05 +00002084 UB.mark(TopBB);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002085 WorkList.pop_front();
2086 continue;
2087 }
2088
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002089 unsigned n1 = IG.getNode(O.LHS, Top);
2090 unsigned n2 = IG.getNode(O.RHS, Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002091
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002092 if (n1 && n1 == n2) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002093 if (O.Op != ICmpInst::ICMP_UGE && O.Op != ICmpInst::ICMP_ULE &&
2094 O.Op != ICmpInst::ICMP_SGE && O.Op != ICmpInst::ICMP_SLE)
2095 UB.mark(TopBB);
2096
2097 WorkList.pop_front();
2098 continue;
2099 }
2100
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002101 if (VR.isRelatedBy(O.LHS, O.RHS, Top, LV) ||
2102 (n1 && n2 && IG.isRelatedBy(n1, n2, Top, LV))) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002103 WorkList.pop_front();
2104 continue;
2105 }
2106
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002107 VR.addInequality(O.LHS, O.RHS, Top, LV, this);
2108 if ((!isa<ConstantInt>(O.RHS) && !isa<ConstantInt>(O.LHS)) ||
2109 LV == NE) {
2110 if (!n1) n1 = IG.newNode(O.LHS);
2111 if (!n2) n2 = IG.newNode(O.RHS);
2112 IG.addInequality(n1, n2, Top, LV);
Nick Lewycky15245952007-02-04 23:43:05 +00002113 }
2114
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002115 if (Instruction *I1 = dyn_cast<Instruction>(O.LHS)) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002116 if (aboveOrBelow(I1))
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002117 defToOps(I1);
2118 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002119 if (isa<Instruction>(O.LHS) || isa<Argument>(O.LHS)) {
2120 for (Value::use_iterator UI = O.LHS->use_begin(),
2121 UE = O.LHS->use_end(); UI != UE;) {
2122 Use &TheUse = UI.getUse();
2123 ++UI;
2124 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002125 if (aboveOrBelow(I))
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002126 opsToDef(I);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002127 }
2128 }
2129 }
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002130 if (Instruction *I2 = dyn_cast<Instruction>(O.RHS)) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002131 if (aboveOrBelow(I2))
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002132 defToOps(I2);
2133 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002134 if (isa<Instruction>(O.RHS) || isa<Argument>(O.RHS)) {
2135 for (Value::use_iterator UI = O.RHS->use_begin(),
2136 UE = O.RHS->use_end(); UI != UE;) {
2137 Use &TheUse = UI.getUse();
2138 ++UI;
2139 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002140 if (aboveOrBelow(I))
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002141 opsToDef(I);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002142 }
2143 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00002144 }
2145 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00002146 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002147 WorkList.pop_front();
Nick Lewycky9d17c822006-10-25 23:48:24 +00002148 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00002149 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002150 };
2151
Nick Lewycky3bb6de82007-04-07 03:36:51 +00002152 void ValueRanges::addToWorklist(Value *V, Constant *C,
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002153 ICmpInst::Predicate Pred, VRPSolver *VRP) {
Nick Lewycky3bb6de82007-04-07 03:36:51 +00002154 VRP->add(V, C, Pred, VRP->TopInst);
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002155 }
2156
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00002157 void ValueRanges::markBlock(VRPSolver *VRP) {
2158 VRP->UB.mark(VRP->TopBB);
2159 }
2160
Nick Lewycky17d20fd2007-03-18 01:09:32 +00002161#ifndef NDEBUG
Nick Lewycky26e25d32007-06-24 04:36:20 +00002162 bool ValueRanges::isCanonical(Value *V, DomTreeDFS::Node *Subtree,
2163 VRPSolver *VRP) {
Nick Lewycky17d20fd2007-03-18 01:09:32 +00002164 return V == VRP->IG.canonicalize(V, Subtree);
2165 }
2166#endif
2167
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002168 /// PredicateSimplifier - This class is a simplifier that replaces
2169 /// one equivalent variable with another. It also tracks what
2170 /// can't be equal and will solve setcc instructions when possible.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002171 /// @brief Root of the predicate simplifier optimization.
2172 class VISIBILITY_HIDDEN PredicateSimplifier : public FunctionPass {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002173 DomTreeDFS *DTDFS;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002174 bool modified;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002175 InequalityGraph *IG;
2176 UnreachableBlocks UB;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002177 ValueRanges *VR;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002178
Nick Lewycky26e25d32007-06-24 04:36:20 +00002179 std::vector<DomTreeDFS::Node *> WorkList;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002180
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002181 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +00002182 static char ID; // Pass identification, replacement for typeid
Devang Patel09f162c2007-05-01 21:15:47 +00002183 PredicateSimplifier() : FunctionPass((intptr_t)&ID) {}
2184
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002185 bool runOnFunction(Function &F);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002186
2187 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
2188 AU.addRequiredID(BreakCriticalEdgesID);
Owen Anderson510fefc2007-04-25 04:18:54 +00002189 AU.addRequired<DominatorTree>();
Nick Lewycky12d44ab2007-04-07 03:16:12 +00002190 AU.addRequired<TargetData>();
2191 AU.addPreserved<TargetData>();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002192 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002193
2194 private:
Nick Lewycky77e030b2006-10-12 02:02:44 +00002195 /// Forwards - Adds new properties into PropertySet and uses them to
2196 /// simplify instructions. Because new properties sometimes apply to
2197 /// a transition from one BasicBlock to another, this will use the
2198 /// PredicateSimplifier::proceedToSuccessor(s) interface to enter the
2199 /// basic block with the new PropertySet.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002200 /// @brief Performs abstract execution of the program.
2201 class VISIBILITY_HIDDEN Forwards : public InstVisitor<Forwards> {
Nick Lewycky77e030b2006-10-12 02:02:44 +00002202 friend class InstVisitor<Forwards>;
2203 PredicateSimplifier *PS;
Nick Lewycky26e25d32007-06-24 04:36:20 +00002204 DomTreeDFS::Node *DTNode;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002205
Nick Lewycky77e030b2006-10-12 02:02:44 +00002206 public:
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002207 InequalityGraph &IG;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002208 UnreachableBlocks &UB;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002209 ValueRanges &VR;
Nick Lewycky77e030b2006-10-12 02:02:44 +00002210
Nick Lewycky26e25d32007-06-24 04:36:20 +00002211 Forwards(PredicateSimplifier *PS, DomTreeDFS::Node *DTNode)
Owen Anderson510fefc2007-04-25 04:18:54 +00002212 : PS(PS), DTNode(DTNode), IG(*PS->IG), UB(PS->UB), VR(*PS->VR) {}
Nick Lewycky77e030b2006-10-12 02:02:44 +00002213
2214 void visitTerminatorInst(TerminatorInst &TI);
2215 void visitBranchInst(BranchInst &BI);
2216 void visitSwitchInst(SwitchInst &SI);
2217
Nick Lewyckyf3450082006-10-22 19:53:27 +00002218 void visitAllocaInst(AllocaInst &AI);
Nick Lewycky77e030b2006-10-12 02:02:44 +00002219 void visitLoadInst(LoadInst &LI);
2220 void visitStoreInst(StoreInst &SI);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002221
Nick Lewycky15245952007-02-04 23:43:05 +00002222 void visitSExtInst(SExtInst &SI);
2223 void visitZExtInst(ZExtInst &ZI);
2224
Nick Lewycky77e030b2006-10-12 02:02:44 +00002225 void visitBinaryOperator(BinaryOperator &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002226 void visitICmpInst(ICmpInst &IC);
Nick Lewycky77e030b2006-10-12 02:02:44 +00002227 };
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002228
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002229 // Used by terminator instructions to proceed from the current basic
2230 // block to the next. Verifies that "current" dominates "next",
2231 // then calls visitBasicBlock.
Nick Lewycky26e25d32007-06-24 04:36:20 +00002232 void proceedToSuccessors(DomTreeDFS::Node *Current) {
2233 for (DomTreeDFS::Node::iterator I = Current->begin(),
Owen Anderson510fefc2007-04-25 04:18:54 +00002234 E = Current->end(); I != E; ++I) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002235 WorkList.push_back(*I);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002236 }
2237 }
2238
Nick Lewycky26e25d32007-06-24 04:36:20 +00002239 void proceedToSuccessor(DomTreeDFS::Node *Next) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002240 WorkList.push_back(Next);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002241 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002242
2243 // Visits each instruction in the basic block.
Nick Lewycky26e25d32007-06-24 04:36:20 +00002244 void visitBasicBlock(DomTreeDFS::Node *Node) {
Owen Anderson510fefc2007-04-25 04:18:54 +00002245 BasicBlock *BB = Node->getBlock();
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002246 DOUT << "Entering Basic Block: " << BB->getName()
Nick Lewycky26e25d32007-06-24 04:36:20 +00002247 << " (" << Node->getDFSNumIn() << ")\n";
Bill Wendling22e978a2006-12-07 20:04:42 +00002248 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002249 visitInstruction(I++, Node);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002250 }
2251 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002252
Nick Lewycky9a22d7b2006-09-10 02:27:07 +00002253 // Tries to simplify each Instruction and add new properties to
Nick Lewycky77e030b2006-10-12 02:02:44 +00002254 // the PropertySet.
Nick Lewycky26e25d32007-06-24 04:36:20 +00002255 void visitInstruction(Instruction *I, DomTreeDFS::Node *DT) {
Bill Wendling22e978a2006-12-07 20:04:42 +00002256 DOUT << "Considering instruction " << *I << "\n";
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002257 DEBUG(IG->dump());
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002258
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002259 // Sometimes instructions are killed in earlier analysis.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002260 if (isInstructionTriviallyDead(I)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002261 ++NumSimple;
2262 modified = true;
2263 IG->remove(I);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002264 I->eraseFromParent();
2265 return;
2266 }
2267
Nick Lewycky42944462007-01-13 02:05:28 +00002268#ifndef NDEBUG
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002269 // Try to replace the whole instruction.
Nick Lewycky26e25d32007-06-24 04:36:20 +00002270 Value *V = IG->canonicalize(I, DT);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002271 assert(V == I && "Late instruction canonicalization.");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002272 if (V != I) {
2273 modified = true;
2274 ++NumInstruction;
Bill Wendling22e978a2006-12-07 20:04:42 +00002275 DOUT << "Removing " << *I << ", replacing with " << *V << "\n";
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002276 IG->remove(I);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002277 I->replaceAllUsesWith(V);
2278 I->eraseFromParent();
2279 return;
2280 }
2281
2282 // Try to substitute operands.
2283 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2284 Value *Oper = I->getOperand(i);
Nick Lewycky26e25d32007-06-24 04:36:20 +00002285 Value *V = IG->canonicalize(Oper, DT);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002286 assert(V == Oper && "Late operand canonicalization.");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002287 if (V != Oper) {
2288 modified = true;
2289 ++NumVarsReplaced;
Bill Wendling22e978a2006-12-07 20:04:42 +00002290 DOUT << "Resolving " << *I;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002291 I->setOperand(i, V);
Bill Wendling22e978a2006-12-07 20:04:42 +00002292 DOUT << " into " << *I;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002293 }
2294 }
Nick Lewycky42944462007-01-13 02:05:28 +00002295#endif
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002296
Nick Lewycky4f73de22007-03-16 02:37:39 +00002297 std::string name = I->getParent()->getName();
2298 DOUT << "push (%" << name << ")\n";
Owen Anderson510fefc2007-04-25 04:18:54 +00002299 Forwards visit(this, DT);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002300 visit.visit(*I);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002301 DOUT << "pop (%" << name << ")\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002302 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002303 };
2304
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002305 bool PredicateSimplifier::runOnFunction(Function &F) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002306 DominatorTree *DT = &getAnalysis<DominatorTree>();
2307 DTDFS = new DomTreeDFS(DT);
Nick Lewycky12d44ab2007-04-07 03:16:12 +00002308 TargetData *TD = &getAnalysis<TargetData>();
2309
Bill Wendling22e978a2006-12-07 20:04:42 +00002310 DOUT << "Entering Function: " << F.getName() << "\n";
Nick Lewyckycfff1c32006-09-20 17:04:01 +00002311
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002312 modified = false;
Nick Lewycky26e25d32007-06-24 04:36:20 +00002313 DomTreeDFS::Node *Root = DTDFS->getRootNode();
2314 IG = new InequalityGraph(Root);
Nick Lewycky12d44ab2007-04-07 03:16:12 +00002315 VR = new ValueRanges(TD);
Nick Lewycky26e25d32007-06-24 04:36:20 +00002316 WorkList.push_back(Root);
Nick Lewyckycfff1c32006-09-20 17:04:01 +00002317
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002318 do {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002319 DomTreeDFS::Node *DTNode = WorkList.back();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002320 WorkList.pop_back();
Owen Anderson510fefc2007-04-25 04:18:54 +00002321 if (!UB.isDead(DTNode->getBlock())) visitBasicBlock(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002322 } while (!WorkList.empty());
Nick Lewyckycfff1c32006-09-20 17:04:01 +00002323
Nick Lewycky26e25d32007-06-24 04:36:20 +00002324 delete DTDFS;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002325 delete VR;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002326 delete IG;
2327
2328 modified |= UB.kill();
Nick Lewyckycfff1c32006-09-20 17:04:01 +00002329
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002330 return modified;
Nick Lewycky8e559932006-09-02 19:40:38 +00002331 }
2332
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002333 void PredicateSimplifier::Forwards::visitTerminatorInst(TerminatorInst &TI) {
Owen Anderson510fefc2007-04-25 04:18:54 +00002334 PS->proceedToSuccessors(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002335 }
2336
2337 void PredicateSimplifier::Forwards::visitBranchInst(BranchInst &BI) {
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002338 if (BI.isUnconditional()) {
Owen Anderson510fefc2007-04-25 04:18:54 +00002339 PS->proceedToSuccessors(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002340 return;
2341 }
2342
2343 Value *Condition = BI.getCondition();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002344 BasicBlock *TrueDest = BI.getSuccessor(0);
2345 BasicBlock *FalseDest = BI.getSuccessor(1);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002346
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002347 if (isa<Constant>(Condition) || TrueDest == FalseDest) {
Owen Anderson510fefc2007-04-25 04:18:54 +00002348 PS->proceedToSuccessors(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002349 return;
2350 }
2351
Nick Lewycky26e25d32007-06-24 04:36:20 +00002352 for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
Owen Anderson510fefc2007-04-25 04:18:54 +00002353 I != E; ++I) {
2354 BasicBlock *Dest = (*I)->getBlock();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002355 DOUT << "Branch thinking about %" << Dest->getName()
Nick Lewycky26e25d32007-06-24 04:36:20 +00002356 << "(" << PS->DTDFS->getNodeForBlock(Dest)->getDFSNumIn() << ")\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002357
2358 if (Dest == TrueDest) {
Owen Anderson510fefc2007-04-25 04:18:54 +00002359 DOUT << "(" << DTNode->getBlock()->getName() << ") true set:\n";
Nick Lewycky26e25d32007-06-24 04:36:20 +00002360 VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, Dest);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002361 VRP.add(ConstantInt::getTrue(), Condition, ICmpInst::ICMP_EQ);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002362 VRP.solve();
2363 DEBUG(IG.dump());
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002364 } else if (Dest == FalseDest) {
Owen Anderson510fefc2007-04-25 04:18:54 +00002365 DOUT << "(" << DTNode->getBlock()->getName() << ") false set:\n";
Nick Lewycky26e25d32007-06-24 04:36:20 +00002366 VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, Dest);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002367 VRP.add(ConstantInt::getFalse(), Condition, ICmpInst::ICMP_EQ);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002368 VRP.solve();
2369 DEBUG(IG.dump());
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002370 }
2371
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002372 PS->proceedToSuccessor(*I);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002373 }
2374 }
2375
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002376 void PredicateSimplifier::Forwards::visitSwitchInst(SwitchInst &SI) {
2377 Value *Condition = SI.getCondition();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002378
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002379 // Set the EQProperty in each of the cases BBs, and the NEProperties
2380 // in the default BB.
Owen Anderson510fefc2007-04-25 04:18:54 +00002381
Nick Lewycky26e25d32007-06-24 04:36:20 +00002382 for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
Owen Anderson510fefc2007-04-25 04:18:54 +00002383 I != E; ++I) {
2384 BasicBlock *BB = (*I)->getBlock();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002385 DOUT << "Switch thinking about BB %" << BB->getName()
Nick Lewycky26e25d32007-06-24 04:36:20 +00002386 << "(" << PS->DTDFS->getNodeForBlock(BB)->getDFSNumIn() << ")\n";
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002387
Nick Lewycky26e25d32007-06-24 04:36:20 +00002388 VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, BB);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002389 if (BB == SI.getDefaultDest()) {
2390 for (unsigned i = 1, e = SI.getNumCases(); i < e; ++i)
2391 if (SI.getSuccessor(i) != BB)
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002392 VRP.add(Condition, SI.getCaseValue(i), ICmpInst::ICMP_NE);
2393 VRP.solve();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002394 } else if (ConstantInt *CI = SI.findCaseDest(BB)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002395 VRP.add(Condition, CI, ICmpInst::ICMP_EQ);
2396 VRP.solve();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002397 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002398 PS->proceedToSuccessor(*I);
Nick Lewycky1d00f3e2006-10-03 15:19:11 +00002399 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002400 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002401
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002402 void PredicateSimplifier::Forwards::visitAllocaInst(AllocaInst &AI) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002403 VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &AI);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002404 VRP.add(Constant::getNullValue(AI.getType()), &AI, ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002405 VRP.solve();
2406 }
Nick Lewyckyf3450082006-10-22 19:53:27 +00002407
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002408 void PredicateSimplifier::Forwards::visitLoadInst(LoadInst &LI) {
2409 Value *Ptr = LI.getPointerOperand();
2410 // avoid "load uint* null" -> null NE null.
2411 if (isa<Constant>(Ptr)) return;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002412
Nick Lewycky26e25d32007-06-24 04:36:20 +00002413 VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &LI);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002414 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002415 VRP.solve();
2416 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002417
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002418 void PredicateSimplifier::Forwards::visitStoreInst(StoreInst &SI) {
2419 Value *Ptr = SI.getPointerOperand();
2420 if (isa<Constant>(Ptr)) return;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002421
Nick Lewycky26e25d32007-06-24 04:36:20 +00002422 VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &SI);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002423 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002424 VRP.solve();
2425 }
2426
Nick Lewycky15245952007-02-04 23:43:05 +00002427 void PredicateSimplifier::Forwards::visitSExtInst(SExtInst &SI) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002428 VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &SI);
Reid Spencerc34dedf2007-03-03 00:48:31 +00002429 uint32_t SrcBitWidth = cast<IntegerType>(SI.getSrcTy())->getBitWidth();
2430 uint32_t DstBitWidth = cast<IntegerType>(SI.getDestTy())->getBitWidth();
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00002431 APInt Min(APInt::getHighBitsSet(DstBitWidth, DstBitWidth-SrcBitWidth+1));
2432 APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth-1));
Reid Spencerc34dedf2007-03-03 00:48:31 +00002433 VRP.add(ConstantInt::get(Min), &SI, ICmpInst::ICMP_SLE);
2434 VRP.add(ConstantInt::get(Max), &SI, ICmpInst::ICMP_SGE);
Nick Lewycky15245952007-02-04 23:43:05 +00002435 VRP.solve();
2436 }
2437
2438 void PredicateSimplifier::Forwards::visitZExtInst(ZExtInst &ZI) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002439 VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &ZI);
Reid Spencerc34dedf2007-03-03 00:48:31 +00002440 uint32_t SrcBitWidth = cast<IntegerType>(ZI.getSrcTy())->getBitWidth();
2441 uint32_t DstBitWidth = cast<IntegerType>(ZI.getDestTy())->getBitWidth();
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00002442 APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth));
Reid Spencerc34dedf2007-03-03 00:48:31 +00002443 VRP.add(ConstantInt::get(Max), &ZI, ICmpInst::ICMP_UGE);
Nick Lewycky15245952007-02-04 23:43:05 +00002444 VRP.solve();
2445 }
2446
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002447 void PredicateSimplifier::Forwards::visitBinaryOperator(BinaryOperator &BO) {
2448 Instruction::BinaryOps ops = BO.getOpcode();
2449
2450 switch (ops) {
Nick Lewycky4f73de22007-03-16 02:37:39 +00002451 default: break;
Nick Lewycky15245952007-02-04 23:43:05 +00002452 case Instruction::URem:
2453 case Instruction::SRem:
2454 case Instruction::UDiv:
2455 case Instruction::SDiv: {
2456 Value *Divisor = BO.getOperand(1);
Nick Lewycky26e25d32007-06-24 04:36:20 +00002457 VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky15245952007-02-04 23:43:05 +00002458 VRP.add(Constant::getNullValue(Divisor->getType()), Divisor,
2459 ICmpInst::ICMP_NE);
2460 VRP.solve();
2461 break;
2462 }
Nick Lewycky4f73de22007-03-16 02:37:39 +00002463 }
2464
2465 switch (ops) {
2466 default: break;
2467 case Instruction::Shl: {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002468 VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002469 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
2470 VRP.solve();
2471 } break;
2472 case Instruction::AShr: {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002473 VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002474 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_SLE);
2475 VRP.solve();
2476 } break;
2477 case Instruction::LShr:
2478 case Instruction::UDiv: {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002479 VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002480 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
2481 VRP.solve();
2482 } break;
2483 case Instruction::URem: {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002484 VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002485 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
2486 VRP.solve();
2487 } break;
2488 case Instruction::And: {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002489 VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002490 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
2491 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
2492 VRP.solve();
2493 } break;
2494 case Instruction::Or: {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002495 VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002496 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
2497 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_UGE);
2498 VRP.solve();
2499 } break;
2500 }
2501 }
2502
2503 void PredicateSimplifier::Forwards::visitICmpInst(ICmpInst &IC) {
2504 // If possible, squeeze the ICmp predicate into something simpler.
2505 // Eg., if x = [0, 4) and we're being asked icmp uge %x, 3 then change
2506 // the predicate to eq.
2507
Nick Lewyckyeeb01b42007-04-07 02:30:14 +00002508 // XXX: once we do full PHI handling, modifying the instruction in the
2509 // Forwards visitor will cause missed optimizations.
2510
Nick Lewycky4f73de22007-03-16 02:37:39 +00002511 ICmpInst::Predicate Pred = IC.getPredicate();
2512
Nick Lewyckyeeb01b42007-04-07 02:30:14 +00002513 switch (Pred) {
2514 default: break;
2515 case ICmpInst::ICMP_ULE: Pred = ICmpInst::ICMP_ULT; break;
2516 case ICmpInst::ICMP_UGE: Pred = ICmpInst::ICMP_UGT; break;
2517 case ICmpInst::ICMP_SLE: Pred = ICmpInst::ICMP_SLT; break;
2518 case ICmpInst::ICMP_SGE: Pred = ICmpInst::ICMP_SGT; break;
2519 }
2520 if (Pred != IC.getPredicate()) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002521 VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &IC);
Nick Lewyckyeeb01b42007-04-07 02:30:14 +00002522 if (VRP.isRelatedBy(IC.getOperand(1), IC.getOperand(0),
2523 ICmpInst::ICMP_NE)) {
2524 ++NumSnuggle;
2525 PS->modified = true;
2526 IC.setPredicate(Pred);
2527 }
2528 }
2529
2530 Pred = IC.getPredicate();
2531
Nick Lewycky4f73de22007-03-16 02:37:39 +00002532 if (ConstantInt *Op1 = dyn_cast<ConstantInt>(IC.getOperand(1))) {
2533 ConstantInt *NextVal = 0;
Nick Lewyckyeeb01b42007-04-07 02:30:14 +00002534 switch (Pred) {
Nick Lewycky4f73de22007-03-16 02:37:39 +00002535 default: break;
2536 case ICmpInst::ICMP_SLT:
2537 case ICmpInst::ICMP_ULT:
2538 if (Op1->getValue() != 0)
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00002539 NextVal = ConstantInt::get(Op1->getValue()-1);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002540 break;
2541 case ICmpInst::ICMP_SGT:
2542 case ICmpInst::ICMP_UGT:
2543 if (!Op1->getValue().isAllOnesValue())
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00002544 NextVal = ConstantInt::get(Op1->getValue()+1);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002545 break;
2546
2547 }
2548 if (NextVal) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002549 VRPSolver VRP(IG, UB, VR, PS->DTDFS, PS->modified, &IC);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002550 if (VRP.isRelatedBy(IC.getOperand(0), NextVal,
2551 ICmpInst::getInversePredicate(Pred))) {
2552 ICmpInst *NewIC = new ICmpInst(ICmpInst::ICMP_EQ, IC.getOperand(0),
2553 NextVal, "", &IC);
2554 NewIC->takeName(&IC);
2555 IC.replaceAllUsesWith(NewIC);
2556 IG.remove(&IC); // XXX: prove this isn't necessary
2557 IC.eraseFromParent();
2558 ++NumSnuggle;
2559 PS->modified = true;
Nick Lewycky4f73de22007-03-16 02:37:39 +00002560 }
2561 }
2562 }
Nick Lewycky5f8f9af2006-08-30 02:46:48 +00002563 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002564
Devang Patel8c78a0b2007-05-03 01:11:54 +00002565 char PredicateSimplifier::ID = 0;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002566 RegisterPass<PredicateSimplifier> X("predsimplify",
2567 "Predicate Simplifier");
2568}
2569
2570FunctionPass *llvm::createPredicateSimplifierPass() {
2571 return new PredicateSimplifier();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002572}