blob: 7b41fb28450a01561e03adc85dedb410ea176427 [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"
Nick Lewyckye635cc42007-07-10 03:28:21 +000095#include "llvm/Assembly/Writer.h"
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000096#include "llvm/Support/CFG.h"
Chris Lattnerf06bb652006-12-06 18:14:47 +000097#include "llvm/Support/Compiler.h"
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +000098#include "llvm/Support/ConstantRange.h"
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000099#include "llvm/Support/Debug.h"
Nick Lewycky77e030b2006-10-12 02:02:44 +0000100#include "llvm/Support/InstVisitor.h"
Nick Lewycky12d44ab2007-04-07 03:16:12 +0000101#include "llvm/Target/TargetData.h"
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000102#include "llvm/Transforms/Utils/Local.h"
103#include <algorithm>
104#include <deque>
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000105#include <sstream>
Nick Lewycky26e25d32007-06-24 04:36:20 +0000106#include <stack>
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000107using namespace llvm;
108
Chris Lattner0e5255b2006-12-19 21:49:03 +0000109STATISTIC(NumVarsReplaced, "Number of argument substitutions");
110STATISTIC(NumInstruction , "Number of instructions removed");
111STATISTIC(NumSimple , "Number of simple replacements");
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000112STATISTIC(NumBlocks , "Number of blocks marked unreachable");
Nick Lewycky4f73de22007-03-16 02:37:39 +0000113STATISTIC(NumSnuggle , "Number of comparisons snuggled");
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000114
Chris Lattner0e5255b2006-12-19 21:49:03 +0000115namespace {
Nick Lewycky26e25d32007-06-24 04:36:20 +0000116 class DomTreeDFS {
117 public:
118 class Node {
119 friend class DomTreeDFS;
120 public:
121 typedef std::vector<Node *>::iterator iterator;
122 typedef std::vector<Node *>::const_iterator const_iterator;
123
124 unsigned getDFSNumIn() const { return DFSin; }
125 unsigned getDFSNumOut() const { return DFSout; }
126
127 BasicBlock *getBlock() const { return BB; }
128
129 iterator begin() { return Children.begin(); }
130 iterator end() { return Children.end(); }
131
132 const_iterator begin() const { return Children.begin(); }
133 const_iterator end() const { return Children.end(); }
134
135 bool dominates(const Node *N) const {
136 return DFSin <= N->DFSin && DFSout >= N->DFSout;
137 }
138
139 bool DominatedBy(const Node *N) const {
140 return N->dominates(this);
141 }
142
143 /// Sorts by the number of descendants. With this, you can iterate
144 /// through a sorted list and the first matching entry is the most
145 /// specific match for your basic block. The order provided is stable;
146 /// DomTreeDFS::Nodes with the same number of descendants are sorted by
147 /// DFS in number.
148 bool operator<(const Node &N) const {
149 unsigned spread = DFSout - DFSin;
150 unsigned N_spread = N.DFSout - N.DFSin;
151 if (spread == N_spread) return DFSin < N.DFSin;
Nick Lewycky73dd6922007-07-05 03:15:00 +0000152 return spread < N_spread;
Nick Lewycky26e25d32007-06-24 04:36:20 +0000153 }
154 bool operator>(const Node &N) const { return N < *this; }
155
156 private:
157 unsigned DFSin, DFSout;
158 BasicBlock *BB;
159
160 std::vector<Node *> Children;
161 };
162
163 // XXX: this may be slow. Instead of using "new" for each node, consider
164 // putting them in a vector to keep them contiguous.
165 explicit DomTreeDFS(DominatorTree *DT) {
166 std::stack<std::pair<Node *, DomTreeNode *> > S;
167
168 Entry = new Node;
169 Entry->BB = DT->getRootNode()->getBlock();
170 S.push(std::make_pair(Entry, DT->getRootNode()));
171
172 NodeMap[Entry->BB] = Entry;
173
174 while (!S.empty()) {
175 std::pair<Node *, DomTreeNode *> &Pair = S.top();
176 Node *N = Pair.first;
177 DomTreeNode *DTNode = Pair.second;
178 S.pop();
179
180 for (DomTreeNode::iterator I = DTNode->begin(), E = DTNode->end();
181 I != E; ++I) {
182 Node *NewNode = new Node;
183 NewNode->BB = (*I)->getBlock();
184 N->Children.push_back(NewNode);
185 S.push(std::make_pair(NewNode, *I));
186
187 NodeMap[NewNode->BB] = NewNode;
188 }
189 }
190
191 renumber();
192
193#ifndef NDEBUG
194 DEBUG(dump());
195#endif
196 }
197
198#ifndef NDEBUG
199 virtual
200#endif
201 ~DomTreeDFS() {
202 std::stack<Node *> S;
203
204 S.push(Entry);
205 while (!S.empty()) {
206 Node *N = S.top(); S.pop();
207
208 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I)
209 S.push(*I);
210
211 delete N;
212 }
213 }
214
Nick Lewyckyb7c0c8a2007-07-16 02:58:37 +0000215 /// getRootNode - This returns the entry node for the CFG of the function.
Nick Lewycky26e25d32007-06-24 04:36:20 +0000216 Node *getRootNode() const { return Entry; }
217
Nick Lewyckyb7c0c8a2007-07-16 02:58:37 +0000218 /// getNodeForBlock - return the node for the specified basic block.
Nick Lewycky26e25d32007-06-24 04:36:20 +0000219 Node *getNodeForBlock(BasicBlock *BB) const {
220 if (!NodeMap.count(BB)) return 0;
Nick Lewycky73dd6922007-07-05 03:15:00 +0000221 return const_cast<DomTreeDFS*>(this)->NodeMap[BB];
Nick Lewycky26e25d32007-06-24 04:36:20 +0000222 }
223
Nick Lewyckyb7c0c8a2007-07-16 02:58:37 +0000224 /// dominates - returns true if the basic block for I1 dominates that of
225 /// the basic block for I2. If the instructions belong to the same basic
226 /// block, the instruction first instruction sequentially in the block is
227 /// considered dominating.
Nick Lewycky26e25d32007-06-24 04:36:20 +0000228 bool dominates(Instruction *I1, Instruction *I2) {
229 BasicBlock *BB1 = I1->getParent(),
230 *BB2 = I2->getParent();
231 if (BB1 == BB2) {
232 if (isa<TerminatorInst>(I1)) return false;
233 if (isa<TerminatorInst>(I2)) return true;
234 if ( isa<PHINode>(I1) && !isa<PHINode>(I2)) return true;
235 if (!isa<PHINode>(I1) && isa<PHINode>(I2)) return false;
236
237 for (BasicBlock::const_iterator I = BB2->begin(), E = BB2->end();
238 I != E; ++I) {
239 if (&*I == I1) return true;
240 else if (&*I == I2) return false;
241 }
242 assert(!"Instructions not found in parent BasicBlock?");
243 } else {
Nick Lewycky0f986fd2007-06-24 04:40:16 +0000244 Node *Node1 = getNodeForBlock(BB1),
Nick Lewycky26e25d32007-06-24 04:36:20 +0000245 *Node2 = getNodeForBlock(BB2);
Nick Lewycky73dd6922007-07-05 03:15:00 +0000246 return Node1 && Node2 && Node1->dominates(Node2);
Nick Lewycky26e25d32007-06-24 04:36:20 +0000247 }
248 }
Nick Lewyckyb7c0c8a2007-07-16 02:58:37 +0000249
Nick Lewycky26e25d32007-06-24 04:36:20 +0000250 private:
Nick Lewyckyb7c0c8a2007-07-16 02:58:37 +0000251 /// renumber - calculates the depth first search numberings and applies
252 /// them onto the nodes.
Nick Lewycky26e25d32007-06-24 04:36:20 +0000253 void renumber() {
254 std::stack<std::pair<Node *, Node::iterator> > S;
255 unsigned n = 0;
256
257 Entry->DFSin = ++n;
258 S.push(std::make_pair(Entry, Entry->begin()));
259
260 while (!S.empty()) {
261 std::pair<Node *, Node::iterator> &Pair = S.top();
262 Node *N = Pair.first;
263 Node::iterator &I = Pair.second;
264
265 if (I == N->end()) {
266 N->DFSout = ++n;
267 S.pop();
268 } else {
269 Node *Next = *I++;
270 Next->DFSin = ++n;
271 S.push(std::make_pair(Next, Next->begin()));
272 }
273 }
274 }
275
276#ifndef NDEBUG
277 virtual void dump() const {
278 dump(*cerr.stream());
279 }
280
281 void dump(std::ostream &os) const {
282 os << "Predicate simplifier DomTreeDFS: \n";
283 dump(Entry, 0, os);
284 os << "\n\n";
285 }
286
287 void dump(Node *N, int depth, std::ostream &os) const {
288 ++depth;
289 for (int i = 0; i < depth; ++i) { os << " "; }
290 os << "[" << depth << "] ";
291
292 os << N->getBlock()->getName() << " (" << N->getDFSNumIn()
293 << ", " << N->getDFSNumOut() << ")\n";
294
295 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I)
296 dump(*I, depth, os);
297 }
298#endif
299
300 Node *Entry;
301 std::map<BasicBlock *, Node *> NodeMap;
302 };
303
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000304 // SLT SGT ULT UGT EQ
305 // 0 1 0 1 0 -- GT 10
306 // 0 1 0 1 1 -- GE 11
307 // 0 1 1 0 0 -- SGTULT 12
308 // 0 1 1 0 1 -- SGEULE 13
Nick Lewycky56639802007-01-29 02:56:54 +0000309 // 0 1 1 1 0 -- SGT 14
310 // 0 1 1 1 1 -- SGE 15
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000311 // 1 0 0 1 0 -- SLTUGT 18
312 // 1 0 0 1 1 -- SLEUGE 19
313 // 1 0 1 0 0 -- LT 20
314 // 1 0 1 0 1 -- LE 21
Nick Lewycky56639802007-01-29 02:56:54 +0000315 // 1 0 1 1 0 -- SLT 22
316 // 1 0 1 1 1 -- SLE 23
317 // 1 1 0 1 0 -- UGT 26
318 // 1 1 0 1 1 -- UGE 27
319 // 1 1 1 0 0 -- ULT 28
320 // 1 1 1 0 1 -- ULE 29
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000321 // 1 1 1 1 0 -- NE 30
322 enum LatticeBits {
323 EQ_BIT = 1, UGT_BIT = 2, ULT_BIT = 4, SGT_BIT = 8, SLT_BIT = 16
324 };
325 enum LatticeVal {
326 GT = SGT_BIT | UGT_BIT,
327 GE = GT | EQ_BIT,
328 LT = SLT_BIT | ULT_BIT,
329 LE = LT | EQ_BIT,
330 NE = SLT_BIT | SGT_BIT | ULT_BIT | UGT_BIT,
331 SGTULT = SGT_BIT | ULT_BIT,
332 SGEULE = SGTULT | EQ_BIT,
333 SLTUGT = SLT_BIT | UGT_BIT,
334 SLEUGE = SLTUGT | EQ_BIT,
Nick Lewycky56639802007-01-29 02:56:54 +0000335 ULT = SLT_BIT | SGT_BIT | ULT_BIT,
336 UGT = SLT_BIT | SGT_BIT | UGT_BIT,
337 SLT = SLT_BIT | ULT_BIT | UGT_BIT,
338 SGT = SGT_BIT | ULT_BIT | UGT_BIT,
339 SLE = SLT | EQ_BIT,
340 SGE = SGT | EQ_BIT,
341 ULE = ULT | EQ_BIT,
342 UGE = UGT | EQ_BIT
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000343 };
344
345 static bool validPredicate(LatticeVal LV) {
346 switch (LV) {
Nick Lewycky15245952007-02-04 23:43:05 +0000347 case GT: case GE: case LT: case LE: case NE:
348 case SGTULT: case SGT: case SGEULE:
349 case SLTUGT: case SLT: case SLEUGE:
350 case ULT: case UGT:
351 case SLE: case SGE: case ULE: case UGE:
352 return true;
353 default:
354 return false;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000355 }
356 }
357
358 /// reversePredicate - reverse the direction of the inequality
359 static LatticeVal reversePredicate(LatticeVal LV) {
360 unsigned reverse = LV ^ (SLT_BIT|SGT_BIT|ULT_BIT|UGT_BIT); //preserve EQ_BIT
Nick Lewycky4f73de22007-03-16 02:37:39 +0000361
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000362 if ((reverse & (SLT_BIT|SGT_BIT)) == 0)
363 reverse |= (SLT_BIT|SGT_BIT);
364
365 if ((reverse & (ULT_BIT|UGT_BIT)) == 0)
366 reverse |= (ULT_BIT|UGT_BIT);
367
368 LatticeVal Rev = static_cast<LatticeVal>(reverse);
369 assert(validPredicate(Rev) && "Failed reversing predicate.");
370 return Rev;
371 }
372
Nick Lewycky73dd6922007-07-05 03:15:00 +0000373 /// ValueNumbering stores the scope-specific value numbers for a given Value.
374 class VISIBILITY_HIDDEN ValueNumbering {
375 class VISIBILITY_HIDDEN VNPair {
376 public:
377 Value *V;
378 unsigned index;
379 DomTreeDFS::Node *Subtree;
380
381 VNPair(Value *V, unsigned index, DomTreeDFS::Node *Subtree)
382 : V(V), index(index), Subtree(Subtree) {}
383
384 bool operator==(const VNPair &RHS) const {
385 return V == RHS.V && Subtree == RHS.Subtree;
386 }
387
388 bool operator<(const VNPair &RHS) const {
389 if (V != RHS.V) return V < RHS.V;
390 return *Subtree < *RHS.Subtree;
391 }
392
393 bool operator<(Value *RHS) const {
394 return V < RHS;
395 }
396 };
397
398 typedef std::vector<VNPair> VNMapType;
399 VNMapType VNMap;
400
401 std::vector<Value *> Values;
402
403 DomTreeDFS *DTDFS;
404
405 public:
Nick Lewyckye635cc42007-07-10 03:28:21 +0000406#ifndef NDEBUG
407 virtual ~ValueNumbering() {}
408 virtual void dump() {
409 dump(*cerr.stream());
410 }
411
412 void dump(std::ostream &os) {
413 for (unsigned i = 1; i <= Values.size(); ++i) {
414 os << i << " = ";
415 WriteAsOperand(os, Values[i-1]);
416 os << " {";
417 for (unsigned j = 0; j < VNMap.size(); ++j) {
418 if (VNMap[j].index == i) {
419 WriteAsOperand(os, VNMap[j].V);
420 os << " (" << VNMap[j].Subtree->getDFSNumIn() << ") ";
421 }
422 }
423 os << "}\n";
424 }
425 }
426#endif
427
Nick Lewycky73dd6922007-07-05 03:15:00 +0000428 /// compare - returns true if V1 is a better canonical value than V2.
429 bool compare(Value *V1, Value *V2) const {
430 if (isa<Constant>(V1))
431 return !isa<Constant>(V2);
432 else if (isa<Constant>(V2))
433 return false;
434 else if (isa<Argument>(V1))
435 return !isa<Argument>(V2);
436 else if (isa<Argument>(V2))
437 return false;
438
439 Instruction *I1 = dyn_cast<Instruction>(V1);
440 Instruction *I2 = dyn_cast<Instruction>(V2);
441
442 if (!I1 || !I2)
443 return V1->getNumUses() < V2->getNumUses();
444
445 return DTDFS->dominates(I1, I2);
446 }
447
448 ValueNumbering(DomTreeDFS *DTDFS) : DTDFS(DTDFS) {}
449
450 /// valueNumber - finds the value number for V under the Subtree. If
451 /// there is no value number, returns zero.
452 unsigned valueNumber(Value *V, DomTreeDFS::Node *Subtree) {
Nick Lewyckye635cc42007-07-10 03:28:21 +0000453 if (!(isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V))
454 || V->getType() == Type::VoidTy) return 0;
455
Nick Lewycky73dd6922007-07-05 03:15:00 +0000456 VNMapType::iterator E = VNMap.end();
457 VNPair pair(V, 0, Subtree);
458 VNMapType::iterator I = std::lower_bound(VNMap.begin(), E, pair);
459 while (I != E && I->V == V) {
460 if (I->Subtree->dominates(Subtree))
461 return I->index;
462 ++I;
463 }
464 return 0;
465 }
466
Nick Lewyckye635cc42007-07-10 03:28:21 +0000467 /// getOrInsertVN - always returns a value number, creating it if necessary.
468 unsigned getOrInsertVN(Value *V, DomTreeDFS::Node *Subtree) {
469 if (unsigned n = valueNumber(V, Subtree))
470 return n;
471 else
472 return newVN(V);
473 }
474
Nick Lewycky73dd6922007-07-05 03:15:00 +0000475 /// newVN - creates a new value number. Value V must not already have a
476 /// value number assigned.
477 unsigned newVN(Value *V) {
Nick Lewyckye635cc42007-07-10 03:28:21 +0000478 assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
479 "Bad Value for value numbering.");
480 assert(V->getType() != Type::VoidTy && "Won't value number a void value");
481
Nick Lewycky73dd6922007-07-05 03:15:00 +0000482 Values.push_back(V);
483
484 VNPair pair = VNPair(V, Values.size(), DTDFS->getRootNode());
Nick Lewyckye635cc42007-07-10 03:28:21 +0000485 VNMapType::iterator I = std::lower_bound(VNMap.begin(), VNMap.end(), pair);
486 assert((I == VNMap.end() || value(I->index) != V) &&
Nick Lewycky73dd6922007-07-05 03:15:00 +0000487 "Attempt to create a duplicate value number.");
Nick Lewyckye635cc42007-07-10 03:28:21 +0000488 VNMap.insert(I, pair);
Nick Lewycky73dd6922007-07-05 03:15:00 +0000489
490 return Values.size();
491 }
492
493 /// value - returns the Value associated with a value number.
494 Value *value(unsigned index) const {
495 assert(index != 0 && "Zero index is reserved for not found.");
496 assert(index <= Values.size() && "Index out of range.");
497 return Values[index-1];
498 }
499
500 /// canonicalize - return a Value that is equal to V under Subtree.
501 Value *canonicalize(Value *V, DomTreeDFS::Node *Subtree) {
502 if (isa<Constant>(V)) return V;
503
504 if (unsigned n = valueNumber(V, Subtree))
505 return value(n);
506 else
507 return V;
508 }
509
510 /// addEquality - adds that value V belongs to the set of equivalent
511 /// values defined by value number n under Subtree.
512 void addEquality(unsigned n, Value *V, DomTreeDFS::Node *Subtree) {
513 assert(canonicalize(value(n), Subtree) == value(n) &&
514 "Node's 'canonical' choice isn't best within this subtree.");
515
516 // Suppose that we are given "%x -> node #1 (%y)". The problem is that
517 // we may already have "%z -> node #2 (%x)" somewhere above us in the
518 // graph. We need to find those edges and add "%z -> node #1 (%y)"
519 // to keep the lookups canonical.
520
521 std::vector<Value *> ToRepoint(1, V);
522
523 if (unsigned Conflict = valueNumber(V, Subtree)) {
524 for (VNMapType::iterator I = VNMap.begin(), E = VNMap.end();
525 I != E; ++I) {
526 if (I->index == Conflict && I->Subtree->dominates(Subtree))
527 ToRepoint.push_back(I->V);
528 }
529 }
530
531 for (std::vector<Value *>::iterator VI = ToRepoint.begin(),
532 VE = ToRepoint.end(); VI != VE; ++VI) {
533 Value *V = *VI;
534
535 VNPair pair(V, n, Subtree);
536 VNMapType::iterator B = VNMap.begin(), E = VNMap.end();
537 VNMapType::iterator I = std::lower_bound(B, E, pair);
538 if (I != E && I->V == V && I->Subtree == Subtree)
539 I->index = n; // Update best choice
Nick Lewyckye635cc42007-07-10 03:28:21 +0000540 else
Nick Lewycky73dd6922007-07-05 03:15:00 +0000541 VNMap.insert(I, pair); // New Value
542
543 // XXX: we currently don't have to worry about updating values with
544 // more specific Subtrees, but we will need to for PHI node support.
545
546#ifndef NDEBUG
547 Value *V_n = value(n);
548 if (isa<Constant>(V) && isa<Constant>(V_n)) {
549 assert(V == V_n && "Constant equals different constant?");
550 }
551#endif
552 }
553 }
554
555 /// remove - removes all references to value V.
556 void remove(Value *V) {
Nick Lewyckye635cc42007-07-10 03:28:21 +0000557 VNMapType::iterator B = VNMap.begin(), E = VNMap.end();
Nick Lewycky73dd6922007-07-05 03:15:00 +0000558 VNPair pair(V, 0, DTDFS->getRootNode());
Nick Lewyckye635cc42007-07-10 03:28:21 +0000559 VNMapType::iterator J = std::upper_bound(B, E, pair);
Nick Lewycky73dd6922007-07-05 03:15:00 +0000560 VNMapType::iterator I = J;
561
Nick Lewyckye635cc42007-07-10 03:28:21 +0000562 while (I != B && (I == E || I->V == V)) --I;
Nick Lewycky73dd6922007-07-05 03:15:00 +0000563
564 VNMap.erase(I, J);
565 }
566 };
567
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000568 /// The InequalityGraph stores the relationships between values.
569 /// Each Value in the graph is assigned to a Node. Nodes are pointer
570 /// comparable for equality. The caller is expected to maintain the logical
571 /// consistency of the system.
572 ///
573 /// The InequalityGraph class may invalidate Node*s after any mutator call.
574 /// @brief The InequalityGraph stores the relationships between values.
575 class VISIBILITY_HIDDEN InequalityGraph {
Nick Lewycky73dd6922007-07-05 03:15:00 +0000576 ValueNumbering &VN;
Nick Lewycky26e25d32007-06-24 04:36:20 +0000577 DomTreeDFS::Node *TreeRoot;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000578
579 InequalityGraph(); // DO NOT IMPLEMENT
580 InequalityGraph(InequalityGraph &); // DO NOT IMPLEMENT
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000581 public:
Nick Lewycky73dd6922007-07-05 03:15:00 +0000582 InequalityGraph(ValueNumbering &VN, DomTreeDFS::Node *TreeRoot)
583 : VN(VN), TreeRoot(TreeRoot) {}
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000584
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000585 class Node;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000586
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000587 /// An Edge is contained inside a Node making one end of the edge implicit
588 /// and contains a pointer to the other end. The edge contains a lattice
Nick Lewycky26e25d32007-06-24 04:36:20 +0000589 /// value specifying the relationship and an DomTreeDFS::Node specifying
590 /// the root in the dominator tree to which this edge applies.
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000591 class VISIBILITY_HIDDEN Edge {
592 public:
Nick Lewycky26e25d32007-06-24 04:36:20 +0000593 Edge(unsigned T, LatticeVal V, DomTreeDFS::Node *ST)
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000594 : To(T), LV(V), Subtree(ST) {}
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000595
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000596 unsigned To;
597 LatticeVal LV;
Nick Lewycky26e25d32007-06-24 04:36:20 +0000598 DomTreeDFS::Node *Subtree;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000599
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000600 bool operator<(const Edge &edge) const {
601 if (To != edge.To) return To < edge.To;
Nick Lewycky73dd6922007-07-05 03:15:00 +0000602 return *Subtree < *edge.Subtree;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000603 }
Nick Lewycky26e25d32007-06-24 04:36:20 +0000604
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000605 bool operator<(unsigned to) const {
606 return To < to;
607 }
Nick Lewycky26e25d32007-06-24 04:36:20 +0000608
Bill Wendling6357bf22007-06-04 23:52:59 +0000609 bool operator>(unsigned to) const {
610 return To > to;
611 }
612
613 friend bool operator<(unsigned to, const Edge &edge) {
614 return edge.operator>(to);
615 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000616 };
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000617
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000618 /// A single node in the InequalityGraph. This stores the canonical Value
619 /// for the node, as well as the relationships with the neighbours.
620 ///
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000621 /// @brief A single node in the InequalityGraph.
622 class VISIBILITY_HIDDEN Node {
623 friend class InequalityGraph;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000624
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000625 typedef SmallVector<Edge, 4> RelationsType;
626 RelationsType Relations;
627
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000628 // TODO: can this idea improve performance?
629 //friend class std::vector<Node>;
630 //Node(Node &N) { RelationsType.swap(N.RelationsType); }
631
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000632 public:
633 typedef RelationsType::iterator iterator;
634 typedef RelationsType::const_iterator const_iterator;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000635
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000636#ifndef NDEBUG
Nick Lewycky5d6ede52007-01-11 02:38:21 +0000637 virtual ~Node() {}
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000638 virtual void dump() const {
639 dump(*cerr.stream());
640 }
641 private:
Nick Lewycky73dd6922007-07-05 03:15:00 +0000642 void dump(std::ostream &os) const {
643 static const std::string names[32] =
644 { "000000", "000001", "000002", "000003", "000004", "000005",
645 "000006", "000007", "000008", "000009", " >", " >=",
646 " s>u<", "s>=u<=", " s>", " s>=", "000016", "000017",
647 " s<u>", "s<=u>=", " <", " <=", " s<", " s<=",
648 "000024", "000025", " u>", " u>=", " u<", " u<=",
649 " !=", "000031" };
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000650 for (Node::const_iterator NI = begin(), NE = end(); NI != NE; ++NI) {
Nick Lewycky73dd6922007-07-05 03:15:00 +0000651 os << names[NI->LV] << " " << NI->To
Nick Lewyckye635cc42007-07-10 03:28:21 +0000652 << " (" << NI->Subtree->getDFSNumIn() << "), ";
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000653 }
654 }
Nick Lewycky73dd6922007-07-05 03:15:00 +0000655 public:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000656#endif
657
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000658 iterator begin() { return Relations.begin(); }
659 iterator end() { return Relations.end(); }
660 const_iterator begin() const { return Relations.begin(); }
661 const_iterator end() const { return Relations.end(); }
662
Nick Lewycky26e25d32007-06-24 04:36:20 +0000663 iterator find(unsigned n, DomTreeDFS::Node *Subtree) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000664 iterator E = end();
665 for (iterator I = std::lower_bound(begin(), E, n);
666 I != E && I->To == n; ++I) {
667 if (Subtree->DominatedBy(I->Subtree))
668 return I;
669 }
670 return E;
671 }
672
Nick Lewycky26e25d32007-06-24 04:36:20 +0000673 const_iterator find(unsigned n, DomTreeDFS::Node *Subtree) const {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000674 const_iterator E = end();
675 for (const_iterator I = std::lower_bound(begin(), E, n);
676 I != E && I->To == n; ++I) {
677 if (Subtree->DominatedBy(I->Subtree))
678 return I;
679 }
680 return E;
681 }
682
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000683 /// Updates the lattice value for a given node. Create a new entry if
684 /// one doesn't exist, otherwise it merges the values. The new lattice
685 /// value must not be inconsistent with any previously existing value.
Nick Lewycky26e25d32007-06-24 04:36:20 +0000686 void update(unsigned n, LatticeVal R, DomTreeDFS::Node *Subtree) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000687 assert(validPredicate(R) && "Invalid predicate.");
688 iterator I = find(n, Subtree);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000689 if (I == end()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000690 Edge edge(n, R, Subtree);
691 iterator Insert = std::lower_bound(begin(), end(), edge);
692 Relations.insert(Insert, edge);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000693 } else {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000694 LatticeVal LV = static_cast<LatticeVal>(I->LV & R);
695 assert(validPredicate(LV) && "Invalid union of lattice values.");
696 if (LV != I->LV) {
Nick Lewycky6ce36cf2007-01-15 14:30:07 +0000697 if (Subtree != I->Subtree) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000698 assert(Subtree->DominatedBy(I->Subtree) &&
699 "Find returned subtree that doesn't apply.");
700
701 Edge edge(n, R, Subtree);
702 iterator Insert = std::lower_bound(begin(), end(), edge);
Nick Lewycky6ce36cf2007-01-15 14:30:07 +0000703 Relations.insert(Insert, edge); // invalidates I
704 I = find(n, Subtree);
705 }
706
707 // Also, we have to tighten any edge that Subtree dominates.
708 for (iterator B = begin(); I->To == n; --I) {
709 if (I->Subtree->DominatedBy(Subtree)) {
710 LatticeVal LV = static_cast<LatticeVal>(I->LV & R);
Chris Lattner28d921d2007-04-14 23:32:02 +0000711 assert(validPredicate(LV) && "Invalid union of lattice values");
Nick Lewycky6ce36cf2007-01-15 14:30:07 +0000712 I->LV = LV;
713 }
714 if (I == B) break;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000715 }
716 }
Nick Lewycky51ce8d62006-09-13 19:24:01 +0000717 }
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000718 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000719 };
720
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000721 private:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000722
723 std::vector<Node> Nodes;
724
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000725 public:
Nick Lewyckye635cc42007-07-10 03:28:21 +0000726 /// node - returns the node object at a given value number. The pointer
727 /// returned may be invalidated on the next call to node().
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000728 Node *node(unsigned index) {
Nick Lewyckye635cc42007-07-10 03:28:21 +0000729 assert(VN.value(index)); // This triggers the necessary checks.
730 if (Nodes.size() < index) Nodes.resize(index);
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000731 return &Nodes[index-1];
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000732 }
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000733
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000734 /// isRelatedBy - true iff n1 op n2
Nick Lewycky26e25d32007-06-24 04:36:20 +0000735 bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
736 LatticeVal LV) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000737 if (n1 == n2) return LV & EQ_BIT;
738
739 Node *N1 = node(n1);
740 Node::iterator I = N1->find(n2, Subtree), E = N1->end();
741 if (I != E) return (I->LV & LV) == I->LV;
742
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000743 return false;
744 }
745
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000746 // The add* methods assume that your input is logically valid and may
747 // assertion-fail or infinitely loop if you attempt a contradiction.
Nick Lewycky9d17c822006-10-25 23:48:24 +0000748
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000749 /// addInequality - Sets n1 op n2.
750 /// It is also an error to call this on an inequality that is already true.
Nick Lewycky26e25d32007-06-24 04:36:20 +0000751 void addInequality(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000752 LatticeVal LV1) {
753 assert(n1 != n2 && "A node can't be inequal to itself.");
754
755 if (LV1 != NE)
756 assert(!isRelatedBy(n1, n2, Subtree, reversePredicate(LV1)) &&
757 "Contradictory inequality.");
758
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000759 // Suppose we're adding %n1 < %n2. Find all the %a < %n1 and
760 // add %a < %n2 too. This keeps the graph fully connected.
761 if (LV1 != NE) {
Nick Lewycky3bb6de82007-04-07 03:36:51 +0000762 // Break up the relationship into signed and unsigned comparison parts.
763 // If the signed parts of %a op1 %n1 match that of %n1 op2 %n2, and
764 // op1 and op2 aren't NE, then add %a op3 %n2. The new relationship
765 // should have the EQ_BIT iff it's set for both op1 and op2.
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000766
767 unsigned LV1_s = LV1 & (SLT_BIT|SGT_BIT);
768 unsigned LV1_u = LV1 & (ULT_BIT|UGT_BIT);
Nick Lewycky3bb6de82007-04-07 03:36:51 +0000769
Nick Lewyckye635cc42007-07-10 03:28:21 +0000770 for (Node::iterator I = node(n1)->begin(), E = node(n1)->end(); I != E; ++I) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000771 if (I->LV != NE && I->To != n2) {
Nick Lewycky3bb6de82007-04-07 03:36:51 +0000772
Nick Lewycky26e25d32007-06-24 04:36:20 +0000773 DomTreeDFS::Node *Local_Subtree = NULL;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000774 if (Subtree->DominatedBy(I->Subtree))
775 Local_Subtree = Subtree;
776 else if (I->Subtree->DominatedBy(Subtree))
777 Local_Subtree = I->Subtree;
778
779 if (Local_Subtree) {
780 unsigned new_relationship = 0;
781 LatticeVal ILV = reversePredicate(I->LV);
782 unsigned ILV_s = ILV & (SLT_BIT|SGT_BIT);
783 unsigned ILV_u = ILV & (ULT_BIT|UGT_BIT);
784
785 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
786 new_relationship |= ILV_s;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000787 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
788 new_relationship |= ILV_u;
789
790 if (new_relationship) {
791 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
792 new_relationship |= (SLT_BIT|SGT_BIT);
793 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
794 new_relationship |= (ULT_BIT|UGT_BIT);
795 if ((LV1 & EQ_BIT) && (ILV & EQ_BIT))
796 new_relationship |= EQ_BIT;
797
798 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
799
800 node(I->To)->update(n2, NewLV, Local_Subtree);
Nick Lewyckye635cc42007-07-10 03:28:21 +0000801 node(n2)->update(I->To, reversePredicate(NewLV), Local_Subtree);
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000802 }
803 }
804 }
805 }
806
Nick Lewyckye635cc42007-07-10 03:28:21 +0000807 for (Node::iterator I = node(n2)->begin(), E = node(n2)->end(); I != E; ++I) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000808 if (I->LV != NE && I->To != n1) {
Nick Lewycky26e25d32007-06-24 04:36:20 +0000809 DomTreeDFS::Node *Local_Subtree = NULL;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000810 if (Subtree->DominatedBy(I->Subtree))
811 Local_Subtree = Subtree;
812 else if (I->Subtree->DominatedBy(Subtree))
813 Local_Subtree = I->Subtree;
814
815 if (Local_Subtree) {
816 unsigned new_relationship = 0;
817 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
818 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
819
820 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
821 new_relationship |= ILV_s;
822
823 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
824 new_relationship |= ILV_u;
825
826 if (new_relationship) {
827 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
828 new_relationship |= (SLT_BIT|SGT_BIT);
829 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
830 new_relationship |= (ULT_BIT|UGT_BIT);
831 if ((LV1 & EQ_BIT) && (I->LV & EQ_BIT))
832 new_relationship |= EQ_BIT;
833
834 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
835
Nick Lewyckye635cc42007-07-10 03:28:21 +0000836 node(n1)->update(I->To, NewLV, Local_Subtree);
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000837 node(I->To)->update(n1, reversePredicate(NewLV), Local_Subtree);
838 }
839 }
840 }
841 }
842 }
843
Nick Lewyckye635cc42007-07-10 03:28:21 +0000844 node(n1)->update(n2, LV1, Subtree);
845 node(n2)->update(n1, reversePredicate(LV1), Subtree);
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000846 }
Nick Lewycky51ce8d62006-09-13 19:24:01 +0000847
Nick Lewycky73dd6922007-07-05 03:15:00 +0000848 /// remove - removes a node from the graph by removing all references to
849 /// and from it.
850 void remove(unsigned n) {
851 Node *N = node(n);
852 for (Node::iterator NI = N->begin(), NE = N->end(); NI != NE; ++NI) {
853 Node::iterator Iter = node(NI->To)->find(n, TreeRoot);
854 do {
855 node(NI->To)->Relations.erase(Iter);
856 Iter = node(NI->To)->find(n, TreeRoot);
857 } while (Iter != node(NI->To)->end());
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000858 }
Nick Lewycky73dd6922007-07-05 03:15:00 +0000859 N->Relations.clear();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000860 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000861
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000862#ifndef NDEBUG
Nick Lewycky5d6ede52007-01-11 02:38:21 +0000863 virtual ~InequalityGraph() {}
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000864 virtual void dump() {
865 dump(*cerr.stream());
866 }
867
868 void dump(std::ostream &os) {
Nick Lewycky73dd6922007-07-05 03:15:00 +0000869 for (unsigned i = 1; i <= Nodes.size(); ++i) {
870 os << i << " = {";
871 node(i)->dump(os);
872 os << "}\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000873 }
874 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000875#endif
876 };
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000877
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000878 class VRPSolver;
879
880 /// ValueRanges tracks the known integer ranges and anti-ranges of the nodes
881 /// in the InequalityGraph.
882 class VISIBILITY_HIDDEN ValueRanges {
Nick Lewyckye635cc42007-07-10 03:28:21 +0000883 ValueNumbering &VN;
884 TargetData *TD;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000885
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000886 class VISIBILITY_HIDDEN ScopedRange {
Nick Lewyckye635cc42007-07-10 03:28:21 +0000887 typedef std::vector<std::pair<DomTreeDFS::Node *, ConstantRange> >
888 RangeListType;
889 RangeListType RangeList;
890
891 static bool swo(const std::pair<DomTreeDFS::Node *, ConstantRange> &LHS,
892 const std::pair<DomTreeDFS::Node *, ConstantRange> &RHS) {
893 return *LHS.first < *RHS.first;
894 }
895
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000896 public:
Nick Lewyckye635cc42007-07-10 03:28:21 +0000897#ifndef NDEBUG
898 virtual ~ScopedRange() {}
899 virtual void dump() const {
900 dump(*cerr.stream());
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000901 }
902
Nick Lewyckye635cc42007-07-10 03:28:21 +0000903 void dump(std::ostream &os) const {
904 os << "{";
905 for (const_iterator I = begin(), E = end(); I != E; ++I) {
906 os << I->second << " (" << I->first->getDFSNumIn() << "), ";
907 }
908 os << "}";
909 }
910#endif
911
912 typedef RangeListType::iterator iterator;
913 typedef RangeListType::const_iterator const_iterator;
914
915 iterator begin() { return RangeList.begin(); }
916 iterator end() { return RangeList.end(); }
917 const_iterator begin() const { return RangeList.begin(); }
918 const_iterator end() const { return RangeList.end(); }
919
920 iterator find(DomTreeDFS::Node *Subtree) {
921 static ConstantRange empty(1, false);
922 iterator E = end();
923 iterator I = std::lower_bound(begin(), E,
924 std::make_pair(Subtree, empty), swo);
925
926 while (I != E && !I->first->dominates(Subtree)) ++I;
927 return I;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000928 }
Bill Wendling6357bf22007-06-04 23:52:59 +0000929
Nick Lewyckye635cc42007-07-10 03:28:21 +0000930 const_iterator find(DomTreeDFS::Node *Subtree) const {
931 static const ConstantRange empty(1, false);
932 const_iterator E = end();
933 const_iterator I = std::lower_bound(begin(), E,
934 std::make_pair(Subtree, empty), swo);
935
936 while (I != E && !I->first->dominates(Subtree)) ++I;
937 return I;
Bill Wendling6357bf22007-06-04 23:52:59 +0000938 }
939
Nick Lewyckye635cc42007-07-10 03:28:21 +0000940 void update(const ConstantRange &CR, DomTreeDFS::Node *Subtree) {
941 assert(!CR.isEmptySet() && "Empty ConstantRange.");
942 assert(!CR.isSingleElement() && "Won't store single element.");
943
944 static ConstantRange empty(1, false);
945 iterator E = end();
946 iterator I =
947 std::lower_bound(begin(), E, std::make_pair(Subtree, empty), swo);
948
949 if (I != end() && I->first == Subtree) {
Nick Lewycky39519f52007-07-14 04:28:04 +0000950 ConstantRange CR2 = I->second.maximalIntersectWith(CR);
Nick Lewyckye635cc42007-07-10 03:28:21 +0000951 assert(!CR2.isEmptySet() && !CR2.isSingleElement() &&
952 "Invalid union of ranges.");
953 I->second = CR2;
954 } else
955 RangeList.insert(I, std::make_pair(Subtree, CR));
Bill Wendling6357bf22007-06-04 23:52:59 +0000956 }
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000957 };
958
959 std::vector<ScopedRange> Ranges;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000960
Nick Lewyckye635cc42007-07-10 03:28:21 +0000961 void update(unsigned n, const ConstantRange &CR, DomTreeDFS::Node *Subtree){
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000962 if (CR.isFullSet()) return;
Nick Lewyckye635cc42007-07-10 03:28:21 +0000963 if (Ranges.size() < n) Ranges.resize(n);
964 Ranges[n-1].update(CR, Subtree);
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000965 }
966
Nick Lewyckye635cc42007-07-10 03:28:21 +0000967 /// create - Creates a ConstantRange that matches the given LatticeVal
968 /// relation with a given integer.
969 ConstantRange create(LatticeVal LV, const ConstantRange &CR) {
970 assert(!CR.isEmptySet() && "Can't deal with empty set.");
971
972 if (LV == NE)
973 return makeConstantRange(ICmpInst::ICMP_NE, CR);
974
975 unsigned LV_s = LV & (SGT_BIT|SLT_BIT);
976 unsigned LV_u = LV & (UGT_BIT|ULT_BIT);
977 bool hasEQ = LV & EQ_BIT;
978
979 ConstantRange Range(CR.getBitWidth());
980
981 if (LV_s == SGT_BIT) {
Nick Lewycky39519f52007-07-14 04:28:04 +0000982 Range = Range.maximalIntersectWith(makeConstantRange(
Nick Lewyckye635cc42007-07-10 03:28:21 +0000983 hasEQ ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_SGT, CR));
984 } else if (LV_s == SLT_BIT) {
Nick Lewycky39519f52007-07-14 04:28:04 +0000985 Range = Range.maximalIntersectWith(makeConstantRange(
Nick Lewyckye635cc42007-07-10 03:28:21 +0000986 hasEQ ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_SLT, CR));
987 }
988
989 if (LV_u == UGT_BIT) {
Nick Lewycky39519f52007-07-14 04:28:04 +0000990 Range = Range.maximalIntersectWith(makeConstantRange(
Nick Lewyckye635cc42007-07-10 03:28:21 +0000991 hasEQ ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_UGT, CR));
992 } else if (LV_u == ULT_BIT) {
Nick Lewycky39519f52007-07-14 04:28:04 +0000993 Range = Range.maximalIntersectWith(makeConstantRange(
Nick Lewyckye635cc42007-07-10 03:28:21 +0000994 hasEQ ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT, CR));
995 }
996
997 return Range;
998 }
999
1000 /// makeConstantRange - Creates a ConstantRange representing the set of all
1001 /// value that match the ICmpInst::Predicate with any of the values in CR.
1002 ConstantRange makeConstantRange(ICmpInst::Predicate ICmpOpcode,
1003 const ConstantRange &CR) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001004 uint32_t W = CR.getBitWidth();
1005 switch (ICmpOpcode) {
Nick Lewyckye635cc42007-07-10 03:28:21 +00001006 default: assert(!"Invalid ICmp opcode to makeConstantRange()");
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001007 case ICmpInst::ICMP_EQ:
1008 return ConstantRange(CR.getLower(), CR.getUpper());
1009 case ICmpInst::ICMP_NE:
1010 if (CR.isSingleElement())
1011 return ConstantRange(CR.getUpper(), CR.getLower());
1012 return ConstantRange(W);
1013 case ICmpInst::ICMP_ULT:
1014 return ConstantRange(APInt::getMinValue(W), CR.getUnsignedMax());
1015 case ICmpInst::ICMP_SLT:
1016 return ConstantRange(APInt::getSignedMinValue(W), CR.getSignedMax());
1017 case ICmpInst::ICMP_ULE: {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001018 APInt UMax(CR.getUnsignedMax());
Zhou Sheng31787362007-04-26 16:42:07 +00001019 if (UMax.isMaxValue())
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001020 return ConstantRange(W);
1021 return ConstantRange(APInt::getMinValue(W), UMax + 1);
1022 }
1023 case ICmpInst::ICMP_SLE: {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001024 APInt SMax(CR.getSignedMax());
Zhou Sheng31787362007-04-26 16:42:07 +00001025 if (SMax.isMaxSignedValue() || (SMax+1).isMaxSignedValue())
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001026 return ConstantRange(W);
1027 return ConstantRange(APInt::getSignedMinValue(W), SMax + 1);
1028 }
1029 case ICmpInst::ICMP_UGT:
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001030 return ConstantRange(CR.getUnsignedMin() + 1, APInt::getNullValue(W));
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001031 case ICmpInst::ICMP_SGT:
1032 return ConstantRange(CR.getSignedMin() + 1,
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001033 APInt::getSignedMinValue(W));
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001034 case ICmpInst::ICMP_UGE: {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001035 APInt UMin(CR.getUnsignedMin());
Zhou Sheng31787362007-04-26 16:42:07 +00001036 if (UMin.isMinValue())
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001037 return ConstantRange(W);
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001038 return ConstantRange(UMin, APInt::getNullValue(W));
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001039 }
1040 case ICmpInst::ICMP_SGE: {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001041 APInt SMin(CR.getSignedMin());
Zhou Sheng31787362007-04-26 16:42:07 +00001042 if (SMin.isMinSignedValue())
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001043 return ConstantRange(W);
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001044 return ConstantRange(SMin, APInt::getSignedMinValue(W));
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001045 }
1046 }
1047 }
1048
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001049#ifndef NDEBUG
Nick Lewyckye635cc42007-07-10 03:28:21 +00001050 bool isCanonical(Value *V, DomTreeDFS::Node *Subtree) {
1051 return V == VN.canonicalize(V, Subtree);
1052 }
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001053#endif
1054
1055 public:
1056
Nick Lewyckye635cc42007-07-10 03:28:21 +00001057 ValueRanges(ValueNumbering &VN, TargetData *TD) : VN(VN), TD(TD) {}
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001058
Nick Lewyckye635cc42007-07-10 03:28:21 +00001059#ifndef NDEBUG
1060 virtual ~ValueRanges() {}
1061
1062 virtual void dump() const {
1063 dump(*cerr.stream());
1064 }
1065
1066 void dump(std::ostream &os) const {
1067 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1068 os << (i+1) << " = ";
1069 Ranges[i].dump(os);
1070 os << "\n";
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001071 }
Nick Lewyckye635cc42007-07-10 03:28:21 +00001072 }
1073#endif
1074
1075 /// range - looks up the ConstantRange associated with a value number.
1076 ConstantRange range(unsigned n, DomTreeDFS::Node *Subtree) {
1077 assert(VN.value(n)); // performs range checks
1078
1079 if (n <= Ranges.size()) {
1080 ScopedRange::iterator I = Ranges[n-1].find(Subtree);
1081 if (I != Ranges[n-1].end()) return I->second;
1082 }
1083
1084 Value *V = VN.value(n);
1085 ConstantRange CR = range(V);
1086 return CR;
1087 }
1088
1089 /// range - determine a range from a Value without performing any lookups.
1090 ConstantRange range(Value *V) const {
1091 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
1092 return ConstantRange(C->getValue());
1093 else if (isa<ConstantPointerNull>(V))
1094 return ConstantRange(APInt::getNullValue(typeToWidth(V->getType())));
1095 else
1096 return typeToWidth(V->getType());
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001097 }
1098
Nick Lewycky12d44ab2007-04-07 03:16:12 +00001099 // typeToWidth - returns the number of bits necessary to store a value of
1100 // this type, or zero if unknown.
1101 uint32_t typeToWidth(const Type *Ty) const {
1102 if (TD)
1103 return TD->getTypeSizeInBits(Ty);
1104
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001105 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
1106 return ITy->getBitWidth();
1107
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001108 return 0;
1109 }
1110
Nick Lewyckye635cc42007-07-10 03:28:21 +00001111 static bool isRelatedBy(const ConstantRange &CR1, const ConstantRange &CR2,
1112 LatticeVal LV) {
Nick Lewycky4f73de22007-03-16 02:37:39 +00001113 switch (LV) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001114 default: assert(!"Impossible lattice value!");
1115 case NE:
Nick Lewycky39519f52007-07-14 04:28:04 +00001116 return CR1.maximalIntersectWith(CR2).isEmptySet();
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001117 case ULT:
1118 return CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
1119 case ULE:
1120 return CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
1121 case UGT:
1122 return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
1123 case UGE:
1124 return CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
1125 case SLT:
1126 return CR1.getSignedMax().slt(CR2.getSignedMin());
1127 case SLE:
1128 return CR1.getSignedMax().sle(CR2.getSignedMin());
1129 case SGT:
1130 return CR1.getSignedMin().sgt(CR2.getSignedMax());
1131 case SGE:
1132 return CR1.getSignedMin().sge(CR2.getSignedMax());
1133 case LT:
1134 return CR1.getUnsignedMax().ult(CR2.getUnsignedMin()) &&
1135 CR1.getSignedMax().slt(CR2.getUnsignedMin());
1136 case LE:
1137 return CR1.getUnsignedMax().ule(CR2.getUnsignedMin()) &&
1138 CR1.getSignedMax().sle(CR2.getUnsignedMin());
1139 case GT:
1140 return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax()) &&
1141 CR1.getSignedMin().sgt(CR2.getSignedMax());
1142 case GE:
1143 return CR1.getUnsignedMin().uge(CR2.getUnsignedMax()) &&
1144 CR1.getSignedMin().sge(CR2.getSignedMax());
1145 case SLTUGT:
1146 return CR1.getSignedMax().slt(CR2.getSignedMin()) &&
1147 CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
1148 case SLEUGE:
1149 return CR1.getSignedMax().sle(CR2.getSignedMin()) &&
1150 CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
1151 case SGTULT:
1152 return CR1.getSignedMin().sgt(CR2.getSignedMax()) &&
1153 CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
1154 case SGEULE:
1155 return CR1.getSignedMin().sge(CR2.getSignedMax()) &&
1156 CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
1157 }
1158 }
1159
Nick Lewyckye635cc42007-07-10 03:28:21 +00001160 bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
1161 LatticeVal LV) {
1162 ConstantRange CR1 = range(n1, Subtree);
1163 ConstantRange CR2 = range(n2, Subtree);
1164
1165 // True iff all values in CR1 are LV to all values in CR2.
1166 return isRelatedBy(CR1, CR2, LV);
1167 }
1168
Nick Lewycky3bb6de82007-04-07 03:36:51 +00001169 void addToWorklist(Value *V, Constant *C, ICmpInst::Predicate Pred,
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001170 VRPSolver *VRP);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001171 void markBlock(VRPSolver *VRP);
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001172
Nick Lewyckye635cc42007-07-10 03:28:21 +00001173 void mergeInto(Value **I, unsigned n, unsigned New,
Nick Lewycky26e25d32007-06-24 04:36:20 +00001174 DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
Nick Lewyckye635cc42007-07-10 03:28:21 +00001175 ConstantRange CR_New = range(New, Subtree);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001176 ConstantRange Merged = CR_New;
1177
1178 for (; n != 0; ++I, --n) {
Nick Lewyckye635cc42007-07-10 03:28:21 +00001179 unsigned i = VN.valueNumber(*I, Subtree);
1180 ConstantRange CR_Kill = i ? range(i, Subtree) : range(*I);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001181 if (CR_Kill.isFullSet()) continue;
Nick Lewycky39519f52007-07-14 04:28:04 +00001182 Merged = Merged.maximalIntersectWith(CR_Kill);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001183 }
1184
1185 if (Merged.isFullSet() || Merged == CR_New) return;
1186
Nick Lewycky3bb6de82007-04-07 03:36:51 +00001187 applyRange(New, Merged, Subtree, VRP);
1188 }
1189
Nick Lewyckye635cc42007-07-10 03:28:21 +00001190 void applyRange(unsigned n, const ConstantRange &CR,
Nick Lewycky26e25d32007-06-24 04:36:20 +00001191 DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
Nick Lewycky39519f52007-07-14 04:28:04 +00001192 ConstantRange Merged = CR.maximalIntersectWith(range(n, Subtree));
Nick Lewyckye635cc42007-07-10 03:28:21 +00001193 if (Merged.isEmptySet()) {
1194 markBlock(VRP);
1195 return;
1196 }
Nick Lewycky3bb6de82007-04-07 03:36:51 +00001197
Nick Lewyckye635cc42007-07-10 03:28:21 +00001198 if (const APInt *I = Merged.getSingleElement()) {
1199 Value *V = VN.value(n); // XXX: redesign worklist.
Nick Lewycky3bb6de82007-04-07 03:36:51 +00001200 const Type *Ty = V->getType();
1201 if (Ty->isInteger()) {
1202 addToWorklist(V, ConstantInt::get(*I), ICmpInst::ICMP_EQ, VRP);
1203 return;
1204 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1205 assert(*I == 0 && "Pointer is null but not zero?");
1206 addToWorklist(V, ConstantPointerNull::get(PTy),
Nick Lewyckye635cc42007-07-10 03:28:21 +00001207 ICmpInst::ICMP_EQ, VRP);
Nick Lewycky3bb6de82007-04-07 03:36:51 +00001208 return;
1209 }
1210 }
1211
Nick Lewyckye635cc42007-07-10 03:28:21 +00001212 update(n, Merged, Subtree);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001213 }
1214
Nick Lewyckye635cc42007-07-10 03:28:21 +00001215 void addNotEquals(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
Nick Lewycky26e25d32007-06-24 04:36:20 +00001216 VRPSolver *VRP) {
Nick Lewyckye635cc42007-07-10 03:28:21 +00001217 ConstantRange CR1 = range(n1, Subtree);
1218 ConstantRange CR2 = range(n2, Subtree);
Nick Lewycky93f54102007-04-07 04:49:12 +00001219
Nick Lewyckye635cc42007-07-10 03:28:21 +00001220 uint32_t W = CR1.getBitWidth();
Nick Lewycky93f54102007-04-07 04:49:12 +00001221
1222 if (const APInt *I = CR1.getSingleElement()) {
1223 if (CR2.isFullSet()) {
1224 ConstantRange NewCR2(CR1.getUpper(), CR1.getLower());
Nick Lewyckye635cc42007-07-10 03:28:21 +00001225 applyRange(n2, NewCR2, Subtree, VRP);
Nick Lewycky93f54102007-04-07 04:49:12 +00001226 } else if (*I == CR2.getLower()) {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001227 APInt NewLower(CR2.getLower() + 1),
1228 NewUpper(CR2.getUpper());
Nick Lewycky93f54102007-04-07 04:49:12 +00001229 if (NewLower == NewUpper)
1230 NewLower = NewUpper = APInt::getMinValue(W);
1231
1232 ConstantRange NewCR2(NewLower, NewUpper);
Nick Lewyckye635cc42007-07-10 03:28:21 +00001233 applyRange(n2, NewCR2, Subtree, VRP);
Nick Lewycky93f54102007-04-07 04:49:12 +00001234 } else if (*I == CR2.getUpper() - 1) {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001235 APInt NewLower(CR2.getLower()),
1236 NewUpper(CR2.getUpper() - 1);
Nick Lewycky93f54102007-04-07 04:49:12 +00001237 if (NewLower == NewUpper)
1238 NewLower = NewUpper = APInt::getMinValue(W);
1239
1240 ConstantRange NewCR2(NewLower, NewUpper);
Nick Lewyckye635cc42007-07-10 03:28:21 +00001241 applyRange(n2, NewCR2, Subtree, VRP);
Nick Lewycky93f54102007-04-07 04:49:12 +00001242 }
1243 }
1244
1245 if (const APInt *I = CR2.getSingleElement()) {
1246 if (CR1.isFullSet()) {
1247 ConstantRange NewCR1(CR2.getUpper(), CR2.getLower());
Nick Lewyckye635cc42007-07-10 03:28:21 +00001248 applyRange(n1, NewCR1, Subtree, VRP);
Nick Lewycky93f54102007-04-07 04:49:12 +00001249 } else if (*I == CR1.getLower()) {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001250 APInt NewLower(CR1.getLower() + 1),
1251 NewUpper(CR1.getUpper());
Nick Lewycky93f54102007-04-07 04:49:12 +00001252 if (NewLower == NewUpper)
1253 NewLower = NewUpper = APInt::getMinValue(W);
1254
1255 ConstantRange NewCR1(NewLower, NewUpper);
Nick Lewyckye635cc42007-07-10 03:28:21 +00001256 applyRange(n1, NewCR1, Subtree, VRP);
Nick Lewycky93f54102007-04-07 04:49:12 +00001257 } else if (*I == CR1.getUpper() - 1) {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001258 APInt NewLower(CR1.getLower()),
1259 NewUpper(CR1.getUpper() - 1);
Nick Lewycky93f54102007-04-07 04:49:12 +00001260 if (NewLower == NewUpper)
1261 NewLower = NewUpper = APInt::getMinValue(W);
1262
1263 ConstantRange NewCR1(NewLower, NewUpper);
Nick Lewyckye635cc42007-07-10 03:28:21 +00001264 applyRange(n1, NewCR1, Subtree, VRP);
Nick Lewycky93f54102007-04-07 04:49:12 +00001265 }
1266 }
1267 }
1268
Nick Lewyckye635cc42007-07-10 03:28:21 +00001269 void addInequality(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
Nick Lewycky26e25d32007-06-24 04:36:20 +00001270 LatticeVal LV, VRPSolver *VRP) {
Nick Lewyckye635cc42007-07-10 03:28:21 +00001271 assert(!isRelatedBy(n1, n2, Subtree, LV) && "Asked to do useless work.");
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001272
Nick Lewycky93f54102007-04-07 04:49:12 +00001273 if (LV == NE) {
Nick Lewyckye635cc42007-07-10 03:28:21 +00001274 addNotEquals(n1, n2, Subtree, VRP);
Nick Lewycky93f54102007-04-07 04:49:12 +00001275 return;
1276 }
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001277
Nick Lewyckye635cc42007-07-10 03:28:21 +00001278 ConstantRange CR1 = range(n1, Subtree);
1279 ConstantRange CR2 = range(n2, Subtree);
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001280
1281 if (!CR1.isSingleElement()) {
Nick Lewycky39519f52007-07-14 04:28:04 +00001282 ConstantRange NewCR1 = CR1.maximalIntersectWith(create(LV, CR2));
Nick Lewycky3bb6de82007-04-07 03:36:51 +00001283 if (NewCR1 != CR1)
Nick Lewyckye635cc42007-07-10 03:28:21 +00001284 applyRange(n1, NewCR1, Subtree, VRP);
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001285 }
1286
1287 if (!CR2.isSingleElement()) {
Nick Lewycky39519f52007-07-14 04:28:04 +00001288 ConstantRange NewCR2 = CR2.maximalIntersectWith(
1289 create(reversePredicate(LV), CR1));
Nick Lewycky3bb6de82007-04-07 03:36:51 +00001290 if (NewCR2 != CR2)
Nick Lewyckye635cc42007-07-10 03:28:21 +00001291 applyRange(n2, NewCR2, Subtree, VRP);
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001292 }
1293 }
1294 };
1295
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001296 /// UnreachableBlocks keeps tracks of blocks that are for one reason or
1297 /// another discovered to be unreachable. This is used to cull the graph when
1298 /// analyzing instructions, and to mark blocks with the "unreachable"
1299 /// terminator instruction after the function has executed.
1300 class VISIBILITY_HIDDEN UnreachableBlocks {
1301 private:
1302 std::vector<BasicBlock *> DeadBlocks;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001303
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001304 public:
1305 /// mark - mark a block as dead
1306 void mark(BasicBlock *BB) {
1307 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
1308 std::vector<BasicBlock *>::iterator I =
1309 std::lower_bound(DeadBlocks.begin(), E, BB);
1310
1311 if (I == E || *I != BB) DeadBlocks.insert(I, BB);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001312 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001313
1314 /// isDead - returns whether a block is known to be dead already
1315 bool isDead(BasicBlock *BB) {
1316 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
1317 std::vector<BasicBlock *>::iterator I =
1318 std::lower_bound(DeadBlocks.begin(), E, BB);
1319
1320 return I != E && *I == BB;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001321 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001322
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001323 /// kill - replace the dead blocks' terminator with an UnreachableInst.
1324 bool kill() {
1325 bool modified = false;
1326 for (std::vector<BasicBlock *>::iterator I = DeadBlocks.begin(),
1327 E = DeadBlocks.end(); I != E; ++I) {
1328 BasicBlock *BB = *I;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001329
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001330 DOUT << "unreachable block: " << BB->getName() << "\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001331
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001332 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
1333 SI != SE; ++SI) {
1334 BasicBlock *Succ = *SI;
1335 Succ->removePredecessor(BB);
Nick Lewycky9d17c822006-10-25 23:48:24 +00001336 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001337
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001338 TerminatorInst *TI = BB->getTerminator();
1339 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1340 TI->eraseFromParent();
1341 new UnreachableInst(BB);
1342 ++NumBlocks;
1343 modified = true;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001344 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001345 DeadBlocks.clear();
1346 return modified;
Nick Lewycky9d17c822006-10-25 23:48:24 +00001347 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001348 };
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001349
1350 /// VRPSolver keeps track of how changes to one variable affect other
1351 /// variables, and forwards changes along to the InequalityGraph. It
1352 /// also maintains the correct choice for "canonical" in the IG.
1353 /// @brief VRPSolver calculates inferences from a new relationship.
1354 class VISIBILITY_HIDDEN VRPSolver {
1355 private:
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001356 friend class ValueRanges;
1357
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001358 struct Operation {
1359 Value *LHS, *RHS;
1360 ICmpInst::Predicate Op;
1361
Nick Lewycky26e25d32007-06-24 04:36:20 +00001362 BasicBlock *ContextBB; // XXX use a DomTreeDFS::Node instead
Nick Lewycky42944462007-01-13 02:05:28 +00001363 Instruction *ContextInst;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001364 };
1365 std::deque<Operation> WorkList;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001366
Nick Lewycky73dd6922007-07-05 03:15:00 +00001367 ValueNumbering &VN;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001368 InequalityGraph &IG;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001369 UnreachableBlocks &UB;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001370 ValueRanges &VR;
Nick Lewycky26e25d32007-06-24 04:36:20 +00001371 DomTreeDFS *DTDFS;
1372 DomTreeDFS::Node *Top;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001373 BasicBlock *TopBB;
1374 Instruction *TopInst;
1375 bool &modified;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001376
1377 typedef InequalityGraph::Node Node;
1378
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001379 // below - true if the Instruction is dominated by the current context
1380 // block or instruction
1381 bool below(Instruction *I) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00001382 BasicBlock *BB = I->getParent();
1383 if (TopInst && TopInst->getParent() == BB) {
1384 if (isa<TerminatorInst>(TopInst)) return false;
1385 if (isa<TerminatorInst>(I)) return true;
1386 if ( isa<PHINode>(TopInst) && !isa<PHINode>(I)) return true;
1387 if (!isa<PHINode>(TopInst) && isa<PHINode>(I)) return false;
1388
1389 for (BasicBlock::const_iterator Iter = BB->begin(), E = BB->end();
1390 Iter != E; ++Iter) {
1391 if (&*Iter == TopInst) return true;
1392 else if (&*Iter == I) return false;
1393 }
1394 assert(!"Instructions not found in parent BasicBlock?");
1395 } else {
Nick Lewycky0f986fd2007-06-24 04:40:16 +00001396 DomTreeDFS::Node *Node = DTDFS->getNodeForBlock(BB);
Nick Lewycky26e25d32007-06-24 04:36:20 +00001397 if (!Node) return false;
1398 return Top->dominates(Node);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001399 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001400 }
1401
Nick Lewycky26e25d32007-06-24 04:36:20 +00001402 // aboveOrBelow - true if the Instruction either dominates or is dominated
1403 // by the current context block or instruction
1404 bool aboveOrBelow(Instruction *I) {
1405 BasicBlock *BB = I->getParent();
1406 DomTreeDFS::Node *Node = DTDFS->getNodeForBlock(BB);
1407 if (!Node) return false;
1408
1409 return Top == Node || Top->dominates(Node) || Node->dominates(Top);
1410 }
1411
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001412 bool makeEqual(Value *V1, Value *V2) {
1413 DOUT << "makeEqual(" << *V1 << ", " << *V2 << ")\n";
Nick Lewycky26e25d32007-06-24 04:36:20 +00001414 DOUT << "context is ";
1415 if (TopInst) DOUT << "I: " << *TopInst << "\n";
1416 else DOUT << "BB: " << TopBB->getName()
1417 << "(" << Top->getDFSNumIn() << ")\n";
Nick Lewycky9d17c822006-10-25 23:48:24 +00001418
Nick Lewycky12d44ab2007-04-07 03:16:12 +00001419 assert(V1->getType() == V2->getType() &&
1420 "Can't make two values with different types equal.");
1421
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001422 if (V1 == V2) return true;
Nick Lewycky9d17c822006-10-25 23:48:24 +00001423
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001424 if (isa<Constant>(V1) && isa<Constant>(V2))
1425 return false;
1426
Nick Lewycky73dd6922007-07-05 03:15:00 +00001427 unsigned n1 = VN.valueNumber(V1, Top), n2 = VN.valueNumber(V2, Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001428
1429 if (n1 && n2) {
1430 if (n1 == n2) return true;
1431 if (IG.isRelatedBy(n1, n2, Top, NE)) return false;
1432 }
1433
Nick Lewycky73dd6922007-07-05 03:15:00 +00001434 if (n1) assert(V1 == VN.value(n1) && "Value isn't canonical.");
1435 if (n2) assert(V2 == VN.value(n2) && "Value isn't canonical.");
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001436
Nick Lewycky73dd6922007-07-05 03:15:00 +00001437 assert(!VN.compare(V2, V1) && "Please order parameters to makeEqual.");
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001438
1439 assert(!isa<Constant>(V2) && "Tried to remove a constant.");
1440
1441 SetVector<unsigned> Remove;
1442 if (n2) Remove.insert(n2);
1443
1444 if (n1 && n2) {
1445 // Suppose we're being told that %x == %y, and %x <= %z and %y >= %z.
1446 // We can't just merge %x and %y because the relationship with %z would
1447 // be EQ and that's invalid. What we're doing is looking for any nodes
1448 // %z such that %x <= %z and %y >= %z, and vice versa.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001449
Nick Lewyckye635cc42007-07-10 03:28:21 +00001450 Node::iterator end = IG.node(n2)->end();
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001451
1452 // Find the intersection between N1 and N2 which is dominated by
1453 // Top. If we find %x where N1 <= %x <= N2 (or >=) then add %x to
1454 // Remove.
Nick Lewyckye635cc42007-07-10 03:28:21 +00001455 for (Node::iterator I = IG.node(n1)->begin(), E = IG.node(n1)->end();
1456 I != E; ++I) {
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001457 if (!(I->LV & EQ_BIT) || !Top->DominatedBy(I->Subtree)) continue;
1458
1459 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
1460 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
Nick Lewyckye635cc42007-07-10 03:28:21 +00001461 Node::iterator NI = IG.node(n2)->find(I->To, Top);
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001462 if (NI != end) {
1463 LatticeVal NILV = reversePredicate(NI->LV);
1464 unsigned NILV_s = NILV & (SLT_BIT|SGT_BIT);
1465 unsigned NILV_u = NILV & (ULT_BIT|UGT_BIT);
1466
1467 if ((ILV_s != (SLT_BIT|SGT_BIT) && ILV_s == NILV_s) ||
1468 (ILV_u != (ULT_BIT|UGT_BIT) && ILV_u == NILV_u))
1469 Remove.insert(I->To);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001470 }
1471 }
1472
1473 // See if one of the nodes about to be removed is actually a better
1474 // canonical choice than n1.
1475 unsigned orig_n1 = n1;
Reid Spencera8a15472007-01-17 02:23:37 +00001476 SetVector<unsigned>::iterator DontRemove = Remove.end();
1477 for (SetVector<unsigned>::iterator I = Remove.begin()+1 /* skip n2 */,
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001478 E = Remove.end(); I != E; ++I) {
1479 unsigned n = *I;
Nick Lewycky73dd6922007-07-05 03:15:00 +00001480 Value *V = VN.value(n);
1481 if (VN.compare(V, V1)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001482 V1 = V;
1483 n1 = n;
1484 DontRemove = I;
1485 }
1486 }
1487 if (DontRemove != Remove.end()) {
1488 unsigned n = *DontRemove;
1489 Remove.remove(n);
1490 Remove.insert(orig_n1);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001491 }
1492 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001493
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001494 // We'd like to allow makeEqual on two values to perform a simple
1495 // substitution without every creating nodes in the IG whenever possible.
1496 //
1497 // The first iteration through this loop operates on V2 before going
1498 // through the Remove list and operating on those too. If all of the
1499 // iterations performed simple replacements then we exit early.
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001500 bool mergeIGNode = false;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001501 unsigned i = 0;
1502 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00001503 if (i) R = VN.value(Remove[i]); // skip n2.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001504
1505 // Try to replace the whole instruction. If we can, we're done.
1506 Instruction *I2 = dyn_cast<Instruction>(R);
1507 if (I2 && below(I2)) {
1508 std::vector<Instruction *> ToNotify;
1509 for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
1510 UI != UE;) {
1511 Use &TheUse = UI.getUse();
1512 ++UI;
1513 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser()))
1514 ToNotify.push_back(I);
1515 }
1516
1517 DOUT << "Simply removing " << *I2
1518 << ", replacing with " << *V1 << "\n";
1519 I2->replaceAllUsesWith(V1);
1520 // leave it dead; it'll get erased later.
1521 ++NumInstruction;
1522 modified = true;
1523
1524 for (std::vector<Instruction *>::iterator II = ToNotify.begin(),
1525 IE = ToNotify.end(); II != IE; ++II) {
1526 opsToDef(*II);
1527 }
1528
1529 continue;
1530 }
1531
1532 // Otherwise, replace all dominated uses.
1533 for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
1534 UI != UE;) {
1535 Use &TheUse = UI.getUse();
1536 ++UI;
1537 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
1538 if (below(I)) {
1539 TheUse.set(V1);
1540 modified = true;
1541 ++NumVarsReplaced;
1542 opsToDef(I);
1543 }
1544 }
1545 }
1546
1547 // If that killed the instruction, stop here.
1548 if (I2 && isInstructionTriviallyDead(I2)) {
1549 DOUT << "Killed all uses of " << *I2
1550 << ", replacing with " << *V1 << "\n";
1551 continue;
1552 }
1553
1554 // If we make it to here, then we will need to create a node for N1.
1555 // Otherwise, we can skip out early!
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001556 mergeIGNode = true;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001557 }
1558
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001559 if (!isa<Constant>(V1)) {
1560 if (Remove.empty()) {
Nick Lewyckye635cc42007-07-10 03:28:21 +00001561 VR.mergeInto(&V2, 1, VN.getOrInsertVN(V1, Top), Top, this);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001562 } else {
1563 std::vector<Value*> RemoveVals;
1564 RemoveVals.reserve(Remove.size());
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001565
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001566 for (SetVector<unsigned>::iterator I = Remove.begin(),
1567 E = Remove.end(); I != E; ++I) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00001568 Value *V = VN.value(*I);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001569 if (!V->use_empty())
1570 RemoveVals.push_back(V);
1571 }
Nick Lewyckye635cc42007-07-10 03:28:21 +00001572 VR.mergeInto(&RemoveVals[0], RemoveVals.size(),
1573 VN.getOrInsertVN(V1, Top), Top, this);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001574 }
1575 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001576
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001577 if (mergeIGNode) {
1578 // Create N1.
Nick Lewyckye635cc42007-07-10 03:28:21 +00001579 if (!n1) n1 = VN.getOrInsertVN(V1, Top);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001580
1581 // Migrate relationships from removed nodes to N1.
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001582 for (SetVector<unsigned>::iterator I = Remove.begin(), E = Remove.end();
1583 I != E; ++I) {
1584 unsigned n = *I;
Nick Lewyckye635cc42007-07-10 03:28:21 +00001585 for (Node::iterator NI = IG.node(n)->begin(), NE = IG.node(n)->end();
1586 NI != NE; ++NI) {
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001587 if (NI->Subtree->DominatedBy(Top)) {
1588 if (NI->To == n1) {
1589 assert((NI->LV & EQ_BIT) && "Node inequal to itself.");
1590 continue;
1591 }
1592 if (Remove.count(NI->To))
1593 continue;
1594
1595 IG.node(NI->To)->update(n1, reversePredicate(NI->LV), Top);
Nick Lewyckye635cc42007-07-10 03:28:21 +00001596 IG.node(n1)->update(NI->To, NI->LV, Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001597 }
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001598 }
1599 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001600
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001601 // Point V2 (and all items in Remove) to N1.
1602 if (!n2)
Nick Lewycky73dd6922007-07-05 03:15:00 +00001603 VN.addEquality(n1, V2, Top);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001604 else {
1605 for (SetVector<unsigned>::iterator I = Remove.begin(),
1606 E = Remove.end(); I != E; ++I) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00001607 VN.addEquality(n1, VN.value(*I), Top);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001608 }
1609 }
1610
1611 // If !Remove.empty() then V2 = Remove[0]->getValue().
1612 // Even when Remove is empty, we still want to process V2.
1613 i = 0;
1614 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00001615 if (i) R = VN.value(Remove[i]); // skip n2.
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001616
1617 if (Instruction *I2 = dyn_cast<Instruction>(R)) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00001618 if (aboveOrBelow(I2))
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001619 defToOps(I2);
1620 }
1621 for (Value::use_iterator UI = V2->use_begin(), UE = V2->use_end();
1622 UI != UE;) {
1623 Use &TheUse = UI.getUse();
1624 ++UI;
1625 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00001626 if (aboveOrBelow(I))
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001627 opsToDef(I);
1628 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001629 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001630 }
1631 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001632
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001633 // re-opsToDef all dominated users of V1.
1634 if (Instruction *I = dyn_cast<Instruction>(V1)) {
1635 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001636 UI != UE;) {
1637 Use &TheUse = UI.getUse();
1638 ++UI;
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001639 Value *V = TheUse.getUser();
1640 if (!V->use_empty()) {
1641 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00001642 if (aboveOrBelow(Inst))
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001643 opsToDef(Inst);
1644 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001645 }
1646 }
1647 }
1648
1649 return true;
1650 }
1651
1652 /// cmpInstToLattice - converts an CmpInst::Predicate to lattice value
1653 /// Requires that the lattice value be valid; does not accept ICMP_EQ.
1654 static LatticeVal cmpInstToLattice(ICmpInst::Predicate Pred) {
1655 switch (Pred) {
1656 case ICmpInst::ICMP_EQ:
1657 assert(!"No matching lattice value.");
1658 return static_cast<LatticeVal>(EQ_BIT);
1659 default:
1660 assert(!"Invalid 'icmp' predicate.");
1661 case ICmpInst::ICMP_NE:
1662 return NE;
1663 case ICmpInst::ICMP_UGT:
Nick Lewycky56639802007-01-29 02:56:54 +00001664 return UGT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001665 case ICmpInst::ICMP_UGE:
Nick Lewycky56639802007-01-29 02:56:54 +00001666 return UGE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001667 case ICmpInst::ICMP_ULT:
Nick Lewycky56639802007-01-29 02:56:54 +00001668 return ULT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001669 case ICmpInst::ICMP_ULE:
Nick Lewycky56639802007-01-29 02:56:54 +00001670 return ULE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001671 case ICmpInst::ICMP_SGT:
Nick Lewycky56639802007-01-29 02:56:54 +00001672 return SGT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001673 case ICmpInst::ICMP_SGE:
Nick Lewycky56639802007-01-29 02:56:54 +00001674 return SGE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001675 case ICmpInst::ICMP_SLT:
Nick Lewycky56639802007-01-29 02:56:54 +00001676 return SLT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001677 case ICmpInst::ICMP_SLE:
Nick Lewycky56639802007-01-29 02:56:54 +00001678 return SLE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001679 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001680 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001681
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001682 public:
Nick Lewycky73dd6922007-07-05 03:15:00 +00001683 VRPSolver(ValueNumbering &VN, InequalityGraph &IG, UnreachableBlocks &UB,
1684 ValueRanges &VR, DomTreeDFS *DTDFS, bool &modified,
1685 BasicBlock *TopBB)
1686 : VN(VN),
1687 IG(IG),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001688 UB(UB),
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001689 VR(VR),
Nick Lewycky26e25d32007-06-24 04:36:20 +00001690 DTDFS(DTDFS),
1691 Top(DTDFS->getNodeForBlock(TopBB)),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001692 TopBB(TopBB),
1693 TopInst(NULL),
Nick Lewycky26e25d32007-06-24 04:36:20 +00001694 modified(modified)
1695 {
1696 assert(Top && "VRPSolver created for unreachable basic block.");
1697 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001698
Nick Lewycky73dd6922007-07-05 03:15:00 +00001699 VRPSolver(ValueNumbering &VN, InequalityGraph &IG, UnreachableBlocks &UB,
1700 ValueRanges &VR, DomTreeDFS *DTDFS, bool &modified,
1701 Instruction *TopInst)
1702 : VN(VN),
1703 IG(IG),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001704 UB(UB),
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001705 VR(VR),
Nick Lewycky26e25d32007-06-24 04:36:20 +00001706 DTDFS(DTDFS),
1707 Top(DTDFS->getNodeForBlock(TopInst->getParent())),
1708 TopBB(TopInst->getParent()),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001709 TopInst(TopInst),
1710 modified(modified)
1711 {
Nick Lewycky26e25d32007-06-24 04:36:20 +00001712 assert(Top && "VRPSolver created for unreachable basic block.");
1713 assert(Top->getBlock() == TopInst->getParent() && "Context mismatch.");
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001714 }
1715
1716 bool isRelatedBy(Value *V1, Value *V2, ICmpInst::Predicate Pred) const {
1717 if (Constant *C1 = dyn_cast<Constant>(V1))
1718 if (Constant *C2 = dyn_cast<Constant>(V2))
1719 return ConstantExpr::getCompare(Pred, C1, C2) ==
Zhou Sheng75b871f2007-01-11 12:24:14 +00001720 ConstantInt::getTrue();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001721
Nick Lewyckye635cc42007-07-10 03:28:21 +00001722 unsigned n1 = VN.valueNumber(V1, Top);
1723 unsigned n2 = VN.valueNumber(V2, Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001724
Nick Lewyckye635cc42007-07-10 03:28:21 +00001725 if (n1 && n2) {
1726 if (n1 == n2) return Pred == ICmpInst::ICMP_EQ ||
1727 Pred == ICmpInst::ICMP_ULE ||
1728 Pred == ICmpInst::ICMP_UGE ||
1729 Pred == ICmpInst::ICMP_SLE ||
1730 Pred == ICmpInst::ICMP_SGE;
1731 if (Pred == ICmpInst::ICMP_EQ) return false;
1732 if (IG.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
1733 if (VR.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
1734 }
1735
1736 if ((n1 && !n2 && isa<Constant>(V2)) ||
1737 (n2 && !n1 && isa<Constant>(V1))) {
1738 ConstantRange CR1 = n1 ? VR.range(n1, Top) : VR.range(V1);
1739 ConstantRange CR2 = n2 ? VR.range(n2, Top) : VR.range(V2);
1740
1741 if (Pred == ICmpInst::ICMP_EQ)
1742 return CR1.isSingleElement() &&
1743 CR1.getSingleElement() == CR2.getSingleElement();
1744
1745 return VR.isRelatedBy(CR1, CR2, cmpInstToLattice(Pred));
1746 }
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001747 if (Pred == ICmpInst::ICMP_EQ) return V1 == V2;
Nick Lewyckye635cc42007-07-10 03:28:21 +00001748 return false;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001749 }
1750
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001751 /// add - adds a new property to the work queue
1752 void add(Value *V1, Value *V2, ICmpInst::Predicate Pred,
1753 Instruction *I = NULL) {
1754 DOUT << "adding " << *V1 << " " << Pred << " " << *V2;
1755 if (I) DOUT << " context: " << *I;
Nick Lewycky26e25d32007-06-24 04:36:20 +00001756 else DOUT << " default context (" << Top->getDFSNumIn() << ")";
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001757 DOUT << "\n";
1758
Nick Lewycky12d44ab2007-04-07 03:16:12 +00001759 assert(V1->getType() == V2->getType() &&
1760 "Can't relate two values with different types.");
1761
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001762 WorkList.push_back(Operation());
1763 Operation &O = WorkList.back();
Nick Lewycky42944462007-01-13 02:05:28 +00001764 O.LHS = V1, O.RHS = V2, O.Op = Pred, O.ContextInst = I;
1765 O.ContextBB = I ? I->getParent() : TopBB;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001766 }
1767
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001768 /// defToOps - Given an instruction definition that we've learned something
1769 /// new about, find any new relationships between its operands.
1770 void defToOps(Instruction *I) {
1771 Instruction *NewContext = below(I) ? I : TopInst;
Nick Lewycky73dd6922007-07-05 03:15:00 +00001772 Value *Canonical = VN.canonicalize(I, Top);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001773
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001774 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1775 const Type *Ty = BO->getType();
1776 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001777
Nick Lewycky73dd6922007-07-05 03:15:00 +00001778 Value *Op0 = VN.canonicalize(BO->getOperand(0), Top);
1779 Value *Op1 = VN.canonicalize(BO->getOperand(1), Top);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001780
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001781 // TODO: "and i32 -1, %x" EQ %y then %x EQ %y.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001782
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001783 switch (BO->getOpcode()) {
1784 case Instruction::And: {
Nick Lewycky4f73de22007-03-16 02:37:39 +00001785 // "and i32 %a, %b" EQ -1 then %a EQ -1 and %b EQ -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00001786 ConstantInt *CI = ConstantInt::getAllOnesValue(Ty);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001787 if (Canonical == CI) {
1788 add(CI, Op0, ICmpInst::ICMP_EQ, NewContext);
1789 add(CI, Op1, ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001790 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001791 } break;
1792 case Instruction::Or: {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001793 // "or i32 %a, %b" EQ 0 then %a EQ 0 and %b EQ 0
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001794 Constant *Zero = Constant::getNullValue(Ty);
1795 if (Canonical == Zero) {
1796 add(Zero, Op0, ICmpInst::ICMP_EQ, NewContext);
1797 add(Zero, Op1, ICmpInst::ICMP_EQ, NewContext);
1798 }
1799 } break;
1800 case Instruction::Xor: {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001801 // "xor i32 %c, %a" EQ %b then %a EQ %c ^ %b
1802 // "xor i32 %c, %a" EQ %c then %a EQ 0
1803 // "xor i32 %c, %a" NE %c then %a NE 0
1804 // Repeat the above, with order of operands reversed.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001805 Value *LHS = Op0;
1806 Value *RHS = Op1;
1807 if (!isa<Constant>(LHS)) std::swap(LHS, RHS);
1808
Nick Lewycky4a74a752007-01-12 00:02:12 +00001809 if (ConstantInt *CI = dyn_cast<ConstantInt>(Canonical)) {
1810 if (ConstantInt *Arg = dyn_cast<ConstantInt>(LHS)) {
Reid Spencerc34dedf2007-03-03 00:48:31 +00001811 add(RHS, ConstantInt::get(CI->getValue() ^ Arg->getValue()),
Nick Lewycky4a74a752007-01-12 00:02:12 +00001812 ICmpInst::ICMP_EQ, NewContext);
1813 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001814 }
1815 if (Canonical == LHS) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001816 if (isa<ConstantInt>(Canonical))
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001817 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_EQ,
1818 NewContext);
1819 } else if (isRelatedBy(LHS, Canonical, ICmpInst::ICMP_NE)) {
1820 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_NE,
1821 NewContext);
1822 }
1823 } break;
1824 default:
1825 break;
1826 }
1827 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001828 // "icmp ult i32 %a, %y" EQ true then %a u< y
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001829 // etc.
1830
Zhou Sheng75b871f2007-01-11 12:24:14 +00001831 if (Canonical == ConstantInt::getTrue()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001832 add(IC->getOperand(0), IC->getOperand(1), IC->getPredicate(),
1833 NewContext);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001834 } else if (Canonical == ConstantInt::getFalse()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001835 add(IC->getOperand(0), IC->getOperand(1),
1836 ICmpInst::getInversePredicate(IC->getPredicate()), NewContext);
1837 }
1838 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
1839 if (I->getType()->isFPOrFPVector()) return;
1840
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001841 // Given: "%a = select i1 %x, i32 %b, i32 %c"
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001842 // %a EQ %b and %b NE %c then %x EQ true
1843 // %a EQ %c and %b NE %c then %x EQ false
1844
1845 Value *True = SI->getTrueValue();
1846 Value *False = SI->getFalseValue();
1847 if (isRelatedBy(True, False, ICmpInst::ICMP_NE)) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00001848 if (Canonical == VN.canonicalize(True, Top) ||
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001849 isRelatedBy(Canonical, False, ICmpInst::ICMP_NE))
Zhou Sheng75b871f2007-01-11 12:24:14 +00001850 add(SI->getCondition(), ConstantInt::getTrue(),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001851 ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky73dd6922007-07-05 03:15:00 +00001852 else if (Canonical == VN.canonicalize(False, Top) ||
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001853 isRelatedBy(Canonical, True, ICmpInst::ICMP_NE))
Zhou Sheng75b871f2007-01-11 12:24:14 +00001854 add(SI->getCondition(), ConstantInt::getFalse(),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001855 ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001856 }
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001857 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1858 for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
1859 OE = GEPI->idx_end(); OI != OE; ++OI) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00001860 ConstantInt *Op = dyn_cast<ConstantInt>(VN.canonicalize(*OI, Top));
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001861 if (!Op || !Op->isZero()) return;
1862 }
1863 // TODO: The GEPI indices are all zero. Copy from definition to operand,
1864 // jumping the type plane as needed.
1865 if (isRelatedBy(GEPI, Constant::getNullValue(GEPI->getType()),
1866 ICmpInst::ICMP_NE)) {
1867 Value *Ptr = GEPI->getPointerOperand();
1868 add(Ptr, Constant::getNullValue(Ptr->getType()), ICmpInst::ICMP_NE,
1869 NewContext);
1870 }
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001871 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
1872 const Type *SrcTy = CI->getSrcTy();
1873
Nick Lewyckye635cc42007-07-10 03:28:21 +00001874 unsigned ci = VN.getOrInsertVN(CI, Top);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001875 uint32_t W = VR.typeToWidth(SrcTy);
1876 if (!W) return;
Nick Lewyckye635cc42007-07-10 03:28:21 +00001877 ConstantRange CR = VR.range(ci, Top);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001878
1879 if (CR.isFullSet()) return;
1880
1881 switch (CI->getOpcode()) {
1882 default: break;
1883 case Instruction::ZExt:
1884 case Instruction::SExt:
Nick Lewyckye635cc42007-07-10 03:28:21 +00001885 VR.applyRange(VN.getOrInsertVN(CI->getOperand(0), Top),
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001886 CR.truncate(W), Top, this);
1887 break;
1888 case Instruction::BitCast:
Nick Lewyckye635cc42007-07-10 03:28:21 +00001889 VR.applyRange(VN.getOrInsertVN(CI->getOperand(0), Top),
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001890 CR, Top, this);
1891 break;
1892 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001893 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001894 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001895
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001896 /// opsToDef - A new relationship was discovered involving one of this
1897 /// instruction's operands. Find any new relationship involving the
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001898 /// definition, or another operand.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001899 void opsToDef(Instruction *I) {
1900 Instruction *NewContext = below(I) ? I : TopInst;
1901
1902 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00001903 Value *Op0 = VN.canonicalize(BO->getOperand(0), Top);
1904 Value *Op1 = VN.canonicalize(BO->getOperand(1), Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001905
Zhou Sheng75b871f2007-01-11 12:24:14 +00001906 if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0))
1907 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001908 add(BO, ConstantExpr::get(BO->getOpcode(), CI0, CI1),
1909 ICmpInst::ICMP_EQ, NewContext);
1910 return;
1911 }
1912
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001913 // "%y = and i1 true, %x" then %x EQ %y
1914 // "%y = or i1 false, %x" then %x EQ %y
1915 // "%x = add i32 %y, 0" then %x EQ %y
1916 // "%x = mul i32 %y, 0" then %x EQ 0
1917
1918 Instruction::BinaryOps Opcode = BO->getOpcode();
Nick Lewyckydb204ec2007-03-18 22:58:46 +00001919 const Type *Ty = BO->getType();
1920 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
1921
1922 Constant *Zero = Constant::getNullValue(Ty);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001923 ConstantInt *AllOnes = ConstantInt::getAllOnesValue(Ty);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001924
1925 switch (Opcode) {
1926 default: break;
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001927 case Instruction::LShr:
1928 case Instruction::AShr:
1929 case Instruction::Shl:
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001930 case Instruction::Sub:
Nick Lewyckydb204ec2007-03-18 22:58:46 +00001931 if (Op1 == Zero) {
1932 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1933 return;
1934 }
1935 break;
1936 case Instruction::Or:
1937 if (Op0 == AllOnes || Op1 == AllOnes) {
1938 add(BO, AllOnes, ICmpInst::ICMP_EQ, NewContext);
1939 return;
1940 } // fall-through
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001941 case Instruction::Xor:
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001942 case Instruction::Add:
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001943 if (Op0 == Zero) {
1944 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1945 return;
1946 } else if (Op1 == Zero) {
1947 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1948 return;
1949 }
Nick Lewyckydb204ec2007-03-18 22:58:46 +00001950 break;
1951 case Instruction::And:
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001952 if (Op0 == AllOnes) {
1953 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1954 return;
1955 } else if (Op1 == AllOnes) {
1956 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1957 return;
1958 }
Nick Lewyckydb204ec2007-03-18 22:58:46 +00001959 // fall-through
1960 case Instruction::Mul:
1961 if (Op0 == Zero || Op1 == Zero) {
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001962 add(BO, Zero, ICmpInst::ICMP_EQ, NewContext);
1963 return;
1964 }
Nick Lewyckydb204ec2007-03-18 22:58:46 +00001965 break;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001966 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001967
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001968 // "%x = add i32 %y, %z" and %x EQ %y then %z EQ 0
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001969 // "%x = add i32 %y, %z" and %x EQ %z then %y EQ 0
1970 // "%x = shl i32 %y, %z" and %x EQ %y and %y NE 0 then %z EQ 0
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001971 // "%x = udiv i32 %y, %z" and %x EQ %y then %z EQ 1
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001972
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001973 Value *Known = Op0, *Unknown = Op1,
Nick Lewycky73dd6922007-07-05 03:15:00 +00001974 *TheBO = VN.canonicalize(BO, Top);
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001975 if (Known != TheBO) std::swap(Known, Unknown);
1976 if (Known == TheBO) {
Nick Lewycky4f73de22007-03-16 02:37:39 +00001977 switch (Opcode) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001978 default: break;
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001979 case Instruction::LShr:
1980 case Instruction::AShr:
1981 case Instruction::Shl:
1982 if (!isRelatedBy(Known, Zero, ICmpInst::ICMP_NE)) break;
1983 // otherwise, fall-through.
1984 case Instruction::Sub:
1985 if (Unknown == Op1) break;
1986 // otherwise, fall-through.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001987 case Instruction::Xor:
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001988 case Instruction::Add:
Nick Lewyckydb204ec2007-03-18 22:58:46 +00001989 add(Unknown, Zero, ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001990 break;
1991 case Instruction::UDiv:
1992 case Instruction::SDiv:
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001993 if (Unknown == Op1) break;
1994 if (isRelatedBy(Known, Zero, ICmpInst::ICMP_NE)) {
Nick Lewycky4a74a752007-01-12 00:02:12 +00001995 Constant *One = ConstantInt::get(Ty, 1);
1996 add(Unknown, One, ICmpInst::ICMP_EQ, NewContext);
1997 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001998 break;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001999 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002000 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002001
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002002 // TODO: "%a = add i32 %b, 1" and %b > %z then %a >= %z.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002003
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002004 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
Nick Lewycky4f73de22007-03-16 02:37:39 +00002005 // "%a = icmp ult i32 %b, %c" and %b u< %c then %a EQ true
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002006 // "%a = icmp ult i32 %b, %c" and %b u>= %c then %a EQ false
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002007 // etc.
2008
Nick Lewycky73dd6922007-07-05 03:15:00 +00002009 Value *Op0 = VN.canonicalize(IC->getOperand(0), Top);
2010 Value *Op1 = VN.canonicalize(IC->getOperand(1), Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002011
2012 ICmpInst::Predicate Pred = IC->getPredicate();
Nick Lewyckye635cc42007-07-10 03:28:21 +00002013 if (isRelatedBy(Op0, Op1, Pred))
Zhou Sheng75b871f2007-01-11 12:24:14 +00002014 add(IC, ConstantInt::getTrue(), ICmpInst::ICMP_EQ, NewContext);
Nick Lewyckye635cc42007-07-10 03:28:21 +00002015 else if (isRelatedBy(Op0, Op1, ICmpInst::getInversePredicate(Pred)))
Zhou Sheng75b871f2007-01-11 12:24:14 +00002016 add(IC, ConstantInt::getFalse(), ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002017
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002018 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00002019 if (I->getType()->isFPOrFPVector()) return;
2020
Nick Lewycky4f73de22007-03-16 02:37:39 +00002021 // Given: "%a = select i1 %x, i32 %b, i32 %c"
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002022 // %x EQ true then %a EQ %b
2023 // %x EQ false then %a EQ %c
2024 // %b EQ %c then %a EQ %b
2025
Nick Lewycky73dd6922007-07-05 03:15:00 +00002026 Value *Canonical = VN.canonicalize(SI->getCondition(), Top);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002027 if (Canonical == ConstantInt::getTrue()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002028 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002029 } else if (Canonical == ConstantInt::getFalse()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002030 add(SI, SI->getFalseValue(), ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky73dd6922007-07-05 03:15:00 +00002031 } else if (VN.canonicalize(SI->getTrueValue(), Top) ==
2032 VN.canonicalize(SI->getFalseValue(), Top)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002033 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
2034 }
Nick Lewyckyee32ee02007-01-12 01:23:53 +00002035 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00002036 const Type *DestTy = CI->getDestTy();
2037 if (DestTy->isFPOrFPVector()) return;
Nick Lewyckyee32ee02007-01-12 01:23:53 +00002038
Nick Lewycky73dd6922007-07-05 03:15:00 +00002039 Value *Op = VN.canonicalize(CI->getOperand(0), Top);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00002040 Instruction::CastOps Opcode = CI->getOpcode();
2041
2042 if (Constant *C = dyn_cast<Constant>(Op)) {
2043 add(CI, ConstantExpr::getCast(Opcode, C, DestTy),
Nick Lewyckyee32ee02007-01-12 01:23:53 +00002044 ICmpInst::ICMP_EQ, NewContext);
2045 }
2046
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00002047 uint32_t W = VR.typeToWidth(DestTy);
Nick Lewyckye635cc42007-07-10 03:28:21 +00002048 unsigned ci = VN.getOrInsertVN(CI, Top);
2049 ConstantRange CR = VR.range(VN.getOrInsertVN(Op, Top), Top);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00002050
2051 if (!CR.isFullSet()) {
2052 switch (Opcode) {
2053 default: break;
2054 case Instruction::ZExt:
Nick Lewyckye635cc42007-07-10 03:28:21 +00002055 VR.applyRange(ci, CR.zeroExtend(W), Top, this);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00002056 break;
2057 case Instruction::SExt:
Nick Lewyckye635cc42007-07-10 03:28:21 +00002058 VR.applyRange(ci, CR.signExtend(W), Top, this);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00002059 break;
2060 case Instruction::Trunc: {
2061 ConstantRange Result = CR.truncate(W);
2062 if (!Result.isFullSet())
Nick Lewyckye635cc42007-07-10 03:28:21 +00002063 VR.applyRange(ci, Result, Top, this);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00002064 } break;
2065 case Instruction::BitCast:
Nick Lewyckye635cc42007-07-10 03:28:21 +00002066 VR.applyRange(ci, CR, Top, this);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00002067 break;
2068 // TODO: other casts?
2069 }
2070 }
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00002071 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
2072 for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
2073 OE = GEPI->idx_end(); OI != OE; ++OI) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002074 ConstantInt *Op = dyn_cast<ConstantInt>(VN.canonicalize(*OI, Top));
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00002075 if (!Op || !Op->isZero()) return;
2076 }
2077 // TODO: The GEPI indices are all zero. Copy from operand to definition,
2078 // jumping the type plane as needed.
2079 Value *Ptr = GEPI->getPointerOperand();
2080 if (isRelatedBy(Ptr, Constant::getNullValue(Ptr->getType()),
2081 ICmpInst::ICMP_NE)) {
2082 add(GEPI, Constant::getNullValue(GEPI->getType()), ICmpInst::ICMP_NE,
2083 NewContext);
2084 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002085 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002086 }
2087
2088 /// solve - process the work queue
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002089 void solve() {
2090 //DOUT << "WorkList entry, size: " << WorkList.size() << "\n";
2091 while (!WorkList.empty()) {
2092 //DOUT << "WorkList size: " << WorkList.size() << "\n";
2093
2094 Operation &O = WorkList.front();
Nick Lewycky42944462007-01-13 02:05:28 +00002095 TopInst = O.ContextInst;
2096 TopBB = O.ContextBB;
Nick Lewycky26e25d32007-06-24 04:36:20 +00002097 Top = DTDFS->getNodeForBlock(TopBB); // XXX move this into Context
Nick Lewycky42944462007-01-13 02:05:28 +00002098
Nick Lewycky73dd6922007-07-05 03:15:00 +00002099 O.LHS = VN.canonicalize(O.LHS, Top);
2100 O.RHS = VN.canonicalize(O.RHS, Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002101
Nick Lewycky73dd6922007-07-05 03:15:00 +00002102 assert(O.LHS == VN.canonicalize(O.LHS, Top) && "Canonicalize isn't.");
2103 assert(O.RHS == VN.canonicalize(O.RHS, Top) && "Canonicalize isn't.");
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002104
2105 DOUT << "solving " << *O.LHS << " " << O.Op << " " << *O.RHS;
Nick Lewycky42944462007-01-13 02:05:28 +00002106 if (O.ContextInst) DOUT << " context inst: " << *O.ContextInst;
2107 else DOUT << " context block: " << O.ContextBB->getName();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002108 DOUT << "\n";
2109
Nick Lewyckye635cc42007-07-10 03:28:21 +00002110 DEBUG(VN.dump());
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002111 DEBUG(IG.dump());
Nick Lewyckye635cc42007-07-10 03:28:21 +00002112 DEBUG(VR.dump());
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002113
Nick Lewycky15245952007-02-04 23:43:05 +00002114 // If they're both Constant, skip it. Check for contradiction and mark
2115 // the BB as unreachable if so.
2116 if (Constant *CI_L = dyn_cast<Constant>(O.LHS)) {
2117 if (Constant *CI_R = dyn_cast<Constant>(O.RHS)) {
2118 if (ConstantExpr::getCompare(O.Op, CI_L, CI_R) ==
2119 ConstantInt::getFalse())
2120 UB.mark(TopBB);
2121
2122 WorkList.pop_front();
2123 continue;
2124 }
2125 }
2126
Nick Lewycky73dd6922007-07-05 03:15:00 +00002127 if (VN.compare(O.LHS, O.RHS)) {
Nick Lewycky15245952007-02-04 23:43:05 +00002128 std::swap(O.LHS, O.RHS);
2129 O.Op = ICmpInst::getSwappedPredicate(O.Op);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002130 }
2131
2132 if (O.Op == ICmpInst::ICMP_EQ) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002133 if (!makeEqual(O.RHS, O.LHS))
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002134 UB.mark(TopBB);
2135 } else {
2136 LatticeVal LV = cmpInstToLattice(O.Op);
2137
2138 if ((LV & EQ_BIT) &&
2139 isRelatedBy(O.LHS, O.RHS, ICmpInst::getSwappedPredicate(O.Op))) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002140 if (!makeEqual(O.RHS, O.LHS))
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002141 UB.mark(TopBB);
2142 } else {
2143 if (isRelatedBy(O.LHS, O.RHS, ICmpInst::getInversePredicate(O.Op))){
Nick Lewycky15245952007-02-04 23:43:05 +00002144 UB.mark(TopBB);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002145 WorkList.pop_front();
2146 continue;
2147 }
2148
Nick Lewyckye635cc42007-07-10 03:28:21 +00002149 unsigned n1 = VN.getOrInsertVN(O.LHS, Top);
2150 unsigned n2 = VN.getOrInsertVN(O.RHS, Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002151
Nick Lewyckye635cc42007-07-10 03:28:21 +00002152 if (n1 == n2) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002153 if (O.Op != ICmpInst::ICMP_UGE && O.Op != ICmpInst::ICMP_ULE &&
2154 O.Op != ICmpInst::ICMP_SGE && O.Op != ICmpInst::ICMP_SLE)
2155 UB.mark(TopBB);
2156
2157 WorkList.pop_front();
2158 continue;
2159 }
2160
Nick Lewyckye635cc42007-07-10 03:28:21 +00002161 if (VR.isRelatedBy(n1, n2, Top, LV) ||
2162 IG.isRelatedBy(n1, n2, Top, LV)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002163 WorkList.pop_front();
2164 continue;
2165 }
2166
Nick Lewyckye635cc42007-07-10 03:28:21 +00002167 VR.addInequality(n1, n2, Top, LV, this);
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002168 if ((!isa<ConstantInt>(O.RHS) && !isa<ConstantInt>(O.LHS)) ||
Nick Lewyckye635cc42007-07-10 03:28:21 +00002169 LV == NE)
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002170 IG.addInequality(n1, n2, Top, LV);
Nick Lewycky15245952007-02-04 23:43:05 +00002171
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002172 if (Instruction *I1 = dyn_cast<Instruction>(O.LHS)) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002173 if (aboveOrBelow(I1))
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002174 defToOps(I1);
2175 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002176 if (isa<Instruction>(O.LHS) || isa<Argument>(O.LHS)) {
2177 for (Value::use_iterator UI = O.LHS->use_begin(),
2178 UE = O.LHS->use_end(); UI != UE;) {
2179 Use &TheUse = UI.getUse();
2180 ++UI;
2181 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002182 if (aboveOrBelow(I))
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002183 opsToDef(I);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002184 }
2185 }
2186 }
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002187 if (Instruction *I2 = dyn_cast<Instruction>(O.RHS)) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002188 if (aboveOrBelow(I2))
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002189 defToOps(I2);
2190 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002191 if (isa<Instruction>(O.RHS) || isa<Argument>(O.RHS)) {
2192 for (Value::use_iterator UI = O.RHS->use_begin(),
2193 UE = O.RHS->use_end(); UI != UE;) {
2194 Use &TheUse = UI.getUse();
2195 ++UI;
2196 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002197 if (aboveOrBelow(I))
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002198 opsToDef(I);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002199 }
2200 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00002201 }
2202 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00002203 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002204 WorkList.pop_front();
Nick Lewycky9d17c822006-10-25 23:48:24 +00002205 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00002206 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002207 };
2208
Nick Lewycky3bb6de82007-04-07 03:36:51 +00002209 void ValueRanges::addToWorklist(Value *V, Constant *C,
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002210 ICmpInst::Predicate Pred, VRPSolver *VRP) {
Nick Lewycky3bb6de82007-04-07 03:36:51 +00002211 VRP->add(V, C, Pred, VRP->TopInst);
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002212 }
2213
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00002214 void ValueRanges::markBlock(VRPSolver *VRP) {
2215 VRP->UB.mark(VRP->TopBB);
2216 }
2217
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002218 /// PredicateSimplifier - This class is a simplifier that replaces
2219 /// one equivalent variable with another. It also tracks what
2220 /// can't be equal and will solve setcc instructions when possible.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002221 /// @brief Root of the predicate simplifier optimization.
2222 class VISIBILITY_HIDDEN PredicateSimplifier : public FunctionPass {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002223 DomTreeDFS *DTDFS;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002224 bool modified;
Nick Lewycky73dd6922007-07-05 03:15:00 +00002225 ValueNumbering *VN;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002226 InequalityGraph *IG;
2227 UnreachableBlocks UB;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002228 ValueRanges *VR;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002229
Nick Lewycky26e25d32007-06-24 04:36:20 +00002230 std::vector<DomTreeDFS::Node *> WorkList;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002231
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002232 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +00002233 static char ID; // Pass identification, replacement for typeid
Devang Patel09f162c2007-05-01 21:15:47 +00002234 PredicateSimplifier() : FunctionPass((intptr_t)&ID) {}
2235
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002236 bool runOnFunction(Function &F);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002237
2238 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
2239 AU.addRequiredID(BreakCriticalEdgesID);
Owen Anderson510fefc2007-04-25 04:18:54 +00002240 AU.addRequired<DominatorTree>();
Nick Lewycky12d44ab2007-04-07 03:16:12 +00002241 AU.addRequired<TargetData>();
2242 AU.addPreserved<TargetData>();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002243 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002244
2245 private:
Nick Lewyckyb7c0c8a2007-07-16 02:58:37 +00002246 /// Forwards - Adds new properties to VRPSolver and uses them to
Nick Lewycky77e030b2006-10-12 02:02:44 +00002247 /// simplify instructions. Because new properties sometimes apply to
2248 /// a transition from one BasicBlock to another, this will use the
2249 /// PredicateSimplifier::proceedToSuccessor(s) interface to enter the
Nick Lewyckyb7c0c8a2007-07-16 02:58:37 +00002250 /// basic block.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002251 /// @brief Performs abstract execution of the program.
2252 class VISIBILITY_HIDDEN Forwards : public InstVisitor<Forwards> {
Nick Lewycky77e030b2006-10-12 02:02:44 +00002253 friend class InstVisitor<Forwards>;
2254 PredicateSimplifier *PS;
Nick Lewycky26e25d32007-06-24 04:36:20 +00002255 DomTreeDFS::Node *DTNode;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002256
Nick Lewycky77e030b2006-10-12 02:02:44 +00002257 public:
Nick Lewycky73dd6922007-07-05 03:15:00 +00002258 ValueNumbering &VN;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002259 InequalityGraph &IG;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002260 UnreachableBlocks &UB;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002261 ValueRanges &VR;
Nick Lewycky77e030b2006-10-12 02:02:44 +00002262
Nick Lewycky26e25d32007-06-24 04:36:20 +00002263 Forwards(PredicateSimplifier *PS, DomTreeDFS::Node *DTNode)
Nick Lewycky73dd6922007-07-05 03:15:00 +00002264 : PS(PS), DTNode(DTNode), VN(*PS->VN), IG(*PS->IG), UB(PS->UB),
2265 VR(*PS->VR) {}
Nick Lewycky77e030b2006-10-12 02:02:44 +00002266
2267 void visitTerminatorInst(TerminatorInst &TI);
2268 void visitBranchInst(BranchInst &BI);
2269 void visitSwitchInst(SwitchInst &SI);
2270
Nick Lewyckyf3450082006-10-22 19:53:27 +00002271 void visitAllocaInst(AllocaInst &AI);
Nick Lewycky77e030b2006-10-12 02:02:44 +00002272 void visitLoadInst(LoadInst &LI);
2273 void visitStoreInst(StoreInst &SI);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002274
Nick Lewycky15245952007-02-04 23:43:05 +00002275 void visitSExtInst(SExtInst &SI);
2276 void visitZExtInst(ZExtInst &ZI);
2277
Nick Lewycky77e030b2006-10-12 02:02:44 +00002278 void visitBinaryOperator(BinaryOperator &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002279 void visitICmpInst(ICmpInst &IC);
Nick Lewycky77e030b2006-10-12 02:02:44 +00002280 };
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002281
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002282 // Used by terminator instructions to proceed from the current basic
2283 // block to the next. Verifies that "current" dominates "next",
2284 // then calls visitBasicBlock.
Nick Lewycky26e25d32007-06-24 04:36:20 +00002285 void proceedToSuccessors(DomTreeDFS::Node *Current) {
2286 for (DomTreeDFS::Node::iterator I = Current->begin(),
Owen Anderson510fefc2007-04-25 04:18:54 +00002287 E = Current->end(); I != E; ++I) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002288 WorkList.push_back(*I);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002289 }
2290 }
2291
Nick Lewycky26e25d32007-06-24 04:36:20 +00002292 void proceedToSuccessor(DomTreeDFS::Node *Next) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002293 WorkList.push_back(Next);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002294 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002295
2296 // Visits each instruction in the basic block.
Nick Lewycky26e25d32007-06-24 04:36:20 +00002297 void visitBasicBlock(DomTreeDFS::Node *Node) {
Owen Anderson510fefc2007-04-25 04:18:54 +00002298 BasicBlock *BB = Node->getBlock();
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002299 DOUT << "Entering Basic Block: " << BB->getName()
Nick Lewycky26e25d32007-06-24 04:36:20 +00002300 << " (" << Node->getDFSNumIn() << ")\n";
Bill Wendling22e978a2006-12-07 20:04:42 +00002301 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002302 visitInstruction(I++, Node);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002303 }
2304 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002305
Nick Lewyckyb7c0c8a2007-07-16 02:58:37 +00002306 // Tries to simplify each Instruction and add new properties.
Nick Lewycky26e25d32007-06-24 04:36:20 +00002307 void visitInstruction(Instruction *I, DomTreeDFS::Node *DT) {
Bill Wendling22e978a2006-12-07 20:04:42 +00002308 DOUT << "Considering instruction " << *I << "\n";
Nick Lewyckye635cc42007-07-10 03:28:21 +00002309 DEBUG(VN->dump());
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002310 DEBUG(IG->dump());
Nick Lewyckye635cc42007-07-10 03:28:21 +00002311 DEBUG(VR->dump());
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002312
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002313 // Sometimes instructions are killed in earlier analysis.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002314 if (isInstructionTriviallyDead(I)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002315 ++NumSimple;
2316 modified = true;
Nick Lewycky73dd6922007-07-05 03:15:00 +00002317 if (unsigned n = VN->valueNumber(I, DTDFS->getRootNode()))
2318 if (VN->value(n) == I) IG->remove(n);
2319 VN->remove(I);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002320 I->eraseFromParent();
2321 return;
2322 }
2323
Nick Lewycky42944462007-01-13 02:05:28 +00002324#ifndef NDEBUG
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002325 // Try to replace the whole instruction.
Nick Lewycky73dd6922007-07-05 03:15:00 +00002326 Value *V = VN->canonicalize(I, DT);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002327 assert(V == I && "Late instruction canonicalization.");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002328 if (V != I) {
2329 modified = true;
2330 ++NumInstruction;
Bill Wendling22e978a2006-12-07 20:04:42 +00002331 DOUT << "Removing " << *I << ", replacing with " << *V << "\n";
Nick Lewycky73dd6922007-07-05 03:15:00 +00002332 if (unsigned n = VN->valueNumber(I, DTDFS->getRootNode()))
2333 if (VN->value(n) == I) IG->remove(n);
2334 VN->remove(I);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002335 I->replaceAllUsesWith(V);
2336 I->eraseFromParent();
2337 return;
2338 }
2339
2340 // Try to substitute operands.
2341 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2342 Value *Oper = I->getOperand(i);
Nick Lewycky73dd6922007-07-05 03:15:00 +00002343 Value *V = VN->canonicalize(Oper, DT);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002344 assert(V == Oper && "Late operand canonicalization.");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002345 if (V != Oper) {
2346 modified = true;
2347 ++NumVarsReplaced;
Bill Wendling22e978a2006-12-07 20:04:42 +00002348 DOUT << "Resolving " << *I;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002349 I->setOperand(i, V);
Bill Wendling22e978a2006-12-07 20:04:42 +00002350 DOUT << " into " << *I;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002351 }
2352 }
Nick Lewycky42944462007-01-13 02:05:28 +00002353#endif
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002354
Nick Lewycky4f73de22007-03-16 02:37:39 +00002355 std::string name = I->getParent()->getName();
2356 DOUT << "push (%" << name << ")\n";
Owen Anderson510fefc2007-04-25 04:18:54 +00002357 Forwards visit(this, DT);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002358 visit.visit(*I);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002359 DOUT << "pop (%" << name << ")\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002360 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002361 };
2362
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002363 bool PredicateSimplifier::runOnFunction(Function &F) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002364 DominatorTree *DT = &getAnalysis<DominatorTree>();
2365 DTDFS = new DomTreeDFS(DT);
Nick Lewycky12d44ab2007-04-07 03:16:12 +00002366 TargetData *TD = &getAnalysis<TargetData>();
2367
Bill Wendling22e978a2006-12-07 20:04:42 +00002368 DOUT << "Entering Function: " << F.getName() << "\n";
Nick Lewyckycfff1c32006-09-20 17:04:01 +00002369
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002370 modified = false;
Nick Lewycky26e25d32007-06-24 04:36:20 +00002371 DomTreeDFS::Node *Root = DTDFS->getRootNode();
Nick Lewycky73dd6922007-07-05 03:15:00 +00002372 VN = new ValueNumbering(DTDFS);
2373 IG = new InequalityGraph(*VN, Root);
Nick Lewyckye635cc42007-07-10 03:28:21 +00002374 VR = new ValueRanges(*VN, TD);
Nick Lewycky26e25d32007-06-24 04:36:20 +00002375 WorkList.push_back(Root);
Nick Lewyckycfff1c32006-09-20 17:04:01 +00002376
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002377 do {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002378 DomTreeDFS::Node *DTNode = WorkList.back();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002379 WorkList.pop_back();
Owen Anderson510fefc2007-04-25 04:18:54 +00002380 if (!UB.isDead(DTNode->getBlock())) visitBasicBlock(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002381 } while (!WorkList.empty());
Nick Lewyckycfff1c32006-09-20 17:04:01 +00002382
Nick Lewycky26e25d32007-06-24 04:36:20 +00002383 delete DTDFS;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002384 delete VR;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002385 delete IG;
2386
2387 modified |= UB.kill();
Nick Lewyckycfff1c32006-09-20 17:04:01 +00002388
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002389 return modified;
Nick Lewycky8e559932006-09-02 19:40:38 +00002390 }
2391
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002392 void PredicateSimplifier::Forwards::visitTerminatorInst(TerminatorInst &TI) {
Owen Anderson510fefc2007-04-25 04:18:54 +00002393 PS->proceedToSuccessors(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002394 }
2395
2396 void PredicateSimplifier::Forwards::visitBranchInst(BranchInst &BI) {
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002397 if (BI.isUnconditional()) {
Owen Anderson510fefc2007-04-25 04:18:54 +00002398 PS->proceedToSuccessors(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002399 return;
2400 }
2401
2402 Value *Condition = BI.getCondition();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002403 BasicBlock *TrueDest = BI.getSuccessor(0);
2404 BasicBlock *FalseDest = BI.getSuccessor(1);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002405
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002406 if (isa<Constant>(Condition) || TrueDest == FalseDest) {
Owen Anderson510fefc2007-04-25 04:18:54 +00002407 PS->proceedToSuccessors(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002408 return;
2409 }
2410
Nick Lewycky26e25d32007-06-24 04:36:20 +00002411 for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
Owen Anderson510fefc2007-04-25 04:18:54 +00002412 I != E; ++I) {
2413 BasicBlock *Dest = (*I)->getBlock();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002414 DOUT << "Branch thinking about %" << Dest->getName()
Nick Lewycky26e25d32007-06-24 04:36:20 +00002415 << "(" << PS->DTDFS->getNodeForBlock(Dest)->getDFSNumIn() << ")\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002416
2417 if (Dest == TrueDest) {
Owen Anderson510fefc2007-04-25 04:18:54 +00002418 DOUT << "(" << DTNode->getBlock()->getName() << ") true set:\n";
Nick Lewycky73dd6922007-07-05 03:15:00 +00002419 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002420 VRP.add(ConstantInt::getTrue(), Condition, ICmpInst::ICMP_EQ);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002421 VRP.solve();
Nick Lewyckye635cc42007-07-10 03:28:21 +00002422 DEBUG(VN.dump());
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002423 DEBUG(IG.dump());
Nick Lewyckye635cc42007-07-10 03:28:21 +00002424 DEBUG(VR.dump());
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002425 } else if (Dest == FalseDest) {
Owen Anderson510fefc2007-04-25 04:18:54 +00002426 DOUT << "(" << DTNode->getBlock()->getName() << ") false set:\n";
Nick Lewycky73dd6922007-07-05 03:15:00 +00002427 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002428 VRP.add(ConstantInt::getFalse(), Condition, ICmpInst::ICMP_EQ);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002429 VRP.solve();
Nick Lewyckye635cc42007-07-10 03:28:21 +00002430 DEBUG(VN.dump());
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002431 DEBUG(IG.dump());
Nick Lewyckye635cc42007-07-10 03:28:21 +00002432 DEBUG(VR.dump());
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002433 }
2434
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002435 PS->proceedToSuccessor(*I);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002436 }
2437 }
2438
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002439 void PredicateSimplifier::Forwards::visitSwitchInst(SwitchInst &SI) {
2440 Value *Condition = SI.getCondition();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002441
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002442 // Set the EQProperty in each of the cases BBs, and the NEProperties
2443 // in the default BB.
Owen Anderson510fefc2007-04-25 04:18:54 +00002444
Nick Lewycky26e25d32007-06-24 04:36:20 +00002445 for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
Owen Anderson510fefc2007-04-25 04:18:54 +00002446 I != E; ++I) {
2447 BasicBlock *BB = (*I)->getBlock();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002448 DOUT << "Switch thinking about BB %" << BB->getName()
Nick Lewycky26e25d32007-06-24 04:36:20 +00002449 << "(" << PS->DTDFS->getNodeForBlock(BB)->getDFSNumIn() << ")\n";
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002450
Nick Lewycky73dd6922007-07-05 03:15:00 +00002451 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, BB);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002452 if (BB == SI.getDefaultDest()) {
2453 for (unsigned i = 1, e = SI.getNumCases(); i < e; ++i)
2454 if (SI.getSuccessor(i) != BB)
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002455 VRP.add(Condition, SI.getCaseValue(i), ICmpInst::ICMP_NE);
2456 VRP.solve();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002457 } else if (ConstantInt *CI = SI.findCaseDest(BB)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002458 VRP.add(Condition, CI, ICmpInst::ICMP_EQ);
2459 VRP.solve();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002460 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002461 PS->proceedToSuccessor(*I);
Nick Lewycky1d00f3e2006-10-03 15:19:11 +00002462 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002463 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002464
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002465 void PredicateSimplifier::Forwards::visitAllocaInst(AllocaInst &AI) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002466 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &AI);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002467 VRP.add(Constant::getNullValue(AI.getType()), &AI, ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002468 VRP.solve();
2469 }
Nick Lewyckyf3450082006-10-22 19:53:27 +00002470
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002471 void PredicateSimplifier::Forwards::visitLoadInst(LoadInst &LI) {
2472 Value *Ptr = LI.getPointerOperand();
2473 // avoid "load uint* null" -> null NE null.
2474 if (isa<Constant>(Ptr)) return;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002475
Nick Lewycky73dd6922007-07-05 03:15:00 +00002476 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &LI);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002477 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002478 VRP.solve();
2479 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002480
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002481 void PredicateSimplifier::Forwards::visitStoreInst(StoreInst &SI) {
2482 Value *Ptr = SI.getPointerOperand();
2483 if (isa<Constant>(Ptr)) return;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002484
Nick Lewycky73dd6922007-07-05 03:15:00 +00002485 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002486 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002487 VRP.solve();
2488 }
2489
Nick Lewycky15245952007-02-04 23:43:05 +00002490 void PredicateSimplifier::Forwards::visitSExtInst(SExtInst &SI) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002491 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
Reid Spencerc34dedf2007-03-03 00:48:31 +00002492 uint32_t SrcBitWidth = cast<IntegerType>(SI.getSrcTy())->getBitWidth();
2493 uint32_t DstBitWidth = cast<IntegerType>(SI.getDestTy())->getBitWidth();
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00002494 APInt Min(APInt::getHighBitsSet(DstBitWidth, DstBitWidth-SrcBitWidth+1));
2495 APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth-1));
Reid Spencerc34dedf2007-03-03 00:48:31 +00002496 VRP.add(ConstantInt::get(Min), &SI, ICmpInst::ICMP_SLE);
2497 VRP.add(ConstantInt::get(Max), &SI, ICmpInst::ICMP_SGE);
Nick Lewycky15245952007-02-04 23:43:05 +00002498 VRP.solve();
2499 }
2500
2501 void PredicateSimplifier::Forwards::visitZExtInst(ZExtInst &ZI) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002502 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &ZI);
Reid Spencerc34dedf2007-03-03 00:48:31 +00002503 uint32_t SrcBitWidth = cast<IntegerType>(ZI.getSrcTy())->getBitWidth();
2504 uint32_t DstBitWidth = cast<IntegerType>(ZI.getDestTy())->getBitWidth();
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00002505 APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth));
Reid Spencerc34dedf2007-03-03 00:48:31 +00002506 VRP.add(ConstantInt::get(Max), &ZI, ICmpInst::ICMP_UGE);
Nick Lewycky15245952007-02-04 23:43:05 +00002507 VRP.solve();
2508 }
2509
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002510 void PredicateSimplifier::Forwards::visitBinaryOperator(BinaryOperator &BO) {
2511 Instruction::BinaryOps ops = BO.getOpcode();
2512
2513 switch (ops) {
Nick Lewycky4f73de22007-03-16 02:37:39 +00002514 default: break;
Nick Lewycky15245952007-02-04 23:43:05 +00002515 case Instruction::URem:
2516 case Instruction::SRem:
2517 case Instruction::UDiv:
2518 case Instruction::SDiv: {
2519 Value *Divisor = BO.getOperand(1);
Nick Lewycky73dd6922007-07-05 03:15:00 +00002520 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky15245952007-02-04 23:43:05 +00002521 VRP.add(Constant::getNullValue(Divisor->getType()), Divisor,
2522 ICmpInst::ICMP_NE);
2523 VRP.solve();
2524 break;
2525 }
Nick Lewycky4f73de22007-03-16 02:37:39 +00002526 }
2527
2528 switch (ops) {
2529 default: break;
2530 case Instruction::Shl: {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002531 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002532 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
2533 VRP.solve();
2534 } break;
2535 case Instruction::AShr: {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002536 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002537 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_SLE);
2538 VRP.solve();
2539 } break;
2540 case Instruction::LShr:
2541 case Instruction::UDiv: {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002542 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002543 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
2544 VRP.solve();
2545 } break;
2546 case Instruction::URem: {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002547 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002548 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
2549 VRP.solve();
2550 } break;
2551 case Instruction::And: {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002552 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002553 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
2554 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
2555 VRP.solve();
2556 } break;
2557 case Instruction::Or: {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002558 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002559 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
2560 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_UGE);
2561 VRP.solve();
2562 } break;
2563 }
2564 }
2565
2566 void PredicateSimplifier::Forwards::visitICmpInst(ICmpInst &IC) {
2567 // If possible, squeeze the ICmp predicate into something simpler.
2568 // Eg., if x = [0, 4) and we're being asked icmp uge %x, 3 then change
2569 // the predicate to eq.
2570
Nick Lewyckyeeb01b42007-04-07 02:30:14 +00002571 // XXX: once we do full PHI handling, modifying the instruction in the
2572 // Forwards visitor will cause missed optimizations.
2573
Nick Lewycky4f73de22007-03-16 02:37:39 +00002574 ICmpInst::Predicate Pred = IC.getPredicate();
2575
Nick Lewyckyeeb01b42007-04-07 02:30:14 +00002576 switch (Pred) {
2577 default: break;
2578 case ICmpInst::ICMP_ULE: Pred = ICmpInst::ICMP_ULT; break;
2579 case ICmpInst::ICMP_UGE: Pred = ICmpInst::ICMP_UGT; break;
2580 case ICmpInst::ICMP_SLE: Pred = ICmpInst::ICMP_SLT; break;
2581 case ICmpInst::ICMP_SGE: Pred = ICmpInst::ICMP_SGT; break;
2582 }
2583 if (Pred != IC.getPredicate()) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002584 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &IC);
Nick Lewyckyeeb01b42007-04-07 02:30:14 +00002585 if (VRP.isRelatedBy(IC.getOperand(1), IC.getOperand(0),
2586 ICmpInst::ICMP_NE)) {
2587 ++NumSnuggle;
2588 PS->modified = true;
2589 IC.setPredicate(Pred);
2590 }
2591 }
2592
2593 Pred = IC.getPredicate();
2594
Nick Lewycky4f73de22007-03-16 02:37:39 +00002595 if (ConstantInt *Op1 = dyn_cast<ConstantInt>(IC.getOperand(1))) {
2596 ConstantInt *NextVal = 0;
Nick Lewyckyeeb01b42007-04-07 02:30:14 +00002597 switch (Pred) {
Nick Lewycky4f73de22007-03-16 02:37:39 +00002598 default: break;
2599 case ICmpInst::ICMP_SLT:
2600 case ICmpInst::ICMP_ULT:
2601 if (Op1->getValue() != 0)
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00002602 NextVal = ConstantInt::get(Op1->getValue()-1);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002603 break;
2604 case ICmpInst::ICMP_SGT:
2605 case ICmpInst::ICMP_UGT:
2606 if (!Op1->getValue().isAllOnesValue())
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00002607 NextVal = ConstantInt::get(Op1->getValue()+1);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002608 break;
2609
2610 }
2611 if (NextVal) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002612 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &IC);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002613 if (VRP.isRelatedBy(IC.getOperand(0), NextVal,
2614 ICmpInst::getInversePredicate(Pred))) {
2615 ICmpInst *NewIC = new ICmpInst(ICmpInst::ICMP_EQ, IC.getOperand(0),
2616 NextVal, "", &IC);
2617 NewIC->takeName(&IC);
2618 IC.replaceAllUsesWith(NewIC);
Nick Lewycky73dd6922007-07-05 03:15:00 +00002619
2620 // XXX: prove this isn't necessary
2621 if (unsigned n = VN.valueNumber(&IC, PS->DTDFS->getRootNode()))
2622 if (VN.value(n) == &IC) IG.remove(n);
2623 VN.remove(&IC);
2624
Nick Lewycky4f73de22007-03-16 02:37:39 +00002625 IC.eraseFromParent();
2626 ++NumSnuggle;
2627 PS->modified = true;
Nick Lewycky4f73de22007-03-16 02:37:39 +00002628 }
2629 }
2630 }
Nick Lewycky5f8f9af2006-08-30 02:46:48 +00002631 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002632
Devang Patel8c78a0b2007-05-03 01:11:54 +00002633 char PredicateSimplifier::ID = 0;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002634 RegisterPass<PredicateSimplifier> X("predsimplify",
2635 "Predicate Simplifier");
2636}
2637
2638FunctionPass *llvm::createPredicateSimplifierPass() {
2639 return new PredicateSimplifier();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002640}