blob: 972e875d4b0d04307b652eed3e4b1af836e4343a [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
Nick Lewycky20f08112007-08-04 18:45:32 +000073// %b = [0, 254].
Nick Lewycky4f73de22007-03-16 02:37:39 +000074//
75// It never stores an empty range, because that means that the code is
76// unreachable. It never stores a single-element range since that's an equality
Nick Lewycky12d44ab2007-04-07 03:16:12 +000077// relationship and better stored in the InequalityGraph, nor an empty range
78// since that is better stored in UnreachableBlocks.
Nick Lewycky4f73de22007-03-16 02:37:39 +000079//
80//===----------------------------------------------------------------------===//
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000081
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000082#define DEBUG_TYPE "predsimplify"
83#include "llvm/Transforms/Scalar.h"
84#include "llvm/Constants.h"
Nick Lewyckyf3450082006-10-22 19:53:27 +000085#include "llvm/DerivedTypes.h"
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000086#include "llvm/Instructions.h"
87#include "llvm/Pass.h"
Nick Lewycky2fc338f2007-01-11 02:32:38 +000088#include "llvm/ADT/DepthFirstIterator.h"
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000089#include "llvm/ADT/SetOperations.h"
Reid Spencer3f4e6e82007-02-04 00:40:42 +000090#include "llvm/ADT/SetVector.h"
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000091#include "llvm/ADT/Statistic.h"
92#include "llvm/ADT/STLExtras.h"
93#include "llvm/Analysis/Dominators.h"
Nick Lewyckye635cc42007-07-10 03:28:21 +000094#include "llvm/Assembly/Writer.h"
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000095#include "llvm/Support/CFG.h"
Chris Lattnerf06bb652006-12-06 18:14:47 +000096#include "llvm/Support/Compiler.h"
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +000097#include "llvm/Support/ConstantRange.h"
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000098#include "llvm/Support/Debug.h"
Nick Lewycky77e030b2006-10-12 02:02:44 +000099#include "llvm/Support/InstVisitor.h"
Nick Lewycky12d44ab2007-04-07 03:16:12 +0000100#include "llvm/Target/TargetData.h"
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000101#include "llvm/Transforms/Utils/Local.h"
102#include <algorithm>
103#include <deque>
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000104#include <sstream>
Nick Lewycky26e25d32007-06-24 04:36:20 +0000105#include <stack>
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000106using namespace llvm;
107
Chris Lattner0e5255b2006-12-19 21:49:03 +0000108STATISTIC(NumVarsReplaced, "Number of argument substitutions");
109STATISTIC(NumInstruction , "Number of instructions removed");
110STATISTIC(NumSimple , "Number of simple replacements");
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000111STATISTIC(NumBlocks , "Number of blocks marked unreachable");
Nick Lewycky4f73de22007-03-16 02:37:39 +0000112STATISTIC(NumSnuggle , "Number of comparisons snuggled");
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000113
Chris Lattner0e5255b2006-12-19 21:49:03 +0000114namespace {
Nick Lewycky26e25d32007-06-24 04:36:20 +0000115 class DomTreeDFS {
116 public:
117 class Node {
118 friend class DomTreeDFS;
119 public:
120 typedef std::vector<Node *>::iterator iterator;
121 typedef std::vector<Node *>::const_iterator const_iterator;
122
123 unsigned getDFSNumIn() const { return DFSin; }
124 unsigned getDFSNumOut() const { return DFSout; }
125
126 BasicBlock *getBlock() const { return BB; }
127
128 iterator begin() { return Children.begin(); }
129 iterator end() { return Children.end(); }
130
131 const_iterator begin() const { return Children.begin(); }
132 const_iterator end() const { return Children.end(); }
133
134 bool dominates(const Node *N) const {
135 return DFSin <= N->DFSin && DFSout >= N->DFSout;
136 }
137
138 bool DominatedBy(const Node *N) const {
139 return N->dominates(this);
140 }
141
142 /// Sorts by the number of descendants. With this, you can iterate
143 /// through a sorted list and the first matching entry is the most
144 /// specific match for your basic block. The order provided is stable;
145 /// DomTreeDFS::Nodes with the same number of descendants are sorted by
146 /// DFS in number.
147 bool operator<(const Node &N) const {
148 unsigned spread = DFSout - DFSin;
149 unsigned N_spread = N.DFSout - N.DFSin;
150 if (spread == N_spread) return DFSin < N.DFSin;
Nick Lewycky73dd6922007-07-05 03:15:00 +0000151 return spread < N_spread;
Nick Lewycky26e25d32007-06-24 04:36:20 +0000152 }
153 bool operator>(const Node &N) const { return N < *this; }
154
155 private:
156 unsigned DFSin, DFSout;
157 BasicBlock *BB;
158
159 std::vector<Node *> Children;
160 };
161
162 // XXX: this may be slow. Instead of using "new" for each node, consider
163 // putting them in a vector to keep them contiguous.
164 explicit DomTreeDFS(DominatorTree *DT) {
165 std::stack<std::pair<Node *, DomTreeNode *> > S;
166
167 Entry = new Node;
168 Entry->BB = DT->getRootNode()->getBlock();
169 S.push(std::make_pair(Entry, DT->getRootNode()));
170
171 NodeMap[Entry->BB] = Entry;
172
173 while (!S.empty()) {
174 std::pair<Node *, DomTreeNode *> &Pair = S.top();
175 Node *N = Pair.first;
176 DomTreeNode *DTNode = Pair.second;
177 S.pop();
178
179 for (DomTreeNode::iterator I = DTNode->begin(), E = DTNode->end();
180 I != E; ++I) {
181 Node *NewNode = new Node;
182 NewNode->BB = (*I)->getBlock();
183 N->Children.push_back(NewNode);
184 S.push(std::make_pair(NewNode, *I));
185
186 NodeMap[NewNode->BB] = NewNode;
187 }
188 }
189
190 renumber();
191
192#ifndef NDEBUG
193 DEBUG(dump());
194#endif
195 }
196
197#ifndef NDEBUG
198 virtual
199#endif
200 ~DomTreeDFS() {
201 std::stack<Node *> S;
202
203 S.push(Entry);
204 while (!S.empty()) {
205 Node *N = S.top(); S.pop();
206
207 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I)
208 S.push(*I);
209
210 delete N;
211 }
212 }
213
Nick Lewyckyb7c0c8a2007-07-16 02:58:37 +0000214 /// getRootNode - This returns the entry node for the CFG of the function.
Nick Lewycky26e25d32007-06-24 04:36:20 +0000215 Node *getRootNode() const { return Entry; }
216
Nick Lewyckyb7c0c8a2007-07-16 02:58:37 +0000217 /// getNodeForBlock - return the node for the specified basic block.
Nick Lewycky26e25d32007-06-24 04:36:20 +0000218 Node *getNodeForBlock(BasicBlock *BB) const {
219 if (!NodeMap.count(BB)) return 0;
Nick Lewycky73dd6922007-07-05 03:15:00 +0000220 return const_cast<DomTreeDFS*>(this)->NodeMap[BB];
Nick Lewycky26e25d32007-06-24 04:36:20 +0000221 }
222
Nick Lewyckyb7c0c8a2007-07-16 02:58:37 +0000223 /// dominates - returns true if the basic block for I1 dominates that of
224 /// the basic block for I2. If the instructions belong to the same basic
225 /// block, the instruction first instruction sequentially in the block is
226 /// considered dominating.
Nick Lewycky26e25d32007-06-24 04:36:20 +0000227 bool dominates(Instruction *I1, Instruction *I2) {
228 BasicBlock *BB1 = I1->getParent(),
229 *BB2 = I2->getParent();
230 if (BB1 == BB2) {
231 if (isa<TerminatorInst>(I1)) return false;
232 if (isa<TerminatorInst>(I2)) return true;
233 if ( isa<PHINode>(I1) && !isa<PHINode>(I2)) return true;
234 if (!isa<PHINode>(I1) && isa<PHINode>(I2)) return false;
235
236 for (BasicBlock::const_iterator I = BB2->begin(), E = BB2->end();
237 I != E; ++I) {
238 if (&*I == I1) return true;
239 else if (&*I == I2) return false;
240 }
241 assert(!"Instructions not found in parent BasicBlock?");
242 } else {
Nick Lewycky0f986fd2007-06-24 04:40:16 +0000243 Node *Node1 = getNodeForBlock(BB1),
Nick Lewycky26e25d32007-06-24 04:36:20 +0000244 *Node2 = getNodeForBlock(BB2);
Nick Lewycky73dd6922007-07-05 03:15:00 +0000245 return Node1 && Node2 && Node1->dominates(Node2);
Nick Lewycky26e25d32007-06-24 04:36:20 +0000246 }
247 }
Nick Lewyckyb7c0c8a2007-07-16 02:58:37 +0000248
Nick Lewycky26e25d32007-06-24 04:36:20 +0000249 private:
Nick Lewyckyb7c0c8a2007-07-16 02:58:37 +0000250 /// renumber - calculates the depth first search numberings and applies
251 /// them onto the nodes.
Nick Lewycky26e25d32007-06-24 04:36:20 +0000252 void renumber() {
253 std::stack<std::pair<Node *, Node::iterator> > S;
254 unsigned n = 0;
255
256 Entry->DFSin = ++n;
257 S.push(std::make_pair(Entry, Entry->begin()));
258
259 while (!S.empty()) {
260 std::pair<Node *, Node::iterator> &Pair = S.top();
261 Node *N = Pair.first;
262 Node::iterator &I = Pair.second;
263
264 if (I == N->end()) {
265 N->DFSout = ++n;
266 S.pop();
267 } else {
268 Node *Next = *I++;
269 Next->DFSin = ++n;
270 S.push(std::make_pair(Next, Next->begin()));
271 }
272 }
273 }
274
275#ifndef NDEBUG
276 virtual void dump() const {
277 dump(*cerr.stream());
278 }
279
280 void dump(std::ostream &os) const {
281 os << "Predicate simplifier DomTreeDFS: \n";
282 dump(Entry, 0, os);
283 os << "\n\n";
284 }
285
286 void dump(Node *N, int depth, std::ostream &os) const {
287 ++depth;
288 for (int i = 0; i < depth; ++i) { os << " "; }
289 os << "[" << depth << "] ";
290
291 os << N->getBlock()->getName() << " (" << N->getDFSNumIn()
292 << ", " << N->getDFSNumOut() << ")\n";
293
294 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I)
295 dump(*I, depth, os);
296 }
297#endif
298
299 Node *Entry;
300 std::map<BasicBlock *, Node *> NodeMap;
301 };
302
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000303 // SLT SGT ULT UGT EQ
304 // 0 1 0 1 0 -- GT 10
305 // 0 1 0 1 1 -- GE 11
306 // 0 1 1 0 0 -- SGTULT 12
307 // 0 1 1 0 1 -- SGEULE 13
Nick Lewycky56639802007-01-29 02:56:54 +0000308 // 0 1 1 1 0 -- SGT 14
309 // 0 1 1 1 1 -- SGE 15
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000310 // 1 0 0 1 0 -- SLTUGT 18
311 // 1 0 0 1 1 -- SLEUGE 19
312 // 1 0 1 0 0 -- LT 20
313 // 1 0 1 0 1 -- LE 21
Nick Lewycky56639802007-01-29 02:56:54 +0000314 // 1 0 1 1 0 -- SLT 22
315 // 1 0 1 1 1 -- SLE 23
316 // 1 1 0 1 0 -- UGT 26
317 // 1 1 0 1 1 -- UGE 27
318 // 1 1 1 0 0 -- ULT 28
319 // 1 1 1 0 1 -- ULE 29
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000320 // 1 1 1 1 0 -- NE 30
321 enum LatticeBits {
322 EQ_BIT = 1, UGT_BIT = 2, ULT_BIT = 4, SGT_BIT = 8, SLT_BIT = 16
323 };
324 enum LatticeVal {
325 GT = SGT_BIT | UGT_BIT,
326 GE = GT | EQ_BIT,
327 LT = SLT_BIT | ULT_BIT,
328 LE = LT | EQ_BIT,
329 NE = SLT_BIT | SGT_BIT | ULT_BIT | UGT_BIT,
330 SGTULT = SGT_BIT | ULT_BIT,
331 SGEULE = SGTULT | EQ_BIT,
332 SLTUGT = SLT_BIT | UGT_BIT,
333 SLEUGE = SLTUGT | EQ_BIT,
Nick Lewycky56639802007-01-29 02:56:54 +0000334 ULT = SLT_BIT | SGT_BIT | ULT_BIT,
335 UGT = SLT_BIT | SGT_BIT | UGT_BIT,
336 SLT = SLT_BIT | ULT_BIT | UGT_BIT,
337 SGT = SGT_BIT | ULT_BIT | UGT_BIT,
338 SLE = SLT | EQ_BIT,
339 SGE = SGT | EQ_BIT,
340 ULE = ULT | EQ_BIT,
341 UGE = UGT | EQ_BIT
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000342 };
343
Nick Lewycky20f08112007-08-04 18:45:32 +0000344 /// validPredicate - determines whether a given value is actually a lattice
345 /// value. Only used in assertions or debugging.
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000346 static bool validPredicate(LatticeVal LV) {
347 switch (LV) {
Nick Lewycky15245952007-02-04 23:43:05 +0000348 case GT: case GE: case LT: case LE: case NE:
349 case SGTULT: case SGT: case SGEULE:
350 case SLTUGT: case SLT: case SLEUGE:
351 case ULT: case UGT:
352 case SLE: case SGE: case ULE: case UGE:
353 return true;
354 default:
355 return false;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000356 }
357 }
358
359 /// reversePredicate - reverse the direction of the inequality
360 static LatticeVal reversePredicate(LatticeVal LV) {
361 unsigned reverse = LV ^ (SLT_BIT|SGT_BIT|ULT_BIT|UGT_BIT); //preserve EQ_BIT
Nick Lewycky4f73de22007-03-16 02:37:39 +0000362
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000363 if ((reverse & (SLT_BIT|SGT_BIT)) == 0)
364 reverse |= (SLT_BIT|SGT_BIT);
365
366 if ((reverse & (ULT_BIT|UGT_BIT)) == 0)
367 reverse |= (ULT_BIT|UGT_BIT);
368
369 LatticeVal Rev = static_cast<LatticeVal>(reverse);
370 assert(validPredicate(Rev) && "Failed reversing predicate.");
371 return Rev;
372 }
373
Nick Lewycky73dd6922007-07-05 03:15:00 +0000374 /// ValueNumbering stores the scope-specific value numbers for a given Value.
375 class VISIBILITY_HIDDEN ValueNumbering {
Nick Lewycky20f08112007-08-04 18:45:32 +0000376
377 /// VNPair is a tuple of {Value, index number, DomTreeDFS::Node}. It
378 /// includes the comparison operators necessary to allow you to store it
379 /// in a sorted vector.
Nick Lewycky73dd6922007-07-05 03:15:00 +0000380 class VISIBILITY_HIDDEN VNPair {
381 public:
382 Value *V;
383 unsigned index;
384 DomTreeDFS::Node *Subtree;
385
386 VNPair(Value *V, unsigned index, DomTreeDFS::Node *Subtree)
387 : V(V), index(index), Subtree(Subtree) {}
388
389 bool operator==(const VNPair &RHS) const {
390 return V == RHS.V && Subtree == RHS.Subtree;
391 }
392
393 bool operator<(const VNPair &RHS) const {
394 if (V != RHS.V) return V < RHS.V;
395 return *Subtree < *RHS.Subtree;
396 }
397
398 bool operator<(Value *RHS) const {
399 return V < RHS;
400 }
Nick Lewycky20f08112007-08-04 18:45:32 +0000401
402 bool operator>(Value *RHS) const {
403 return V > RHS;
404 }
405
406 friend bool operator<(Value *RHS, const VNPair &pair) {
407 return pair.operator>(RHS);
408 }
Nick Lewycky73dd6922007-07-05 03:15:00 +0000409 };
410
411 typedef std::vector<VNPair> VNMapType;
412 VNMapType VNMap;
413
Nick Lewycky20f08112007-08-04 18:45:32 +0000414 /// The canonical choice for value number at index.
Nick Lewycky73dd6922007-07-05 03:15:00 +0000415 std::vector<Value *> Values;
416
417 DomTreeDFS *DTDFS;
418
419 public:
Nick Lewyckye635cc42007-07-10 03:28:21 +0000420#ifndef NDEBUG
421 virtual ~ValueNumbering() {}
422 virtual void dump() {
423 dump(*cerr.stream());
424 }
425
426 void dump(std::ostream &os) {
427 for (unsigned i = 1; i <= Values.size(); ++i) {
428 os << i << " = ";
429 WriteAsOperand(os, Values[i-1]);
430 os << " {";
431 for (unsigned j = 0; j < VNMap.size(); ++j) {
432 if (VNMap[j].index == i) {
433 WriteAsOperand(os, VNMap[j].V);
434 os << " (" << VNMap[j].Subtree->getDFSNumIn() << ") ";
435 }
436 }
437 os << "}\n";
438 }
439 }
440#endif
441
Nick Lewycky73dd6922007-07-05 03:15:00 +0000442 /// compare - returns true if V1 is a better canonical value than V2.
443 bool compare(Value *V1, Value *V2) const {
444 if (isa<Constant>(V1))
445 return !isa<Constant>(V2);
446 else if (isa<Constant>(V2))
447 return false;
448 else if (isa<Argument>(V1))
449 return !isa<Argument>(V2);
450 else if (isa<Argument>(V2))
451 return false;
452
453 Instruction *I1 = dyn_cast<Instruction>(V1);
454 Instruction *I2 = dyn_cast<Instruction>(V2);
455
456 if (!I1 || !I2)
457 return V1->getNumUses() < V2->getNumUses();
458
459 return DTDFS->dominates(I1, I2);
460 }
461
462 ValueNumbering(DomTreeDFS *DTDFS) : DTDFS(DTDFS) {}
463
464 /// valueNumber - finds the value number for V under the Subtree. If
465 /// there is no value number, returns zero.
466 unsigned valueNumber(Value *V, DomTreeDFS::Node *Subtree) {
Nick Lewyckye635cc42007-07-10 03:28:21 +0000467 if (!(isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V))
468 || V->getType() == Type::VoidTy) return 0;
469
Nick Lewycky73dd6922007-07-05 03:15:00 +0000470 VNMapType::iterator E = VNMap.end();
471 VNPair pair(V, 0, Subtree);
472 VNMapType::iterator I = std::lower_bound(VNMap.begin(), E, pair);
473 while (I != E && I->V == V) {
474 if (I->Subtree->dominates(Subtree))
475 return I->index;
476 ++I;
477 }
478 return 0;
479 }
480
Nick Lewyckye635cc42007-07-10 03:28:21 +0000481 /// getOrInsertVN - always returns a value number, creating it if necessary.
482 unsigned getOrInsertVN(Value *V, DomTreeDFS::Node *Subtree) {
483 if (unsigned n = valueNumber(V, Subtree))
484 return n;
485 else
486 return newVN(V);
487 }
488
Nick Lewycky73dd6922007-07-05 03:15:00 +0000489 /// newVN - creates a new value number. Value V must not already have a
490 /// value number assigned.
491 unsigned newVN(Value *V) {
Nick Lewyckye635cc42007-07-10 03:28:21 +0000492 assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
493 "Bad Value for value numbering.");
494 assert(V->getType() != Type::VoidTy && "Won't value number a void value");
495
Nick Lewycky73dd6922007-07-05 03:15:00 +0000496 Values.push_back(V);
497
498 VNPair pair = VNPair(V, Values.size(), DTDFS->getRootNode());
Nick Lewyckye635cc42007-07-10 03:28:21 +0000499 VNMapType::iterator I = std::lower_bound(VNMap.begin(), VNMap.end(), pair);
500 assert((I == VNMap.end() || value(I->index) != V) &&
Nick Lewycky73dd6922007-07-05 03:15:00 +0000501 "Attempt to create a duplicate value number.");
Nick Lewyckye635cc42007-07-10 03:28:21 +0000502 VNMap.insert(I, pair);
Nick Lewycky73dd6922007-07-05 03:15:00 +0000503
504 return Values.size();
505 }
506
507 /// value - returns the Value associated with a value number.
508 Value *value(unsigned index) const {
509 assert(index != 0 && "Zero index is reserved for not found.");
510 assert(index <= Values.size() && "Index out of range.");
511 return Values[index-1];
512 }
513
514 /// canonicalize - return a Value that is equal to V under Subtree.
515 Value *canonicalize(Value *V, DomTreeDFS::Node *Subtree) {
516 if (isa<Constant>(V)) return V;
517
518 if (unsigned n = valueNumber(V, Subtree))
519 return value(n);
520 else
521 return V;
522 }
523
524 /// addEquality - adds that value V belongs to the set of equivalent
525 /// values defined by value number n under Subtree.
526 void addEquality(unsigned n, Value *V, DomTreeDFS::Node *Subtree) {
527 assert(canonicalize(value(n), Subtree) == value(n) &&
528 "Node's 'canonical' choice isn't best within this subtree.");
529
530 // Suppose that we are given "%x -> node #1 (%y)". The problem is that
531 // we may already have "%z -> node #2 (%x)" somewhere above us in the
532 // graph. We need to find those edges and add "%z -> node #1 (%y)"
533 // to keep the lookups canonical.
534
535 std::vector<Value *> ToRepoint(1, V);
536
537 if (unsigned Conflict = valueNumber(V, Subtree)) {
538 for (VNMapType::iterator I = VNMap.begin(), E = VNMap.end();
539 I != E; ++I) {
540 if (I->index == Conflict && I->Subtree->dominates(Subtree))
541 ToRepoint.push_back(I->V);
542 }
543 }
544
545 for (std::vector<Value *>::iterator VI = ToRepoint.begin(),
546 VE = ToRepoint.end(); VI != VE; ++VI) {
547 Value *V = *VI;
548
549 VNPair pair(V, n, Subtree);
550 VNMapType::iterator B = VNMap.begin(), E = VNMap.end();
551 VNMapType::iterator I = std::lower_bound(B, E, pair);
552 if (I != E && I->V == V && I->Subtree == Subtree)
553 I->index = n; // Update best choice
Nick Lewyckye635cc42007-07-10 03:28:21 +0000554 else
Nick Lewycky73dd6922007-07-05 03:15:00 +0000555 VNMap.insert(I, pair); // New Value
556
557 // XXX: we currently don't have to worry about updating values with
558 // more specific Subtrees, but we will need to for PHI node support.
559
560#ifndef NDEBUG
561 Value *V_n = value(n);
562 if (isa<Constant>(V) && isa<Constant>(V_n)) {
563 assert(V == V_n && "Constant equals different constant?");
564 }
565#endif
566 }
567 }
568
569 /// remove - removes all references to value V.
570 void remove(Value *V) {
Nick Lewyckye635cc42007-07-10 03:28:21 +0000571 VNMapType::iterator B = VNMap.begin(), E = VNMap.end();
Nick Lewycky73dd6922007-07-05 03:15:00 +0000572 VNPair pair(V, 0, DTDFS->getRootNode());
Nick Lewyckye635cc42007-07-10 03:28:21 +0000573 VNMapType::iterator J = std::upper_bound(B, E, pair);
Nick Lewycky73dd6922007-07-05 03:15:00 +0000574 VNMapType::iterator I = J;
575
Nick Lewyckye635cc42007-07-10 03:28:21 +0000576 while (I != B && (I == E || I->V == V)) --I;
Nick Lewycky73dd6922007-07-05 03:15:00 +0000577
578 VNMap.erase(I, J);
579 }
580 };
581
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000582 /// The InequalityGraph stores the relationships between values.
583 /// Each Value in the graph is assigned to a Node. Nodes are pointer
584 /// comparable for equality. The caller is expected to maintain the logical
585 /// consistency of the system.
586 ///
587 /// The InequalityGraph class may invalidate Node*s after any mutator call.
588 /// @brief The InequalityGraph stores the relationships between values.
589 class VISIBILITY_HIDDEN InequalityGraph {
Nick Lewycky73dd6922007-07-05 03:15:00 +0000590 ValueNumbering &VN;
Nick Lewycky26e25d32007-06-24 04:36:20 +0000591 DomTreeDFS::Node *TreeRoot;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000592
593 InequalityGraph(); // DO NOT IMPLEMENT
594 InequalityGraph(InequalityGraph &); // DO NOT IMPLEMENT
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000595 public:
Nick Lewycky73dd6922007-07-05 03:15:00 +0000596 InequalityGraph(ValueNumbering &VN, DomTreeDFS::Node *TreeRoot)
597 : VN(VN), TreeRoot(TreeRoot) {}
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000598
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000599 class Node;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000600
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000601 /// An Edge is contained inside a Node making one end of the edge implicit
602 /// and contains a pointer to the other end. The edge contains a lattice
Nick Lewycky26e25d32007-06-24 04:36:20 +0000603 /// value specifying the relationship and an DomTreeDFS::Node specifying
604 /// the root in the dominator tree to which this edge applies.
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000605 class VISIBILITY_HIDDEN Edge {
606 public:
Nick Lewycky26e25d32007-06-24 04:36:20 +0000607 Edge(unsigned T, LatticeVal V, DomTreeDFS::Node *ST)
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000608 : To(T), LV(V), Subtree(ST) {}
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000609
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000610 unsigned To;
611 LatticeVal LV;
Nick Lewycky26e25d32007-06-24 04:36:20 +0000612 DomTreeDFS::Node *Subtree;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000613
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000614 bool operator<(const Edge &edge) const {
615 if (To != edge.To) return To < edge.To;
Nick Lewycky73dd6922007-07-05 03:15:00 +0000616 return *Subtree < *edge.Subtree;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000617 }
Nick Lewycky26e25d32007-06-24 04:36:20 +0000618
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000619 bool operator<(unsigned to) const {
620 return To < to;
621 }
Nick Lewycky26e25d32007-06-24 04:36:20 +0000622
Bill Wendling6357bf22007-06-04 23:52:59 +0000623 bool operator>(unsigned to) const {
624 return To > to;
625 }
626
627 friend bool operator<(unsigned to, const Edge &edge) {
628 return edge.operator>(to);
629 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000630 };
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000631
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000632 /// A single node in the InequalityGraph. This stores the canonical Value
633 /// for the node, as well as the relationships with the neighbours.
634 ///
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000635 /// @brief A single node in the InequalityGraph.
636 class VISIBILITY_HIDDEN Node {
637 friend class InequalityGraph;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000638
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000639 typedef SmallVector<Edge, 4> RelationsType;
640 RelationsType Relations;
641
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000642 // TODO: can this idea improve performance?
643 //friend class std::vector<Node>;
644 //Node(Node &N) { RelationsType.swap(N.RelationsType); }
645
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000646 public:
647 typedef RelationsType::iterator iterator;
648 typedef RelationsType::const_iterator const_iterator;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000649
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000650#ifndef NDEBUG
Nick Lewycky5d6ede52007-01-11 02:38:21 +0000651 virtual ~Node() {}
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000652 virtual void dump() const {
653 dump(*cerr.stream());
654 }
655 private:
Nick Lewycky73dd6922007-07-05 03:15:00 +0000656 void dump(std::ostream &os) const {
657 static const std::string names[32] =
658 { "000000", "000001", "000002", "000003", "000004", "000005",
659 "000006", "000007", "000008", "000009", " >", " >=",
660 " s>u<", "s>=u<=", " s>", " s>=", "000016", "000017",
661 " s<u>", "s<=u>=", " <", " <=", " s<", " s<=",
662 "000024", "000025", " u>", " u>=", " u<", " u<=",
663 " !=", "000031" };
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000664 for (Node::const_iterator NI = begin(), NE = end(); NI != NE; ++NI) {
Nick Lewycky73dd6922007-07-05 03:15:00 +0000665 os << names[NI->LV] << " " << NI->To
Nick Lewyckye635cc42007-07-10 03:28:21 +0000666 << " (" << NI->Subtree->getDFSNumIn() << "), ";
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000667 }
668 }
Nick Lewycky73dd6922007-07-05 03:15:00 +0000669 public:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000670#endif
671
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000672 iterator begin() { return Relations.begin(); }
673 iterator end() { return Relations.end(); }
674 const_iterator begin() const { return Relations.begin(); }
675 const_iterator end() const { return Relations.end(); }
676
Nick Lewycky26e25d32007-06-24 04:36:20 +0000677 iterator find(unsigned n, DomTreeDFS::Node *Subtree) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000678 iterator E = end();
679 for (iterator I = std::lower_bound(begin(), E, n);
680 I != E && I->To == n; ++I) {
681 if (Subtree->DominatedBy(I->Subtree))
682 return I;
683 }
684 return E;
685 }
686
Nick Lewycky26e25d32007-06-24 04:36:20 +0000687 const_iterator find(unsigned n, DomTreeDFS::Node *Subtree) const {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000688 const_iterator E = end();
689 for (const_iterator I = std::lower_bound(begin(), E, n);
690 I != E && I->To == n; ++I) {
691 if (Subtree->DominatedBy(I->Subtree))
692 return I;
693 }
694 return E;
695 }
696
Nick Lewycky20f08112007-08-04 18:45:32 +0000697 /// update - updates the lattice value for a given node, creating a new
698 /// entry if one doesn't exist. The new lattice value must not be
699 /// inconsistent with any previously existing value.
Nick Lewycky26e25d32007-06-24 04:36:20 +0000700 void update(unsigned n, LatticeVal R, DomTreeDFS::Node *Subtree) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000701 assert(validPredicate(R) && "Invalid predicate.");
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000702
Nick Lewycky20f08112007-08-04 18:45:32 +0000703 Edge edge(n, R, Subtree);
704 iterator B = begin(), E = end();
705 iterator I = std::lower_bound(B, E, edge);
Nick Lewycky6ce36cf2007-01-15 14:30:07 +0000706
Nick Lewycky20f08112007-08-04 18:45:32 +0000707 iterator J = I;
708 while (J != E && J->To == n) {
709 if (Subtree->DominatedBy(J->Subtree))
710 break;
711 ++J;
712 }
713
714 if (J != E && J->To == n && J->Subtree->dominates(Subtree)) {
715 edge.LV = static_cast<LatticeVal>(J->LV & R);
716 assert(validPredicate(edge.LV) && "Invalid union of lattice values.");
717 if (edge.LV != J->LV) {
718
719 // We have to tighten any edge beneath our update.
720 for (iterator K = I; K->To == n; --K) {
721 if (K->Subtree->DominatedBy(Subtree)) {
722 LatticeVal LV = static_cast<LatticeVal>(K->LV & edge.LV);
Chris Lattner28d921d2007-04-14 23:32:02 +0000723 assert(validPredicate(LV) && "Invalid union of lattice values");
Nick Lewycky20f08112007-08-04 18:45:32 +0000724 K->LV = LV;
Nick Lewycky6ce36cf2007-01-15 14:30:07 +0000725 }
Nick Lewycky20f08112007-08-04 18:45:32 +0000726 if (K == B) break;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000727 }
Nick Lewycky20f08112007-08-04 18:45:32 +0000728
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000729 }
Nick Lewycky51ce8d62006-09-13 19:24:01 +0000730 }
Nick Lewycky20f08112007-08-04 18:45:32 +0000731
732 // Insert new edge at Subtree if it isn't already there.
733 if (I == E || I->To != n || Subtree != I->Subtree)
734 Relations.insert(I, edge);
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000735 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000736 };
737
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000738 private:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000739
740 std::vector<Node> Nodes;
741
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000742 public:
Nick Lewyckye635cc42007-07-10 03:28:21 +0000743 /// node - returns the node object at a given value number. The pointer
744 /// returned may be invalidated on the next call to node().
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000745 Node *node(unsigned index) {
Nick Lewyckye635cc42007-07-10 03:28:21 +0000746 assert(VN.value(index)); // This triggers the necessary checks.
747 if (Nodes.size() < index) Nodes.resize(index);
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000748 return &Nodes[index-1];
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000749 }
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000750
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000751 /// isRelatedBy - true iff n1 op n2
Nick Lewycky26e25d32007-06-24 04:36:20 +0000752 bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
753 LatticeVal LV) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000754 if (n1 == n2) return LV & EQ_BIT;
755
756 Node *N1 = node(n1);
757 Node::iterator I = N1->find(n2, Subtree), E = N1->end();
758 if (I != E) return (I->LV & LV) == I->LV;
759
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000760 return false;
761 }
762
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000763 // The add* methods assume that your input is logically valid and may
764 // assertion-fail or infinitely loop if you attempt a contradiction.
Nick Lewycky9d17c822006-10-25 23:48:24 +0000765
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000766 /// addInequality - Sets n1 op n2.
767 /// It is also an error to call this on an inequality that is already true.
Nick Lewycky26e25d32007-06-24 04:36:20 +0000768 void addInequality(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000769 LatticeVal LV1) {
770 assert(n1 != n2 && "A node can't be inequal to itself.");
771
772 if (LV1 != NE)
773 assert(!isRelatedBy(n1, n2, Subtree, reversePredicate(LV1)) &&
774 "Contradictory inequality.");
775
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000776 // Suppose we're adding %n1 < %n2. Find all the %a < %n1 and
777 // add %a < %n2 too. This keeps the graph fully connected.
778 if (LV1 != NE) {
Nick Lewycky3bb6de82007-04-07 03:36:51 +0000779 // Break up the relationship into signed and unsigned comparison parts.
780 // If the signed parts of %a op1 %n1 match that of %n1 op2 %n2, and
781 // op1 and op2 aren't NE, then add %a op3 %n2. The new relationship
782 // should have the EQ_BIT iff it's set for both op1 and op2.
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000783
784 unsigned LV1_s = LV1 & (SLT_BIT|SGT_BIT);
785 unsigned LV1_u = LV1 & (ULT_BIT|UGT_BIT);
Nick Lewycky3bb6de82007-04-07 03:36:51 +0000786
Nick Lewyckye635cc42007-07-10 03:28:21 +0000787 for (Node::iterator I = node(n1)->begin(), E = node(n1)->end(); I != E; ++I) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000788 if (I->LV != NE && I->To != n2) {
Nick Lewycky3bb6de82007-04-07 03:36:51 +0000789
Nick Lewycky26e25d32007-06-24 04:36:20 +0000790 DomTreeDFS::Node *Local_Subtree = NULL;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000791 if (Subtree->DominatedBy(I->Subtree))
792 Local_Subtree = Subtree;
793 else if (I->Subtree->DominatedBy(Subtree))
794 Local_Subtree = I->Subtree;
795
796 if (Local_Subtree) {
797 unsigned new_relationship = 0;
798 LatticeVal ILV = reversePredicate(I->LV);
799 unsigned ILV_s = ILV & (SLT_BIT|SGT_BIT);
800 unsigned ILV_u = ILV & (ULT_BIT|UGT_BIT);
801
802 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
803 new_relationship |= ILV_s;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000804 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
805 new_relationship |= ILV_u;
806
807 if (new_relationship) {
808 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
809 new_relationship |= (SLT_BIT|SGT_BIT);
810 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
811 new_relationship |= (ULT_BIT|UGT_BIT);
812 if ((LV1 & EQ_BIT) && (ILV & EQ_BIT))
813 new_relationship |= EQ_BIT;
814
815 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
816
817 node(I->To)->update(n2, NewLV, Local_Subtree);
Nick Lewyckye635cc42007-07-10 03:28:21 +0000818 node(n2)->update(I->To, reversePredicate(NewLV), Local_Subtree);
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000819 }
820 }
821 }
822 }
823
Nick Lewyckye635cc42007-07-10 03:28:21 +0000824 for (Node::iterator I = node(n2)->begin(), E = node(n2)->end(); I != E; ++I) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000825 if (I->LV != NE && I->To != n1) {
Nick Lewycky26e25d32007-06-24 04:36:20 +0000826 DomTreeDFS::Node *Local_Subtree = NULL;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000827 if (Subtree->DominatedBy(I->Subtree))
828 Local_Subtree = Subtree;
829 else if (I->Subtree->DominatedBy(Subtree))
830 Local_Subtree = I->Subtree;
831
832 if (Local_Subtree) {
833 unsigned new_relationship = 0;
834 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
835 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
836
837 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
838 new_relationship |= ILV_s;
839
840 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
841 new_relationship |= ILV_u;
842
843 if (new_relationship) {
844 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
845 new_relationship |= (SLT_BIT|SGT_BIT);
846 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
847 new_relationship |= (ULT_BIT|UGT_BIT);
848 if ((LV1 & EQ_BIT) && (I->LV & EQ_BIT))
849 new_relationship |= EQ_BIT;
850
851 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
852
Nick Lewyckye635cc42007-07-10 03:28:21 +0000853 node(n1)->update(I->To, NewLV, Local_Subtree);
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000854 node(I->To)->update(n1, reversePredicate(NewLV), Local_Subtree);
855 }
856 }
857 }
858 }
859 }
860
Nick Lewyckye635cc42007-07-10 03:28:21 +0000861 node(n1)->update(n2, LV1, Subtree);
862 node(n2)->update(n1, reversePredicate(LV1), Subtree);
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000863 }
Nick Lewycky51ce8d62006-09-13 19:24:01 +0000864
Nick Lewycky73dd6922007-07-05 03:15:00 +0000865 /// remove - removes a node from the graph by removing all references to
866 /// and from it.
867 void remove(unsigned n) {
868 Node *N = node(n);
869 for (Node::iterator NI = N->begin(), NE = N->end(); NI != NE; ++NI) {
870 Node::iterator Iter = node(NI->To)->find(n, TreeRoot);
871 do {
872 node(NI->To)->Relations.erase(Iter);
873 Iter = node(NI->To)->find(n, TreeRoot);
874 } while (Iter != node(NI->To)->end());
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000875 }
Nick Lewycky73dd6922007-07-05 03:15:00 +0000876 N->Relations.clear();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000877 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000878
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000879#ifndef NDEBUG
Nick Lewycky5d6ede52007-01-11 02:38:21 +0000880 virtual ~InequalityGraph() {}
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000881 virtual void dump() {
882 dump(*cerr.stream());
883 }
884
885 void dump(std::ostream &os) {
Nick Lewycky73dd6922007-07-05 03:15:00 +0000886 for (unsigned i = 1; i <= Nodes.size(); ++i) {
887 os << i << " = {";
888 node(i)->dump(os);
889 os << "}\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000890 }
891 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000892#endif
893 };
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000894
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000895 class VRPSolver;
896
897 /// ValueRanges tracks the known integer ranges and anti-ranges of the nodes
898 /// in the InequalityGraph.
899 class VISIBILITY_HIDDEN ValueRanges {
Nick Lewyckye635cc42007-07-10 03:28:21 +0000900 ValueNumbering &VN;
901 TargetData *TD;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000902
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000903 class VISIBILITY_HIDDEN ScopedRange {
Nick Lewyckye635cc42007-07-10 03:28:21 +0000904 typedef std::vector<std::pair<DomTreeDFS::Node *, ConstantRange> >
905 RangeListType;
906 RangeListType RangeList;
907
908 static bool swo(const std::pair<DomTreeDFS::Node *, ConstantRange> &LHS,
909 const std::pair<DomTreeDFS::Node *, ConstantRange> &RHS) {
910 return *LHS.first < *RHS.first;
911 }
912
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000913 public:
Nick Lewyckye635cc42007-07-10 03:28:21 +0000914#ifndef NDEBUG
915 virtual ~ScopedRange() {}
916 virtual void dump() const {
917 dump(*cerr.stream());
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000918 }
919
Nick Lewyckye635cc42007-07-10 03:28:21 +0000920 void dump(std::ostream &os) const {
921 os << "{";
922 for (const_iterator I = begin(), E = end(); I != E; ++I) {
923 os << I->second << " (" << I->first->getDFSNumIn() << "), ";
924 }
925 os << "}";
926 }
927#endif
928
929 typedef RangeListType::iterator iterator;
930 typedef RangeListType::const_iterator const_iterator;
931
932 iterator begin() { return RangeList.begin(); }
933 iterator end() { return RangeList.end(); }
934 const_iterator begin() const { return RangeList.begin(); }
935 const_iterator end() const { return RangeList.end(); }
936
937 iterator find(DomTreeDFS::Node *Subtree) {
938 static ConstantRange empty(1, false);
939 iterator E = end();
940 iterator I = std::lower_bound(begin(), E,
941 std::make_pair(Subtree, empty), swo);
942
943 while (I != E && !I->first->dominates(Subtree)) ++I;
944 return I;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000945 }
Bill Wendling6357bf22007-06-04 23:52:59 +0000946
Nick Lewyckye635cc42007-07-10 03:28:21 +0000947 const_iterator find(DomTreeDFS::Node *Subtree) const {
948 static const ConstantRange empty(1, false);
949 const_iterator E = end();
950 const_iterator I = std::lower_bound(begin(), E,
951 std::make_pair(Subtree, empty), swo);
952
953 while (I != E && !I->first->dominates(Subtree)) ++I;
954 return I;
Bill Wendling6357bf22007-06-04 23:52:59 +0000955 }
956
Nick Lewyckye635cc42007-07-10 03:28:21 +0000957 void update(const ConstantRange &CR, DomTreeDFS::Node *Subtree) {
958 assert(!CR.isEmptySet() && "Empty ConstantRange.");
Nick Lewycky20f08112007-08-04 18:45:32 +0000959 assert(!CR.isSingleElement() && "Refusing to store single element.");
Nick Lewyckye635cc42007-07-10 03:28:21 +0000960
961 static ConstantRange empty(1, false);
962 iterator E = end();
963 iterator I =
964 std::lower_bound(begin(), E, std::make_pair(Subtree, empty), swo);
965
966 if (I != end() && I->first == Subtree) {
Nick Lewycky39519f52007-07-14 04:28:04 +0000967 ConstantRange CR2 = I->second.maximalIntersectWith(CR);
Nick Lewyckye635cc42007-07-10 03:28:21 +0000968 assert(!CR2.isEmptySet() && !CR2.isSingleElement() &&
969 "Invalid union of ranges.");
970 I->second = CR2;
971 } else
972 RangeList.insert(I, std::make_pair(Subtree, CR));
Bill Wendling6357bf22007-06-04 23:52:59 +0000973 }
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000974 };
975
976 std::vector<ScopedRange> Ranges;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000977
Nick Lewyckye635cc42007-07-10 03:28:21 +0000978 void update(unsigned n, const ConstantRange &CR, DomTreeDFS::Node *Subtree){
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000979 if (CR.isFullSet()) return;
Nick Lewyckye635cc42007-07-10 03:28:21 +0000980 if (Ranges.size() < n) Ranges.resize(n);
981 Ranges[n-1].update(CR, Subtree);
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000982 }
983
Nick Lewyckye635cc42007-07-10 03:28:21 +0000984 /// create - Creates a ConstantRange that matches the given LatticeVal
985 /// relation with a given integer.
986 ConstantRange create(LatticeVal LV, const ConstantRange &CR) {
987 assert(!CR.isEmptySet() && "Can't deal with empty set.");
988
989 if (LV == NE)
990 return makeConstantRange(ICmpInst::ICMP_NE, CR);
991
992 unsigned LV_s = LV & (SGT_BIT|SLT_BIT);
993 unsigned LV_u = LV & (UGT_BIT|ULT_BIT);
994 bool hasEQ = LV & EQ_BIT;
995
996 ConstantRange Range(CR.getBitWidth());
997
998 if (LV_s == SGT_BIT) {
Nick Lewycky39519f52007-07-14 04:28:04 +0000999 Range = Range.maximalIntersectWith(makeConstantRange(
Nick Lewyckye635cc42007-07-10 03:28:21 +00001000 hasEQ ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_SGT, CR));
1001 } else if (LV_s == SLT_BIT) {
Nick Lewycky39519f52007-07-14 04:28:04 +00001002 Range = Range.maximalIntersectWith(makeConstantRange(
Nick Lewyckye635cc42007-07-10 03:28:21 +00001003 hasEQ ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_SLT, CR));
1004 }
1005
1006 if (LV_u == UGT_BIT) {
Nick Lewycky39519f52007-07-14 04:28:04 +00001007 Range = Range.maximalIntersectWith(makeConstantRange(
Nick Lewyckye635cc42007-07-10 03:28:21 +00001008 hasEQ ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_UGT, CR));
1009 } else if (LV_u == ULT_BIT) {
Nick Lewycky39519f52007-07-14 04:28:04 +00001010 Range = Range.maximalIntersectWith(makeConstantRange(
Nick Lewyckye635cc42007-07-10 03:28:21 +00001011 hasEQ ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT, CR));
1012 }
1013
1014 return Range;
1015 }
1016
1017 /// makeConstantRange - Creates a ConstantRange representing the set of all
1018 /// value that match the ICmpInst::Predicate with any of the values in CR.
1019 ConstantRange makeConstantRange(ICmpInst::Predicate ICmpOpcode,
1020 const ConstantRange &CR) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001021 uint32_t W = CR.getBitWidth();
1022 switch (ICmpOpcode) {
Nick Lewyckye635cc42007-07-10 03:28:21 +00001023 default: assert(!"Invalid ICmp opcode to makeConstantRange()");
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001024 case ICmpInst::ICMP_EQ:
1025 return ConstantRange(CR.getLower(), CR.getUpper());
1026 case ICmpInst::ICMP_NE:
1027 if (CR.isSingleElement())
1028 return ConstantRange(CR.getUpper(), CR.getLower());
1029 return ConstantRange(W);
1030 case ICmpInst::ICMP_ULT:
1031 return ConstantRange(APInt::getMinValue(W), CR.getUnsignedMax());
1032 case ICmpInst::ICMP_SLT:
1033 return ConstantRange(APInt::getSignedMinValue(W), CR.getSignedMax());
1034 case ICmpInst::ICMP_ULE: {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001035 APInt UMax(CR.getUnsignedMax());
Zhou Sheng31787362007-04-26 16:42:07 +00001036 if (UMax.isMaxValue())
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001037 return ConstantRange(W);
1038 return ConstantRange(APInt::getMinValue(W), UMax + 1);
1039 }
1040 case ICmpInst::ICMP_SLE: {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001041 APInt SMax(CR.getSignedMax());
Zhou Sheng31787362007-04-26 16:42:07 +00001042 if (SMax.isMaxSignedValue() || (SMax+1).isMaxSignedValue())
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001043 return ConstantRange(W);
1044 return ConstantRange(APInt::getSignedMinValue(W), SMax + 1);
1045 }
1046 case ICmpInst::ICMP_UGT:
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001047 return ConstantRange(CR.getUnsignedMin() + 1, APInt::getNullValue(W));
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001048 case ICmpInst::ICMP_SGT:
1049 return ConstantRange(CR.getSignedMin() + 1,
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001050 APInt::getSignedMinValue(W));
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001051 case ICmpInst::ICMP_UGE: {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001052 APInt UMin(CR.getUnsignedMin());
Zhou Sheng31787362007-04-26 16:42:07 +00001053 if (UMin.isMinValue())
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001054 return ConstantRange(W);
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001055 return ConstantRange(UMin, APInt::getNullValue(W));
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001056 }
1057 case ICmpInst::ICMP_SGE: {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001058 APInt SMin(CR.getSignedMin());
Zhou Sheng31787362007-04-26 16:42:07 +00001059 if (SMin.isMinSignedValue())
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001060 return ConstantRange(W);
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001061 return ConstantRange(SMin, APInt::getSignedMinValue(W));
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001062 }
1063 }
1064 }
1065
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001066#ifndef NDEBUG
Nick Lewyckye635cc42007-07-10 03:28:21 +00001067 bool isCanonical(Value *V, DomTreeDFS::Node *Subtree) {
1068 return V == VN.canonicalize(V, Subtree);
1069 }
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001070#endif
1071
1072 public:
1073
Nick Lewyckye635cc42007-07-10 03:28:21 +00001074 ValueRanges(ValueNumbering &VN, TargetData *TD) : VN(VN), TD(TD) {}
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001075
Nick Lewyckye635cc42007-07-10 03:28:21 +00001076#ifndef NDEBUG
1077 virtual ~ValueRanges() {}
1078
1079 virtual void dump() const {
1080 dump(*cerr.stream());
1081 }
1082
1083 void dump(std::ostream &os) const {
1084 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1085 os << (i+1) << " = ";
1086 Ranges[i].dump(os);
1087 os << "\n";
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001088 }
Nick Lewyckye635cc42007-07-10 03:28:21 +00001089 }
1090#endif
1091
1092 /// range - looks up the ConstantRange associated with a value number.
1093 ConstantRange range(unsigned n, DomTreeDFS::Node *Subtree) {
1094 assert(VN.value(n)); // performs range checks
1095
1096 if (n <= Ranges.size()) {
1097 ScopedRange::iterator I = Ranges[n-1].find(Subtree);
1098 if (I != Ranges[n-1].end()) return I->second;
1099 }
1100
1101 Value *V = VN.value(n);
1102 ConstantRange CR = range(V);
1103 return CR;
1104 }
1105
1106 /// range - determine a range from a Value without performing any lookups.
1107 ConstantRange range(Value *V) const {
1108 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
1109 return ConstantRange(C->getValue());
1110 else if (isa<ConstantPointerNull>(V))
1111 return ConstantRange(APInt::getNullValue(typeToWidth(V->getType())));
1112 else
1113 return typeToWidth(V->getType());
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001114 }
1115
Nick Lewycky12d44ab2007-04-07 03:16:12 +00001116 // typeToWidth - returns the number of bits necessary to store a value of
1117 // this type, or zero if unknown.
1118 uint32_t typeToWidth(const Type *Ty) const {
1119 if (TD)
1120 return TD->getTypeSizeInBits(Ty);
1121
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001122 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
1123 return ITy->getBitWidth();
1124
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001125 return 0;
1126 }
1127
Nick Lewyckye635cc42007-07-10 03:28:21 +00001128 static bool isRelatedBy(const ConstantRange &CR1, const ConstantRange &CR2,
1129 LatticeVal LV) {
Nick Lewycky4f73de22007-03-16 02:37:39 +00001130 switch (LV) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001131 default: assert(!"Impossible lattice value!");
1132 case NE:
Nick Lewycky39519f52007-07-14 04:28:04 +00001133 return CR1.maximalIntersectWith(CR2).isEmptySet();
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001134 case ULT:
1135 return CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
1136 case ULE:
1137 return CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
1138 case UGT:
1139 return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
1140 case UGE:
1141 return CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
1142 case SLT:
1143 return CR1.getSignedMax().slt(CR2.getSignedMin());
1144 case SLE:
1145 return CR1.getSignedMax().sle(CR2.getSignedMin());
1146 case SGT:
1147 return CR1.getSignedMin().sgt(CR2.getSignedMax());
1148 case SGE:
1149 return CR1.getSignedMin().sge(CR2.getSignedMax());
1150 case LT:
1151 return CR1.getUnsignedMax().ult(CR2.getUnsignedMin()) &&
1152 CR1.getSignedMax().slt(CR2.getUnsignedMin());
1153 case LE:
1154 return CR1.getUnsignedMax().ule(CR2.getUnsignedMin()) &&
1155 CR1.getSignedMax().sle(CR2.getUnsignedMin());
1156 case GT:
1157 return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax()) &&
1158 CR1.getSignedMin().sgt(CR2.getSignedMax());
1159 case GE:
1160 return CR1.getUnsignedMin().uge(CR2.getUnsignedMax()) &&
1161 CR1.getSignedMin().sge(CR2.getSignedMax());
1162 case SLTUGT:
1163 return CR1.getSignedMax().slt(CR2.getSignedMin()) &&
1164 CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
1165 case SLEUGE:
1166 return CR1.getSignedMax().sle(CR2.getSignedMin()) &&
1167 CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
1168 case SGTULT:
1169 return CR1.getSignedMin().sgt(CR2.getSignedMax()) &&
1170 CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
1171 case SGEULE:
1172 return CR1.getSignedMin().sge(CR2.getSignedMax()) &&
1173 CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
1174 }
1175 }
1176
Nick Lewyckye635cc42007-07-10 03:28:21 +00001177 bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
1178 LatticeVal LV) {
1179 ConstantRange CR1 = range(n1, Subtree);
1180 ConstantRange CR2 = range(n2, Subtree);
1181
1182 // True iff all values in CR1 are LV to all values in CR2.
1183 return isRelatedBy(CR1, CR2, LV);
1184 }
1185
Nick Lewycky3bb6de82007-04-07 03:36:51 +00001186 void addToWorklist(Value *V, Constant *C, ICmpInst::Predicate Pred,
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001187 VRPSolver *VRP);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001188 void markBlock(VRPSolver *VRP);
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001189
Nick Lewyckye635cc42007-07-10 03:28:21 +00001190 void mergeInto(Value **I, unsigned n, unsigned New,
Nick Lewycky26e25d32007-06-24 04:36:20 +00001191 DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
Nick Lewyckye635cc42007-07-10 03:28:21 +00001192 ConstantRange CR_New = range(New, Subtree);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001193 ConstantRange Merged = CR_New;
1194
1195 for (; n != 0; ++I, --n) {
Nick Lewyckye635cc42007-07-10 03:28:21 +00001196 unsigned i = VN.valueNumber(*I, Subtree);
1197 ConstantRange CR_Kill = i ? range(i, Subtree) : range(*I);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001198 if (CR_Kill.isFullSet()) continue;
Nick Lewycky39519f52007-07-14 04:28:04 +00001199 Merged = Merged.maximalIntersectWith(CR_Kill);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001200 }
1201
1202 if (Merged.isFullSet() || Merged == CR_New) return;
1203
Nick Lewycky3bb6de82007-04-07 03:36:51 +00001204 applyRange(New, Merged, Subtree, VRP);
1205 }
1206
Nick Lewyckye635cc42007-07-10 03:28:21 +00001207 void applyRange(unsigned n, const ConstantRange &CR,
Nick Lewycky26e25d32007-06-24 04:36:20 +00001208 DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
Nick Lewycky39519f52007-07-14 04:28:04 +00001209 ConstantRange Merged = CR.maximalIntersectWith(range(n, Subtree));
Nick Lewyckye635cc42007-07-10 03:28:21 +00001210 if (Merged.isEmptySet()) {
1211 markBlock(VRP);
1212 return;
1213 }
Nick Lewycky3bb6de82007-04-07 03:36:51 +00001214
Nick Lewyckye635cc42007-07-10 03:28:21 +00001215 if (const APInt *I = Merged.getSingleElement()) {
1216 Value *V = VN.value(n); // XXX: redesign worklist.
Nick Lewycky3bb6de82007-04-07 03:36:51 +00001217 const Type *Ty = V->getType();
1218 if (Ty->isInteger()) {
1219 addToWorklist(V, ConstantInt::get(*I), ICmpInst::ICMP_EQ, VRP);
1220 return;
1221 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1222 assert(*I == 0 && "Pointer is null but not zero?");
1223 addToWorklist(V, ConstantPointerNull::get(PTy),
Nick Lewyckye635cc42007-07-10 03:28:21 +00001224 ICmpInst::ICMP_EQ, VRP);
Nick Lewycky3bb6de82007-04-07 03:36:51 +00001225 return;
1226 }
1227 }
1228
Nick Lewyckye635cc42007-07-10 03:28:21 +00001229 update(n, Merged, Subtree);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001230 }
1231
Nick Lewyckye635cc42007-07-10 03:28:21 +00001232 void addNotEquals(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
Nick Lewycky26e25d32007-06-24 04:36:20 +00001233 VRPSolver *VRP) {
Nick Lewyckye635cc42007-07-10 03:28:21 +00001234 ConstantRange CR1 = range(n1, Subtree);
1235 ConstantRange CR2 = range(n2, Subtree);
Nick Lewycky93f54102007-04-07 04:49:12 +00001236
Nick Lewyckye635cc42007-07-10 03:28:21 +00001237 uint32_t W = CR1.getBitWidth();
Nick Lewycky93f54102007-04-07 04:49:12 +00001238
1239 if (const APInt *I = CR1.getSingleElement()) {
1240 if (CR2.isFullSet()) {
1241 ConstantRange NewCR2(CR1.getUpper(), CR1.getLower());
Nick Lewyckye635cc42007-07-10 03:28:21 +00001242 applyRange(n2, NewCR2, Subtree, VRP);
Nick Lewycky93f54102007-04-07 04:49:12 +00001243 } else if (*I == CR2.getLower()) {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001244 APInt NewLower(CR2.getLower() + 1),
1245 NewUpper(CR2.getUpper());
Nick Lewycky93f54102007-04-07 04:49:12 +00001246 if (NewLower == NewUpper)
1247 NewLower = NewUpper = APInt::getMinValue(W);
1248
1249 ConstantRange NewCR2(NewLower, NewUpper);
Nick Lewyckye635cc42007-07-10 03:28:21 +00001250 applyRange(n2, NewCR2, Subtree, VRP);
Nick Lewycky93f54102007-04-07 04:49:12 +00001251 } else if (*I == CR2.getUpper() - 1) {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001252 APInt NewLower(CR2.getLower()),
1253 NewUpper(CR2.getUpper() - 1);
Nick Lewycky93f54102007-04-07 04:49:12 +00001254 if (NewLower == NewUpper)
1255 NewLower = NewUpper = APInt::getMinValue(W);
1256
1257 ConstantRange NewCR2(NewLower, NewUpper);
Nick Lewyckye635cc42007-07-10 03:28:21 +00001258 applyRange(n2, NewCR2, Subtree, VRP);
Nick Lewycky93f54102007-04-07 04:49:12 +00001259 }
1260 }
1261
1262 if (const APInt *I = CR2.getSingleElement()) {
1263 if (CR1.isFullSet()) {
1264 ConstantRange NewCR1(CR2.getUpper(), CR2.getLower());
Nick Lewyckye635cc42007-07-10 03:28:21 +00001265 applyRange(n1, NewCR1, Subtree, VRP);
Nick Lewycky93f54102007-04-07 04:49:12 +00001266 } else if (*I == CR1.getLower()) {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001267 APInt NewLower(CR1.getLower() + 1),
1268 NewUpper(CR1.getUpper());
Nick Lewycky93f54102007-04-07 04:49:12 +00001269 if (NewLower == NewUpper)
1270 NewLower = NewUpper = APInt::getMinValue(W);
1271
1272 ConstantRange NewCR1(NewLower, NewUpper);
Nick Lewyckye635cc42007-07-10 03:28:21 +00001273 applyRange(n1, NewCR1, Subtree, VRP);
Nick Lewycky93f54102007-04-07 04:49:12 +00001274 } else if (*I == CR1.getUpper() - 1) {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001275 APInt NewLower(CR1.getLower()),
1276 NewUpper(CR1.getUpper() - 1);
Nick Lewycky93f54102007-04-07 04:49:12 +00001277 if (NewLower == NewUpper)
1278 NewLower = NewUpper = APInt::getMinValue(W);
1279
1280 ConstantRange NewCR1(NewLower, NewUpper);
Nick Lewyckye635cc42007-07-10 03:28:21 +00001281 applyRange(n1, NewCR1, Subtree, VRP);
Nick Lewycky93f54102007-04-07 04:49:12 +00001282 }
1283 }
1284 }
1285
Nick Lewyckye635cc42007-07-10 03:28:21 +00001286 void addInequality(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
Nick Lewycky26e25d32007-06-24 04:36:20 +00001287 LatticeVal LV, VRPSolver *VRP) {
Nick Lewyckye635cc42007-07-10 03:28:21 +00001288 assert(!isRelatedBy(n1, n2, Subtree, LV) && "Asked to do useless work.");
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001289
Nick Lewycky93f54102007-04-07 04:49:12 +00001290 if (LV == NE) {
Nick Lewyckye635cc42007-07-10 03:28:21 +00001291 addNotEquals(n1, n2, Subtree, VRP);
Nick Lewycky93f54102007-04-07 04:49:12 +00001292 return;
1293 }
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001294
Nick Lewyckye635cc42007-07-10 03:28:21 +00001295 ConstantRange CR1 = range(n1, Subtree);
1296 ConstantRange CR2 = range(n2, Subtree);
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001297
1298 if (!CR1.isSingleElement()) {
Nick Lewycky39519f52007-07-14 04:28:04 +00001299 ConstantRange NewCR1 = CR1.maximalIntersectWith(create(LV, CR2));
Nick Lewycky3bb6de82007-04-07 03:36:51 +00001300 if (NewCR1 != CR1)
Nick Lewyckye635cc42007-07-10 03:28:21 +00001301 applyRange(n1, NewCR1, Subtree, VRP);
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001302 }
1303
1304 if (!CR2.isSingleElement()) {
Nick Lewycky39519f52007-07-14 04:28:04 +00001305 ConstantRange NewCR2 = CR2.maximalIntersectWith(
1306 create(reversePredicate(LV), CR1));
Nick Lewycky3bb6de82007-04-07 03:36:51 +00001307 if (NewCR2 != CR2)
Nick Lewyckye635cc42007-07-10 03:28:21 +00001308 applyRange(n2, NewCR2, Subtree, VRP);
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001309 }
1310 }
1311 };
1312
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001313 /// UnreachableBlocks keeps tracks of blocks that are for one reason or
1314 /// another discovered to be unreachable. This is used to cull the graph when
1315 /// analyzing instructions, and to mark blocks with the "unreachable"
1316 /// terminator instruction after the function has executed.
1317 class VISIBILITY_HIDDEN UnreachableBlocks {
1318 private:
1319 std::vector<BasicBlock *> DeadBlocks;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001320
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001321 public:
1322 /// mark - mark a block as dead
1323 void mark(BasicBlock *BB) {
1324 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
1325 std::vector<BasicBlock *>::iterator I =
1326 std::lower_bound(DeadBlocks.begin(), E, BB);
1327
1328 if (I == E || *I != BB) DeadBlocks.insert(I, BB);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001329 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001330
1331 /// isDead - returns whether a block is known to be dead already
1332 bool isDead(BasicBlock *BB) {
1333 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
1334 std::vector<BasicBlock *>::iterator I =
1335 std::lower_bound(DeadBlocks.begin(), E, BB);
1336
1337 return I != E && *I == BB;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001338 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001339
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001340 /// kill - replace the dead blocks' terminator with an UnreachableInst.
1341 bool kill() {
1342 bool modified = false;
1343 for (std::vector<BasicBlock *>::iterator I = DeadBlocks.begin(),
1344 E = DeadBlocks.end(); I != E; ++I) {
1345 BasicBlock *BB = *I;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001346
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001347 DOUT << "unreachable block: " << BB->getName() << "\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001348
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001349 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
1350 SI != SE; ++SI) {
1351 BasicBlock *Succ = *SI;
1352 Succ->removePredecessor(BB);
Nick Lewycky9d17c822006-10-25 23:48:24 +00001353 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001354
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001355 TerminatorInst *TI = BB->getTerminator();
1356 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1357 TI->eraseFromParent();
1358 new UnreachableInst(BB);
1359 ++NumBlocks;
1360 modified = true;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001361 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001362 DeadBlocks.clear();
1363 return modified;
Nick Lewycky9d17c822006-10-25 23:48:24 +00001364 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001365 };
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001366
1367 /// VRPSolver keeps track of how changes to one variable affect other
1368 /// variables, and forwards changes along to the InequalityGraph. It
1369 /// also maintains the correct choice for "canonical" in the IG.
1370 /// @brief VRPSolver calculates inferences from a new relationship.
1371 class VISIBILITY_HIDDEN VRPSolver {
1372 private:
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001373 friend class ValueRanges;
1374
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001375 struct Operation {
1376 Value *LHS, *RHS;
1377 ICmpInst::Predicate Op;
1378
Nick Lewycky26e25d32007-06-24 04:36:20 +00001379 BasicBlock *ContextBB; // XXX use a DomTreeDFS::Node instead
Nick Lewycky42944462007-01-13 02:05:28 +00001380 Instruction *ContextInst;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001381 };
1382 std::deque<Operation> WorkList;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001383
Nick Lewycky73dd6922007-07-05 03:15:00 +00001384 ValueNumbering &VN;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001385 InequalityGraph &IG;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001386 UnreachableBlocks &UB;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001387 ValueRanges &VR;
Nick Lewycky26e25d32007-06-24 04:36:20 +00001388 DomTreeDFS *DTDFS;
1389 DomTreeDFS::Node *Top;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001390 BasicBlock *TopBB;
1391 Instruction *TopInst;
1392 bool &modified;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001393
1394 typedef InequalityGraph::Node Node;
1395
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001396 // below - true if the Instruction is dominated by the current context
1397 // block or instruction
1398 bool below(Instruction *I) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00001399 BasicBlock *BB = I->getParent();
1400 if (TopInst && TopInst->getParent() == BB) {
1401 if (isa<TerminatorInst>(TopInst)) return false;
1402 if (isa<TerminatorInst>(I)) return true;
1403 if ( isa<PHINode>(TopInst) && !isa<PHINode>(I)) return true;
1404 if (!isa<PHINode>(TopInst) && isa<PHINode>(I)) return false;
1405
1406 for (BasicBlock::const_iterator Iter = BB->begin(), E = BB->end();
1407 Iter != E; ++Iter) {
1408 if (&*Iter == TopInst) return true;
1409 else if (&*Iter == I) return false;
1410 }
1411 assert(!"Instructions not found in parent BasicBlock?");
1412 } else {
Nick Lewycky0f986fd2007-06-24 04:40:16 +00001413 DomTreeDFS::Node *Node = DTDFS->getNodeForBlock(BB);
Nick Lewycky26e25d32007-06-24 04:36:20 +00001414 if (!Node) return false;
1415 return Top->dominates(Node);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001416 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001417 }
1418
Nick Lewycky26e25d32007-06-24 04:36:20 +00001419 // aboveOrBelow - true if the Instruction either dominates or is dominated
1420 // by the current context block or instruction
1421 bool aboveOrBelow(Instruction *I) {
1422 BasicBlock *BB = I->getParent();
1423 DomTreeDFS::Node *Node = DTDFS->getNodeForBlock(BB);
1424 if (!Node) return false;
1425
1426 return Top == Node || Top->dominates(Node) || Node->dominates(Top);
1427 }
1428
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001429 bool makeEqual(Value *V1, Value *V2) {
1430 DOUT << "makeEqual(" << *V1 << ", " << *V2 << ")\n";
Nick Lewycky26e25d32007-06-24 04:36:20 +00001431 DOUT << "context is ";
1432 if (TopInst) DOUT << "I: " << *TopInst << "\n";
1433 else DOUT << "BB: " << TopBB->getName()
1434 << "(" << Top->getDFSNumIn() << ")\n";
Nick Lewycky9d17c822006-10-25 23:48:24 +00001435
Nick Lewycky12d44ab2007-04-07 03:16:12 +00001436 assert(V1->getType() == V2->getType() &&
1437 "Can't make two values with different types equal.");
1438
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001439 if (V1 == V2) return true;
Nick Lewycky9d17c822006-10-25 23:48:24 +00001440
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001441 if (isa<Constant>(V1) && isa<Constant>(V2))
1442 return false;
1443
Nick Lewycky73dd6922007-07-05 03:15:00 +00001444 unsigned n1 = VN.valueNumber(V1, Top), n2 = VN.valueNumber(V2, Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001445
1446 if (n1 && n2) {
1447 if (n1 == n2) return true;
1448 if (IG.isRelatedBy(n1, n2, Top, NE)) return false;
1449 }
1450
Nick Lewycky73dd6922007-07-05 03:15:00 +00001451 if (n1) assert(V1 == VN.value(n1) && "Value isn't canonical.");
1452 if (n2) assert(V2 == VN.value(n2) && "Value isn't canonical.");
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001453
Nick Lewycky73dd6922007-07-05 03:15:00 +00001454 assert(!VN.compare(V2, V1) && "Please order parameters to makeEqual.");
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001455
1456 assert(!isa<Constant>(V2) && "Tried to remove a constant.");
1457
1458 SetVector<unsigned> Remove;
1459 if (n2) Remove.insert(n2);
1460
1461 if (n1 && n2) {
1462 // Suppose we're being told that %x == %y, and %x <= %z and %y >= %z.
1463 // We can't just merge %x and %y because the relationship with %z would
1464 // be EQ and that's invalid. What we're doing is looking for any nodes
1465 // %z such that %x <= %z and %y >= %z, and vice versa.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001466
Nick Lewyckye635cc42007-07-10 03:28:21 +00001467 Node::iterator end = IG.node(n2)->end();
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001468
1469 // Find the intersection between N1 and N2 which is dominated by
1470 // Top. If we find %x where N1 <= %x <= N2 (or >=) then add %x to
1471 // Remove.
Nick Lewyckye635cc42007-07-10 03:28:21 +00001472 for (Node::iterator I = IG.node(n1)->begin(), E = IG.node(n1)->end();
1473 I != E; ++I) {
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001474 if (!(I->LV & EQ_BIT) || !Top->DominatedBy(I->Subtree)) continue;
1475
1476 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
1477 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
Nick Lewyckye635cc42007-07-10 03:28:21 +00001478 Node::iterator NI = IG.node(n2)->find(I->To, Top);
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001479 if (NI != end) {
1480 LatticeVal NILV = reversePredicate(NI->LV);
1481 unsigned NILV_s = NILV & (SLT_BIT|SGT_BIT);
1482 unsigned NILV_u = NILV & (ULT_BIT|UGT_BIT);
1483
1484 if ((ILV_s != (SLT_BIT|SGT_BIT) && ILV_s == NILV_s) ||
1485 (ILV_u != (ULT_BIT|UGT_BIT) && ILV_u == NILV_u))
1486 Remove.insert(I->To);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001487 }
1488 }
1489
1490 // See if one of the nodes about to be removed is actually a better
1491 // canonical choice than n1.
1492 unsigned orig_n1 = n1;
Reid Spencera8a15472007-01-17 02:23:37 +00001493 SetVector<unsigned>::iterator DontRemove = Remove.end();
1494 for (SetVector<unsigned>::iterator I = Remove.begin()+1 /* skip n2 */,
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001495 E = Remove.end(); I != E; ++I) {
1496 unsigned n = *I;
Nick Lewycky73dd6922007-07-05 03:15:00 +00001497 Value *V = VN.value(n);
1498 if (VN.compare(V, V1)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001499 V1 = V;
1500 n1 = n;
1501 DontRemove = I;
1502 }
1503 }
1504 if (DontRemove != Remove.end()) {
1505 unsigned n = *DontRemove;
1506 Remove.remove(n);
1507 Remove.insert(orig_n1);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001508 }
1509 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001510
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001511 // We'd like to allow makeEqual on two values to perform a simple
1512 // substitution without every creating nodes in the IG whenever possible.
1513 //
1514 // The first iteration through this loop operates on V2 before going
1515 // through the Remove list and operating on those too. If all of the
1516 // iterations performed simple replacements then we exit early.
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001517 bool mergeIGNode = false;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001518 unsigned i = 0;
1519 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00001520 if (i) R = VN.value(Remove[i]); // skip n2.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001521
1522 // Try to replace the whole instruction. If we can, we're done.
1523 Instruction *I2 = dyn_cast<Instruction>(R);
1524 if (I2 && below(I2)) {
1525 std::vector<Instruction *> ToNotify;
1526 for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
1527 UI != UE;) {
1528 Use &TheUse = UI.getUse();
1529 ++UI;
1530 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser()))
1531 ToNotify.push_back(I);
1532 }
1533
1534 DOUT << "Simply removing " << *I2
1535 << ", replacing with " << *V1 << "\n";
1536 I2->replaceAllUsesWith(V1);
1537 // leave it dead; it'll get erased later.
1538 ++NumInstruction;
1539 modified = true;
1540
1541 for (std::vector<Instruction *>::iterator II = ToNotify.begin(),
1542 IE = ToNotify.end(); II != IE; ++II) {
1543 opsToDef(*II);
1544 }
1545
1546 continue;
1547 }
1548
1549 // Otherwise, replace all dominated uses.
1550 for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
1551 UI != UE;) {
1552 Use &TheUse = UI.getUse();
1553 ++UI;
1554 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
1555 if (below(I)) {
1556 TheUse.set(V1);
1557 modified = true;
1558 ++NumVarsReplaced;
1559 opsToDef(I);
1560 }
1561 }
1562 }
1563
1564 // If that killed the instruction, stop here.
1565 if (I2 && isInstructionTriviallyDead(I2)) {
1566 DOUT << "Killed all uses of " << *I2
1567 << ", replacing with " << *V1 << "\n";
1568 continue;
1569 }
1570
1571 // If we make it to here, then we will need to create a node for N1.
1572 // Otherwise, we can skip out early!
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001573 mergeIGNode = true;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001574 }
1575
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001576 if (!isa<Constant>(V1)) {
1577 if (Remove.empty()) {
Nick Lewyckye635cc42007-07-10 03:28:21 +00001578 VR.mergeInto(&V2, 1, VN.getOrInsertVN(V1, Top), Top, this);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001579 } else {
1580 std::vector<Value*> RemoveVals;
1581 RemoveVals.reserve(Remove.size());
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001582
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001583 for (SetVector<unsigned>::iterator I = Remove.begin(),
1584 E = Remove.end(); I != E; ++I) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00001585 Value *V = VN.value(*I);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001586 if (!V->use_empty())
1587 RemoveVals.push_back(V);
1588 }
Nick Lewyckye635cc42007-07-10 03:28:21 +00001589 VR.mergeInto(&RemoveVals[0], RemoveVals.size(),
1590 VN.getOrInsertVN(V1, Top), Top, this);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001591 }
1592 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001593
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001594 if (mergeIGNode) {
1595 // Create N1.
Nick Lewyckye635cc42007-07-10 03:28:21 +00001596 if (!n1) n1 = VN.getOrInsertVN(V1, Top);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001597
1598 // Migrate relationships from removed nodes to N1.
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001599 for (SetVector<unsigned>::iterator I = Remove.begin(), E = Remove.end();
1600 I != E; ++I) {
1601 unsigned n = *I;
Nick Lewyckye635cc42007-07-10 03:28:21 +00001602 for (Node::iterator NI = IG.node(n)->begin(), NE = IG.node(n)->end();
1603 NI != NE; ++NI) {
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001604 if (NI->Subtree->DominatedBy(Top)) {
1605 if (NI->To == n1) {
1606 assert((NI->LV & EQ_BIT) && "Node inequal to itself.");
1607 continue;
1608 }
1609 if (Remove.count(NI->To))
1610 continue;
1611
1612 IG.node(NI->To)->update(n1, reversePredicate(NI->LV), Top);
Nick Lewyckye635cc42007-07-10 03:28:21 +00001613 IG.node(n1)->update(NI->To, NI->LV, Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001614 }
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001615 }
1616 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001617
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001618 // Point V2 (and all items in Remove) to N1.
1619 if (!n2)
Nick Lewycky73dd6922007-07-05 03:15:00 +00001620 VN.addEquality(n1, V2, Top);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001621 else {
1622 for (SetVector<unsigned>::iterator I = Remove.begin(),
1623 E = Remove.end(); I != E; ++I) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00001624 VN.addEquality(n1, VN.value(*I), Top);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001625 }
1626 }
1627
1628 // If !Remove.empty() then V2 = Remove[0]->getValue().
1629 // Even when Remove is empty, we still want to process V2.
1630 i = 0;
1631 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00001632 if (i) R = VN.value(Remove[i]); // skip n2.
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001633
1634 if (Instruction *I2 = dyn_cast<Instruction>(R)) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00001635 if (aboveOrBelow(I2))
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001636 defToOps(I2);
1637 }
1638 for (Value::use_iterator UI = V2->use_begin(), UE = V2->use_end();
1639 UI != UE;) {
1640 Use &TheUse = UI.getUse();
1641 ++UI;
1642 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00001643 if (aboveOrBelow(I))
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001644 opsToDef(I);
1645 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001646 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001647 }
1648 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001649
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001650 // re-opsToDef all dominated users of V1.
1651 if (Instruction *I = dyn_cast<Instruction>(V1)) {
1652 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001653 UI != UE;) {
1654 Use &TheUse = UI.getUse();
1655 ++UI;
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001656 Value *V = TheUse.getUser();
1657 if (!V->use_empty()) {
1658 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00001659 if (aboveOrBelow(Inst))
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001660 opsToDef(Inst);
1661 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001662 }
1663 }
1664 }
1665
1666 return true;
1667 }
1668
1669 /// cmpInstToLattice - converts an CmpInst::Predicate to lattice value
1670 /// Requires that the lattice value be valid; does not accept ICMP_EQ.
1671 static LatticeVal cmpInstToLattice(ICmpInst::Predicate Pred) {
1672 switch (Pred) {
1673 case ICmpInst::ICMP_EQ:
1674 assert(!"No matching lattice value.");
1675 return static_cast<LatticeVal>(EQ_BIT);
1676 default:
1677 assert(!"Invalid 'icmp' predicate.");
1678 case ICmpInst::ICMP_NE:
1679 return NE;
1680 case ICmpInst::ICMP_UGT:
Nick Lewycky56639802007-01-29 02:56:54 +00001681 return UGT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001682 case ICmpInst::ICMP_UGE:
Nick Lewycky56639802007-01-29 02:56:54 +00001683 return UGE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001684 case ICmpInst::ICMP_ULT:
Nick Lewycky56639802007-01-29 02:56:54 +00001685 return ULT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001686 case ICmpInst::ICMP_ULE:
Nick Lewycky56639802007-01-29 02:56:54 +00001687 return ULE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001688 case ICmpInst::ICMP_SGT:
Nick Lewycky56639802007-01-29 02:56:54 +00001689 return SGT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001690 case ICmpInst::ICMP_SGE:
Nick Lewycky56639802007-01-29 02:56:54 +00001691 return SGE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001692 case ICmpInst::ICMP_SLT:
Nick Lewycky56639802007-01-29 02:56:54 +00001693 return SLT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001694 case ICmpInst::ICMP_SLE:
Nick Lewycky56639802007-01-29 02:56:54 +00001695 return SLE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001696 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001697 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001698
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001699 public:
Nick Lewycky73dd6922007-07-05 03:15:00 +00001700 VRPSolver(ValueNumbering &VN, InequalityGraph &IG, UnreachableBlocks &UB,
1701 ValueRanges &VR, DomTreeDFS *DTDFS, bool &modified,
1702 BasicBlock *TopBB)
1703 : VN(VN),
1704 IG(IG),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001705 UB(UB),
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001706 VR(VR),
Nick Lewycky26e25d32007-06-24 04:36:20 +00001707 DTDFS(DTDFS),
1708 Top(DTDFS->getNodeForBlock(TopBB)),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001709 TopBB(TopBB),
1710 TopInst(NULL),
Nick Lewycky26e25d32007-06-24 04:36:20 +00001711 modified(modified)
1712 {
1713 assert(Top && "VRPSolver created for unreachable basic block.");
1714 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001715
Nick Lewycky73dd6922007-07-05 03:15:00 +00001716 VRPSolver(ValueNumbering &VN, InequalityGraph &IG, UnreachableBlocks &UB,
1717 ValueRanges &VR, DomTreeDFS *DTDFS, bool &modified,
1718 Instruction *TopInst)
1719 : VN(VN),
1720 IG(IG),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001721 UB(UB),
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001722 VR(VR),
Nick Lewycky26e25d32007-06-24 04:36:20 +00001723 DTDFS(DTDFS),
1724 Top(DTDFS->getNodeForBlock(TopInst->getParent())),
1725 TopBB(TopInst->getParent()),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001726 TopInst(TopInst),
1727 modified(modified)
1728 {
Nick Lewycky26e25d32007-06-24 04:36:20 +00001729 assert(Top && "VRPSolver created for unreachable basic block.");
1730 assert(Top->getBlock() == TopInst->getParent() && "Context mismatch.");
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001731 }
1732
1733 bool isRelatedBy(Value *V1, Value *V2, ICmpInst::Predicate Pred) const {
1734 if (Constant *C1 = dyn_cast<Constant>(V1))
1735 if (Constant *C2 = dyn_cast<Constant>(V2))
1736 return ConstantExpr::getCompare(Pred, C1, C2) ==
Zhou Sheng75b871f2007-01-11 12:24:14 +00001737 ConstantInt::getTrue();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001738
Nick Lewyckye635cc42007-07-10 03:28:21 +00001739 unsigned n1 = VN.valueNumber(V1, Top);
1740 unsigned n2 = VN.valueNumber(V2, Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001741
Nick Lewyckye635cc42007-07-10 03:28:21 +00001742 if (n1 && n2) {
1743 if (n1 == n2) return Pred == ICmpInst::ICMP_EQ ||
1744 Pred == ICmpInst::ICMP_ULE ||
1745 Pred == ICmpInst::ICMP_UGE ||
1746 Pred == ICmpInst::ICMP_SLE ||
1747 Pred == ICmpInst::ICMP_SGE;
1748 if (Pred == ICmpInst::ICMP_EQ) return false;
1749 if (IG.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
1750 if (VR.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
1751 }
1752
1753 if ((n1 && !n2 && isa<Constant>(V2)) ||
1754 (n2 && !n1 && isa<Constant>(V1))) {
1755 ConstantRange CR1 = n1 ? VR.range(n1, Top) : VR.range(V1);
1756 ConstantRange CR2 = n2 ? VR.range(n2, Top) : VR.range(V2);
1757
1758 if (Pred == ICmpInst::ICMP_EQ)
1759 return CR1.isSingleElement() &&
1760 CR1.getSingleElement() == CR2.getSingleElement();
1761
1762 return VR.isRelatedBy(CR1, CR2, cmpInstToLattice(Pred));
1763 }
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001764 if (Pred == ICmpInst::ICMP_EQ) return V1 == V2;
Nick Lewyckye635cc42007-07-10 03:28:21 +00001765 return false;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001766 }
1767
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001768 /// add - adds a new property to the work queue
1769 void add(Value *V1, Value *V2, ICmpInst::Predicate Pred,
1770 Instruction *I = NULL) {
1771 DOUT << "adding " << *V1 << " " << Pred << " " << *V2;
1772 if (I) DOUT << " context: " << *I;
Nick Lewycky26e25d32007-06-24 04:36:20 +00001773 else DOUT << " default context (" << Top->getDFSNumIn() << ")";
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001774 DOUT << "\n";
1775
Nick Lewycky12d44ab2007-04-07 03:16:12 +00001776 assert(V1->getType() == V2->getType() &&
1777 "Can't relate two values with different types.");
1778
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001779 WorkList.push_back(Operation());
1780 Operation &O = WorkList.back();
Nick Lewycky42944462007-01-13 02:05:28 +00001781 O.LHS = V1, O.RHS = V2, O.Op = Pred, O.ContextInst = I;
1782 O.ContextBB = I ? I->getParent() : TopBB;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001783 }
1784
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001785 /// defToOps - Given an instruction definition that we've learned something
1786 /// new about, find any new relationships between its operands.
1787 void defToOps(Instruction *I) {
1788 Instruction *NewContext = below(I) ? I : TopInst;
Nick Lewycky73dd6922007-07-05 03:15:00 +00001789 Value *Canonical = VN.canonicalize(I, Top);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001790
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001791 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1792 const Type *Ty = BO->getType();
1793 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001794
Nick Lewycky73dd6922007-07-05 03:15:00 +00001795 Value *Op0 = VN.canonicalize(BO->getOperand(0), Top);
1796 Value *Op1 = VN.canonicalize(BO->getOperand(1), Top);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001797
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001798 // TODO: "and i32 -1, %x" EQ %y then %x EQ %y.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001799
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001800 switch (BO->getOpcode()) {
1801 case Instruction::And: {
Nick Lewycky4f73de22007-03-16 02:37:39 +00001802 // "and i32 %a, %b" EQ -1 then %a EQ -1 and %b EQ -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00001803 ConstantInt *CI = ConstantInt::getAllOnesValue(Ty);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001804 if (Canonical == CI) {
1805 add(CI, Op0, ICmpInst::ICMP_EQ, NewContext);
1806 add(CI, Op1, ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001807 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001808 } break;
1809 case Instruction::Or: {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001810 // "or i32 %a, %b" EQ 0 then %a EQ 0 and %b EQ 0
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001811 Constant *Zero = Constant::getNullValue(Ty);
1812 if (Canonical == Zero) {
1813 add(Zero, Op0, ICmpInst::ICMP_EQ, NewContext);
1814 add(Zero, Op1, ICmpInst::ICMP_EQ, NewContext);
1815 }
1816 } break;
1817 case Instruction::Xor: {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001818 // "xor i32 %c, %a" EQ %b then %a EQ %c ^ %b
1819 // "xor i32 %c, %a" EQ %c then %a EQ 0
1820 // "xor i32 %c, %a" NE %c then %a NE 0
1821 // Repeat the above, with order of operands reversed.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001822 Value *LHS = Op0;
1823 Value *RHS = Op1;
1824 if (!isa<Constant>(LHS)) std::swap(LHS, RHS);
1825
Nick Lewycky4a74a752007-01-12 00:02:12 +00001826 if (ConstantInt *CI = dyn_cast<ConstantInt>(Canonical)) {
1827 if (ConstantInt *Arg = dyn_cast<ConstantInt>(LHS)) {
Reid Spencerc34dedf2007-03-03 00:48:31 +00001828 add(RHS, ConstantInt::get(CI->getValue() ^ Arg->getValue()),
Nick Lewycky4a74a752007-01-12 00:02:12 +00001829 ICmpInst::ICMP_EQ, NewContext);
1830 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001831 }
1832 if (Canonical == LHS) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001833 if (isa<ConstantInt>(Canonical))
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001834 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_EQ,
1835 NewContext);
1836 } else if (isRelatedBy(LHS, Canonical, ICmpInst::ICMP_NE)) {
1837 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_NE,
1838 NewContext);
1839 }
1840 } break;
1841 default:
1842 break;
1843 }
1844 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001845 // "icmp ult i32 %a, %y" EQ true then %a u< y
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001846 // etc.
1847
Zhou Sheng75b871f2007-01-11 12:24:14 +00001848 if (Canonical == ConstantInt::getTrue()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001849 add(IC->getOperand(0), IC->getOperand(1), IC->getPredicate(),
1850 NewContext);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001851 } else if (Canonical == ConstantInt::getFalse()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001852 add(IC->getOperand(0), IC->getOperand(1),
1853 ICmpInst::getInversePredicate(IC->getPredicate()), NewContext);
1854 }
1855 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
1856 if (I->getType()->isFPOrFPVector()) return;
1857
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001858 // Given: "%a = select i1 %x, i32 %b, i32 %c"
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001859 // %a EQ %b and %b NE %c then %x EQ true
1860 // %a EQ %c and %b NE %c then %x EQ false
1861
1862 Value *True = SI->getTrueValue();
1863 Value *False = SI->getFalseValue();
1864 if (isRelatedBy(True, False, ICmpInst::ICMP_NE)) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00001865 if (Canonical == VN.canonicalize(True, Top) ||
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001866 isRelatedBy(Canonical, False, ICmpInst::ICMP_NE))
Zhou Sheng75b871f2007-01-11 12:24:14 +00001867 add(SI->getCondition(), ConstantInt::getTrue(),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001868 ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky73dd6922007-07-05 03:15:00 +00001869 else if (Canonical == VN.canonicalize(False, Top) ||
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001870 isRelatedBy(Canonical, True, ICmpInst::ICMP_NE))
Zhou Sheng75b871f2007-01-11 12:24:14 +00001871 add(SI->getCondition(), ConstantInt::getFalse(),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001872 ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001873 }
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001874 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1875 for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
1876 OE = GEPI->idx_end(); OI != OE; ++OI) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00001877 ConstantInt *Op = dyn_cast<ConstantInt>(VN.canonicalize(*OI, Top));
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001878 if (!Op || !Op->isZero()) return;
1879 }
1880 // TODO: The GEPI indices are all zero. Copy from definition to operand,
1881 // jumping the type plane as needed.
1882 if (isRelatedBy(GEPI, Constant::getNullValue(GEPI->getType()),
1883 ICmpInst::ICMP_NE)) {
1884 Value *Ptr = GEPI->getPointerOperand();
1885 add(Ptr, Constant::getNullValue(Ptr->getType()), ICmpInst::ICMP_NE,
1886 NewContext);
1887 }
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001888 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
1889 const Type *SrcTy = CI->getSrcTy();
1890
Nick Lewyckye635cc42007-07-10 03:28:21 +00001891 unsigned ci = VN.getOrInsertVN(CI, Top);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001892 uint32_t W = VR.typeToWidth(SrcTy);
1893 if (!W) return;
Nick Lewyckye635cc42007-07-10 03:28:21 +00001894 ConstantRange CR = VR.range(ci, Top);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001895
1896 if (CR.isFullSet()) return;
1897
1898 switch (CI->getOpcode()) {
1899 default: break;
1900 case Instruction::ZExt:
1901 case Instruction::SExt:
Nick Lewyckye635cc42007-07-10 03:28:21 +00001902 VR.applyRange(VN.getOrInsertVN(CI->getOperand(0), Top),
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001903 CR.truncate(W), Top, this);
1904 break;
1905 case Instruction::BitCast:
Nick Lewyckye635cc42007-07-10 03:28:21 +00001906 VR.applyRange(VN.getOrInsertVN(CI->getOperand(0), Top),
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001907 CR, Top, this);
1908 break;
1909 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001910 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001911 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001912
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001913 /// opsToDef - A new relationship was discovered involving one of this
1914 /// instruction's operands. Find any new relationship involving the
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001915 /// definition, or another operand.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001916 void opsToDef(Instruction *I) {
1917 Instruction *NewContext = below(I) ? I : TopInst;
1918
1919 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00001920 Value *Op0 = VN.canonicalize(BO->getOperand(0), Top);
1921 Value *Op1 = VN.canonicalize(BO->getOperand(1), Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001922
Zhou Sheng75b871f2007-01-11 12:24:14 +00001923 if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0))
1924 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001925 add(BO, ConstantExpr::get(BO->getOpcode(), CI0, CI1),
1926 ICmpInst::ICMP_EQ, NewContext);
1927 return;
1928 }
1929
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001930 // "%y = and i1 true, %x" then %x EQ %y
1931 // "%y = or i1 false, %x" then %x EQ %y
1932 // "%x = add i32 %y, 0" then %x EQ %y
1933 // "%x = mul i32 %y, 0" then %x EQ 0
1934
1935 Instruction::BinaryOps Opcode = BO->getOpcode();
Nick Lewyckydb204ec2007-03-18 22:58:46 +00001936 const Type *Ty = BO->getType();
1937 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
1938
1939 Constant *Zero = Constant::getNullValue(Ty);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001940 ConstantInt *AllOnes = ConstantInt::getAllOnesValue(Ty);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001941
1942 switch (Opcode) {
1943 default: break;
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001944 case Instruction::LShr:
1945 case Instruction::AShr:
1946 case Instruction::Shl:
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001947 case Instruction::Sub:
Nick Lewyckydb204ec2007-03-18 22:58:46 +00001948 if (Op1 == Zero) {
1949 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1950 return;
1951 }
1952 break;
1953 case Instruction::Or:
1954 if (Op0 == AllOnes || Op1 == AllOnes) {
1955 add(BO, AllOnes, ICmpInst::ICMP_EQ, NewContext);
1956 return;
1957 } // fall-through
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001958 case Instruction::Xor:
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001959 case Instruction::Add:
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001960 if (Op0 == Zero) {
1961 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1962 return;
1963 } else if (Op1 == Zero) {
1964 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1965 return;
1966 }
Nick Lewyckydb204ec2007-03-18 22:58:46 +00001967 break;
1968 case Instruction::And:
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001969 if (Op0 == AllOnes) {
1970 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1971 return;
1972 } else if (Op1 == AllOnes) {
1973 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1974 return;
1975 }
Nick Lewyckydb204ec2007-03-18 22:58:46 +00001976 // fall-through
1977 case Instruction::Mul:
1978 if (Op0 == Zero || Op1 == Zero) {
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001979 add(BO, Zero, ICmpInst::ICMP_EQ, NewContext);
1980 return;
1981 }
Nick Lewyckydb204ec2007-03-18 22:58:46 +00001982 break;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001983 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001984
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001985 // "%x = add i32 %y, %z" and %x EQ %y then %z EQ 0
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001986 // "%x = add i32 %y, %z" and %x EQ %z then %y EQ 0
1987 // "%x = shl i32 %y, %z" and %x EQ %y and %y NE 0 then %z EQ 0
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001988 // "%x = udiv i32 %y, %z" and %x EQ %y then %z EQ 1
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001989
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001990 Value *Known = Op0, *Unknown = Op1,
Nick Lewycky73dd6922007-07-05 03:15:00 +00001991 *TheBO = VN.canonicalize(BO, Top);
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001992 if (Known != TheBO) std::swap(Known, Unknown);
1993 if (Known == TheBO) {
Nick Lewycky4f73de22007-03-16 02:37:39 +00001994 switch (Opcode) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001995 default: break;
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001996 case Instruction::LShr:
1997 case Instruction::AShr:
1998 case Instruction::Shl:
1999 if (!isRelatedBy(Known, Zero, ICmpInst::ICMP_NE)) break;
2000 // otherwise, fall-through.
2001 case Instruction::Sub:
2002 if (Unknown == Op1) break;
2003 // otherwise, fall-through.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002004 case Instruction::Xor:
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002005 case Instruction::Add:
Nick Lewyckydb204ec2007-03-18 22:58:46 +00002006 add(Unknown, Zero, ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002007 break;
2008 case Instruction::UDiv:
2009 case Instruction::SDiv:
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00002010 if (Unknown == Op1) break;
2011 if (isRelatedBy(Known, Zero, ICmpInst::ICMP_NE)) {
Nick Lewycky4a74a752007-01-12 00:02:12 +00002012 Constant *One = ConstantInt::get(Ty, 1);
2013 add(Unknown, One, ICmpInst::ICMP_EQ, NewContext);
2014 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00002015 break;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002016 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002017 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002018
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002019 // TODO: "%a = add i32 %b, 1" and %b > %z then %a >= %z.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002020
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002021 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
Nick Lewycky4f73de22007-03-16 02:37:39 +00002022 // "%a = icmp ult i32 %b, %c" and %b u< %c then %a EQ true
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002023 // "%a = icmp ult i32 %b, %c" and %b u>= %c then %a EQ false
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002024 // etc.
2025
Nick Lewycky73dd6922007-07-05 03:15:00 +00002026 Value *Op0 = VN.canonicalize(IC->getOperand(0), Top);
2027 Value *Op1 = VN.canonicalize(IC->getOperand(1), Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002028
2029 ICmpInst::Predicate Pred = IC->getPredicate();
Nick Lewyckye635cc42007-07-10 03:28:21 +00002030 if (isRelatedBy(Op0, Op1, Pred))
Zhou Sheng75b871f2007-01-11 12:24:14 +00002031 add(IC, ConstantInt::getTrue(), ICmpInst::ICMP_EQ, NewContext);
Nick Lewyckye635cc42007-07-10 03:28:21 +00002032 else if (isRelatedBy(Op0, Op1, ICmpInst::getInversePredicate(Pred)))
Zhou Sheng75b871f2007-01-11 12:24:14 +00002033 add(IC, ConstantInt::getFalse(), ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002034
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002035 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00002036 if (I->getType()->isFPOrFPVector()) return;
2037
Nick Lewycky4f73de22007-03-16 02:37:39 +00002038 // Given: "%a = select i1 %x, i32 %b, i32 %c"
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002039 // %x EQ true then %a EQ %b
2040 // %x EQ false then %a EQ %c
2041 // %b EQ %c then %a EQ %b
2042
Nick Lewycky73dd6922007-07-05 03:15:00 +00002043 Value *Canonical = VN.canonicalize(SI->getCondition(), Top);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002044 if (Canonical == ConstantInt::getTrue()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002045 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002046 } else if (Canonical == ConstantInt::getFalse()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002047 add(SI, SI->getFalseValue(), ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky73dd6922007-07-05 03:15:00 +00002048 } else if (VN.canonicalize(SI->getTrueValue(), Top) ==
2049 VN.canonicalize(SI->getFalseValue(), Top)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002050 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
2051 }
Nick Lewyckyee32ee02007-01-12 01:23:53 +00002052 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00002053 const Type *DestTy = CI->getDestTy();
2054 if (DestTy->isFPOrFPVector()) return;
Nick Lewyckyee32ee02007-01-12 01:23:53 +00002055
Nick Lewycky73dd6922007-07-05 03:15:00 +00002056 Value *Op = VN.canonicalize(CI->getOperand(0), Top);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00002057 Instruction::CastOps Opcode = CI->getOpcode();
2058
2059 if (Constant *C = dyn_cast<Constant>(Op)) {
2060 add(CI, ConstantExpr::getCast(Opcode, C, DestTy),
Nick Lewyckyee32ee02007-01-12 01:23:53 +00002061 ICmpInst::ICMP_EQ, NewContext);
2062 }
2063
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00002064 uint32_t W = VR.typeToWidth(DestTy);
Nick Lewyckye635cc42007-07-10 03:28:21 +00002065 unsigned ci = VN.getOrInsertVN(CI, Top);
2066 ConstantRange CR = VR.range(VN.getOrInsertVN(Op, Top), Top);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00002067
2068 if (!CR.isFullSet()) {
2069 switch (Opcode) {
2070 default: break;
2071 case Instruction::ZExt:
Nick Lewyckye635cc42007-07-10 03:28:21 +00002072 VR.applyRange(ci, CR.zeroExtend(W), Top, this);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00002073 break;
2074 case Instruction::SExt:
Nick Lewyckye635cc42007-07-10 03:28:21 +00002075 VR.applyRange(ci, CR.signExtend(W), Top, this);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00002076 break;
2077 case Instruction::Trunc: {
2078 ConstantRange Result = CR.truncate(W);
2079 if (!Result.isFullSet())
Nick Lewyckye635cc42007-07-10 03:28:21 +00002080 VR.applyRange(ci, Result, Top, this);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00002081 } break;
2082 case Instruction::BitCast:
Nick Lewyckye635cc42007-07-10 03:28:21 +00002083 VR.applyRange(ci, CR, Top, this);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00002084 break;
2085 // TODO: other casts?
2086 }
2087 }
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00002088 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
2089 for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
2090 OE = GEPI->idx_end(); OI != OE; ++OI) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002091 ConstantInt *Op = dyn_cast<ConstantInt>(VN.canonicalize(*OI, Top));
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00002092 if (!Op || !Op->isZero()) return;
2093 }
2094 // TODO: The GEPI indices are all zero. Copy from operand to definition,
2095 // jumping the type plane as needed.
2096 Value *Ptr = GEPI->getPointerOperand();
2097 if (isRelatedBy(Ptr, Constant::getNullValue(Ptr->getType()),
2098 ICmpInst::ICMP_NE)) {
2099 add(GEPI, Constant::getNullValue(GEPI->getType()), ICmpInst::ICMP_NE,
2100 NewContext);
2101 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002102 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002103 }
2104
2105 /// solve - process the work queue
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002106 void solve() {
2107 //DOUT << "WorkList entry, size: " << WorkList.size() << "\n";
2108 while (!WorkList.empty()) {
2109 //DOUT << "WorkList size: " << WorkList.size() << "\n";
2110
2111 Operation &O = WorkList.front();
Nick Lewycky42944462007-01-13 02:05:28 +00002112 TopInst = O.ContextInst;
2113 TopBB = O.ContextBB;
Nick Lewycky26e25d32007-06-24 04:36:20 +00002114 Top = DTDFS->getNodeForBlock(TopBB); // XXX move this into Context
Nick Lewycky42944462007-01-13 02:05:28 +00002115
Nick Lewycky73dd6922007-07-05 03:15:00 +00002116 O.LHS = VN.canonicalize(O.LHS, Top);
2117 O.RHS = VN.canonicalize(O.RHS, Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002118
Nick Lewycky73dd6922007-07-05 03:15:00 +00002119 assert(O.LHS == VN.canonicalize(O.LHS, Top) && "Canonicalize isn't.");
2120 assert(O.RHS == VN.canonicalize(O.RHS, Top) && "Canonicalize isn't.");
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002121
2122 DOUT << "solving " << *O.LHS << " " << O.Op << " " << *O.RHS;
Nick Lewycky42944462007-01-13 02:05:28 +00002123 if (O.ContextInst) DOUT << " context inst: " << *O.ContextInst;
2124 else DOUT << " context block: " << O.ContextBB->getName();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002125 DOUT << "\n";
2126
Nick Lewyckye635cc42007-07-10 03:28:21 +00002127 DEBUG(VN.dump());
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002128 DEBUG(IG.dump());
Nick Lewyckye635cc42007-07-10 03:28:21 +00002129 DEBUG(VR.dump());
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002130
Nick Lewycky15245952007-02-04 23:43:05 +00002131 // If they're both Constant, skip it. Check for contradiction and mark
2132 // the BB as unreachable if so.
2133 if (Constant *CI_L = dyn_cast<Constant>(O.LHS)) {
2134 if (Constant *CI_R = dyn_cast<Constant>(O.RHS)) {
2135 if (ConstantExpr::getCompare(O.Op, CI_L, CI_R) ==
2136 ConstantInt::getFalse())
2137 UB.mark(TopBB);
2138
2139 WorkList.pop_front();
2140 continue;
2141 }
2142 }
2143
Nick Lewycky73dd6922007-07-05 03:15:00 +00002144 if (VN.compare(O.LHS, O.RHS)) {
Nick Lewycky15245952007-02-04 23:43:05 +00002145 std::swap(O.LHS, O.RHS);
2146 O.Op = ICmpInst::getSwappedPredicate(O.Op);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002147 }
2148
2149 if (O.Op == ICmpInst::ICMP_EQ) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002150 if (!makeEqual(O.RHS, O.LHS))
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002151 UB.mark(TopBB);
2152 } else {
2153 LatticeVal LV = cmpInstToLattice(O.Op);
2154
2155 if ((LV & EQ_BIT) &&
2156 isRelatedBy(O.LHS, O.RHS, ICmpInst::getSwappedPredicate(O.Op))) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002157 if (!makeEqual(O.RHS, O.LHS))
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002158 UB.mark(TopBB);
2159 } else {
2160 if (isRelatedBy(O.LHS, O.RHS, ICmpInst::getInversePredicate(O.Op))){
Nick Lewycky15245952007-02-04 23:43:05 +00002161 UB.mark(TopBB);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002162 WorkList.pop_front();
2163 continue;
2164 }
2165
Nick Lewyckye635cc42007-07-10 03:28:21 +00002166 unsigned n1 = VN.getOrInsertVN(O.LHS, Top);
2167 unsigned n2 = VN.getOrInsertVN(O.RHS, Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002168
Nick Lewyckye635cc42007-07-10 03:28:21 +00002169 if (n1 == n2) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002170 if (O.Op != ICmpInst::ICMP_UGE && O.Op != ICmpInst::ICMP_ULE &&
2171 O.Op != ICmpInst::ICMP_SGE && O.Op != ICmpInst::ICMP_SLE)
2172 UB.mark(TopBB);
2173
2174 WorkList.pop_front();
2175 continue;
2176 }
2177
Nick Lewyckye635cc42007-07-10 03:28:21 +00002178 if (VR.isRelatedBy(n1, n2, Top, LV) ||
2179 IG.isRelatedBy(n1, n2, Top, LV)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002180 WorkList.pop_front();
2181 continue;
2182 }
2183
Nick Lewyckye635cc42007-07-10 03:28:21 +00002184 VR.addInequality(n1, n2, Top, LV, this);
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002185 if ((!isa<ConstantInt>(O.RHS) && !isa<ConstantInt>(O.LHS)) ||
Nick Lewyckye635cc42007-07-10 03:28:21 +00002186 LV == NE)
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002187 IG.addInequality(n1, n2, Top, LV);
Nick Lewycky15245952007-02-04 23:43:05 +00002188
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002189 if (Instruction *I1 = dyn_cast<Instruction>(O.LHS)) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002190 if (aboveOrBelow(I1))
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002191 defToOps(I1);
2192 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002193 if (isa<Instruction>(O.LHS) || isa<Argument>(O.LHS)) {
2194 for (Value::use_iterator UI = O.LHS->use_begin(),
2195 UE = O.LHS->use_end(); UI != UE;) {
2196 Use &TheUse = UI.getUse();
2197 ++UI;
2198 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002199 if (aboveOrBelow(I))
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002200 opsToDef(I);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002201 }
2202 }
2203 }
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002204 if (Instruction *I2 = dyn_cast<Instruction>(O.RHS)) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002205 if (aboveOrBelow(I2))
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002206 defToOps(I2);
2207 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002208 if (isa<Instruction>(O.RHS) || isa<Argument>(O.RHS)) {
2209 for (Value::use_iterator UI = O.RHS->use_begin(),
2210 UE = O.RHS->use_end(); UI != UE;) {
2211 Use &TheUse = UI.getUse();
2212 ++UI;
2213 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002214 if (aboveOrBelow(I))
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002215 opsToDef(I);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002216 }
2217 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00002218 }
2219 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00002220 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002221 WorkList.pop_front();
Nick Lewycky9d17c822006-10-25 23:48:24 +00002222 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00002223 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002224 };
2225
Nick Lewycky3bb6de82007-04-07 03:36:51 +00002226 void ValueRanges::addToWorklist(Value *V, Constant *C,
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002227 ICmpInst::Predicate Pred, VRPSolver *VRP) {
Nick Lewycky3bb6de82007-04-07 03:36:51 +00002228 VRP->add(V, C, Pred, VRP->TopInst);
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002229 }
2230
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00002231 void ValueRanges::markBlock(VRPSolver *VRP) {
2232 VRP->UB.mark(VRP->TopBB);
2233 }
2234
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002235 /// PredicateSimplifier - This class is a simplifier that replaces
2236 /// one equivalent variable with another. It also tracks what
2237 /// can't be equal and will solve setcc instructions when possible.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002238 /// @brief Root of the predicate simplifier optimization.
2239 class VISIBILITY_HIDDEN PredicateSimplifier : public FunctionPass {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002240 DomTreeDFS *DTDFS;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002241 bool modified;
Nick Lewycky73dd6922007-07-05 03:15:00 +00002242 ValueNumbering *VN;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002243 InequalityGraph *IG;
2244 UnreachableBlocks UB;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002245 ValueRanges *VR;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002246
Nick Lewycky26e25d32007-06-24 04:36:20 +00002247 std::vector<DomTreeDFS::Node *> WorkList;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002248
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002249 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +00002250 static char ID; // Pass identification, replacement for typeid
Devang Patel09f162c2007-05-01 21:15:47 +00002251 PredicateSimplifier() : FunctionPass((intptr_t)&ID) {}
2252
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002253 bool runOnFunction(Function &F);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002254
2255 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
2256 AU.addRequiredID(BreakCriticalEdgesID);
Owen Anderson510fefc2007-04-25 04:18:54 +00002257 AU.addRequired<DominatorTree>();
Nick Lewycky12d44ab2007-04-07 03:16:12 +00002258 AU.addRequired<TargetData>();
2259 AU.addPreserved<TargetData>();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002260 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002261
2262 private:
Nick Lewyckyb7c0c8a2007-07-16 02:58:37 +00002263 /// Forwards - Adds new properties to VRPSolver and uses them to
Nick Lewycky77e030b2006-10-12 02:02:44 +00002264 /// simplify instructions. Because new properties sometimes apply to
2265 /// a transition from one BasicBlock to another, this will use the
2266 /// PredicateSimplifier::proceedToSuccessor(s) interface to enter the
Nick Lewyckyb7c0c8a2007-07-16 02:58:37 +00002267 /// basic block.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002268 /// @brief Performs abstract execution of the program.
2269 class VISIBILITY_HIDDEN Forwards : public InstVisitor<Forwards> {
Nick Lewycky77e030b2006-10-12 02:02:44 +00002270 friend class InstVisitor<Forwards>;
2271 PredicateSimplifier *PS;
Nick Lewycky26e25d32007-06-24 04:36:20 +00002272 DomTreeDFS::Node *DTNode;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002273
Nick Lewycky77e030b2006-10-12 02:02:44 +00002274 public:
Nick Lewycky73dd6922007-07-05 03:15:00 +00002275 ValueNumbering &VN;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002276 InequalityGraph &IG;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002277 UnreachableBlocks &UB;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002278 ValueRanges &VR;
Nick Lewycky77e030b2006-10-12 02:02:44 +00002279
Nick Lewycky26e25d32007-06-24 04:36:20 +00002280 Forwards(PredicateSimplifier *PS, DomTreeDFS::Node *DTNode)
Nick Lewycky73dd6922007-07-05 03:15:00 +00002281 : PS(PS), DTNode(DTNode), VN(*PS->VN), IG(*PS->IG), UB(PS->UB),
2282 VR(*PS->VR) {}
Nick Lewycky77e030b2006-10-12 02:02:44 +00002283
2284 void visitTerminatorInst(TerminatorInst &TI);
2285 void visitBranchInst(BranchInst &BI);
2286 void visitSwitchInst(SwitchInst &SI);
2287
Nick Lewyckyf3450082006-10-22 19:53:27 +00002288 void visitAllocaInst(AllocaInst &AI);
Nick Lewycky77e030b2006-10-12 02:02:44 +00002289 void visitLoadInst(LoadInst &LI);
2290 void visitStoreInst(StoreInst &SI);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002291
Nick Lewycky15245952007-02-04 23:43:05 +00002292 void visitSExtInst(SExtInst &SI);
2293 void visitZExtInst(ZExtInst &ZI);
2294
Nick Lewycky77e030b2006-10-12 02:02:44 +00002295 void visitBinaryOperator(BinaryOperator &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002296 void visitICmpInst(ICmpInst &IC);
Nick Lewycky77e030b2006-10-12 02:02:44 +00002297 };
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002298
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002299 // Used by terminator instructions to proceed from the current basic
2300 // block to the next. Verifies that "current" dominates "next",
2301 // then calls visitBasicBlock.
Nick Lewycky26e25d32007-06-24 04:36:20 +00002302 void proceedToSuccessors(DomTreeDFS::Node *Current) {
2303 for (DomTreeDFS::Node::iterator I = Current->begin(),
Owen Anderson510fefc2007-04-25 04:18:54 +00002304 E = Current->end(); I != E; ++I) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002305 WorkList.push_back(*I);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002306 }
2307 }
2308
Nick Lewycky26e25d32007-06-24 04:36:20 +00002309 void proceedToSuccessor(DomTreeDFS::Node *Next) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002310 WorkList.push_back(Next);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002311 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002312
2313 // Visits each instruction in the basic block.
Nick Lewycky26e25d32007-06-24 04:36:20 +00002314 void visitBasicBlock(DomTreeDFS::Node *Node) {
Owen Anderson510fefc2007-04-25 04:18:54 +00002315 BasicBlock *BB = Node->getBlock();
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002316 DOUT << "Entering Basic Block: " << BB->getName()
Nick Lewycky26e25d32007-06-24 04:36:20 +00002317 << " (" << Node->getDFSNumIn() << ")\n";
Bill Wendling22e978a2006-12-07 20:04:42 +00002318 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002319 visitInstruction(I++, Node);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002320 }
2321 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002322
Nick Lewyckyb7c0c8a2007-07-16 02:58:37 +00002323 // Tries to simplify each Instruction and add new properties.
Nick Lewycky26e25d32007-06-24 04:36:20 +00002324 void visitInstruction(Instruction *I, DomTreeDFS::Node *DT) {
Bill Wendling22e978a2006-12-07 20:04:42 +00002325 DOUT << "Considering instruction " << *I << "\n";
Nick Lewyckye635cc42007-07-10 03:28:21 +00002326 DEBUG(VN->dump());
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002327 DEBUG(IG->dump());
Nick Lewyckye635cc42007-07-10 03:28:21 +00002328 DEBUG(VR->dump());
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002329
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002330 // Sometimes instructions are killed in earlier analysis.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002331 if (isInstructionTriviallyDead(I)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002332 ++NumSimple;
2333 modified = true;
Nick Lewycky73dd6922007-07-05 03:15:00 +00002334 if (unsigned n = VN->valueNumber(I, DTDFS->getRootNode()))
2335 if (VN->value(n) == I) IG->remove(n);
2336 VN->remove(I);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002337 I->eraseFromParent();
2338 return;
2339 }
2340
Nick Lewycky42944462007-01-13 02:05:28 +00002341#ifndef NDEBUG
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002342 // Try to replace the whole instruction.
Nick Lewycky73dd6922007-07-05 03:15:00 +00002343 Value *V = VN->canonicalize(I, DT);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002344 assert(V == I && "Late instruction canonicalization.");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002345 if (V != I) {
2346 modified = true;
2347 ++NumInstruction;
Bill Wendling22e978a2006-12-07 20:04:42 +00002348 DOUT << "Removing " << *I << ", replacing with " << *V << "\n";
Nick Lewycky73dd6922007-07-05 03:15:00 +00002349 if (unsigned n = VN->valueNumber(I, DTDFS->getRootNode()))
2350 if (VN->value(n) == I) IG->remove(n);
2351 VN->remove(I);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002352 I->replaceAllUsesWith(V);
2353 I->eraseFromParent();
2354 return;
2355 }
2356
2357 // Try to substitute operands.
2358 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2359 Value *Oper = I->getOperand(i);
Nick Lewycky73dd6922007-07-05 03:15:00 +00002360 Value *V = VN->canonicalize(Oper, DT);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002361 assert(V == Oper && "Late operand canonicalization.");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002362 if (V != Oper) {
2363 modified = true;
2364 ++NumVarsReplaced;
Bill Wendling22e978a2006-12-07 20:04:42 +00002365 DOUT << "Resolving " << *I;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002366 I->setOperand(i, V);
Bill Wendling22e978a2006-12-07 20:04:42 +00002367 DOUT << " into " << *I;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002368 }
2369 }
Nick Lewycky42944462007-01-13 02:05:28 +00002370#endif
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002371
Nick Lewycky4f73de22007-03-16 02:37:39 +00002372 std::string name = I->getParent()->getName();
2373 DOUT << "push (%" << name << ")\n";
Owen Anderson510fefc2007-04-25 04:18:54 +00002374 Forwards visit(this, DT);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002375 visit.visit(*I);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002376 DOUT << "pop (%" << name << ")\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002377 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002378 };
2379
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002380 bool PredicateSimplifier::runOnFunction(Function &F) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002381 DominatorTree *DT = &getAnalysis<DominatorTree>();
2382 DTDFS = new DomTreeDFS(DT);
Nick Lewycky12d44ab2007-04-07 03:16:12 +00002383 TargetData *TD = &getAnalysis<TargetData>();
2384
Bill Wendling22e978a2006-12-07 20:04:42 +00002385 DOUT << "Entering Function: " << F.getName() << "\n";
Nick Lewyckycfff1c32006-09-20 17:04:01 +00002386
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002387 modified = false;
Nick Lewycky26e25d32007-06-24 04:36:20 +00002388 DomTreeDFS::Node *Root = DTDFS->getRootNode();
Nick Lewycky73dd6922007-07-05 03:15:00 +00002389 VN = new ValueNumbering(DTDFS);
2390 IG = new InequalityGraph(*VN, Root);
Nick Lewyckye635cc42007-07-10 03:28:21 +00002391 VR = new ValueRanges(*VN, TD);
Nick Lewycky26e25d32007-06-24 04:36:20 +00002392 WorkList.push_back(Root);
Nick Lewyckycfff1c32006-09-20 17:04:01 +00002393
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002394 do {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002395 DomTreeDFS::Node *DTNode = WorkList.back();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002396 WorkList.pop_back();
Owen Anderson510fefc2007-04-25 04:18:54 +00002397 if (!UB.isDead(DTNode->getBlock())) visitBasicBlock(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002398 } while (!WorkList.empty());
Nick Lewyckycfff1c32006-09-20 17:04:01 +00002399
Nick Lewycky26e25d32007-06-24 04:36:20 +00002400 delete DTDFS;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002401 delete VR;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002402 delete IG;
2403
2404 modified |= UB.kill();
Nick Lewyckycfff1c32006-09-20 17:04:01 +00002405
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002406 return modified;
Nick Lewycky8e559932006-09-02 19:40:38 +00002407 }
2408
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002409 void PredicateSimplifier::Forwards::visitTerminatorInst(TerminatorInst &TI) {
Owen Anderson510fefc2007-04-25 04:18:54 +00002410 PS->proceedToSuccessors(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002411 }
2412
2413 void PredicateSimplifier::Forwards::visitBranchInst(BranchInst &BI) {
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002414 if (BI.isUnconditional()) {
Owen Anderson510fefc2007-04-25 04:18:54 +00002415 PS->proceedToSuccessors(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002416 return;
2417 }
2418
2419 Value *Condition = BI.getCondition();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002420 BasicBlock *TrueDest = BI.getSuccessor(0);
2421 BasicBlock *FalseDest = BI.getSuccessor(1);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002422
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002423 if (isa<Constant>(Condition) || TrueDest == FalseDest) {
Owen Anderson510fefc2007-04-25 04:18:54 +00002424 PS->proceedToSuccessors(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002425 return;
2426 }
2427
Nick Lewycky26e25d32007-06-24 04:36:20 +00002428 for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
Owen Anderson510fefc2007-04-25 04:18:54 +00002429 I != E; ++I) {
2430 BasicBlock *Dest = (*I)->getBlock();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002431 DOUT << "Branch thinking about %" << Dest->getName()
Nick Lewycky26e25d32007-06-24 04:36:20 +00002432 << "(" << PS->DTDFS->getNodeForBlock(Dest)->getDFSNumIn() << ")\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002433
2434 if (Dest == TrueDest) {
Owen Anderson510fefc2007-04-25 04:18:54 +00002435 DOUT << "(" << DTNode->getBlock()->getName() << ") true set:\n";
Nick Lewycky73dd6922007-07-05 03:15:00 +00002436 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002437 VRP.add(ConstantInt::getTrue(), Condition, ICmpInst::ICMP_EQ);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002438 VRP.solve();
Nick Lewyckye635cc42007-07-10 03:28:21 +00002439 DEBUG(VN.dump());
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002440 DEBUG(IG.dump());
Nick Lewyckye635cc42007-07-10 03:28:21 +00002441 DEBUG(VR.dump());
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002442 } else if (Dest == FalseDest) {
Owen Anderson510fefc2007-04-25 04:18:54 +00002443 DOUT << "(" << DTNode->getBlock()->getName() << ") false set:\n";
Nick Lewycky73dd6922007-07-05 03:15:00 +00002444 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002445 VRP.add(ConstantInt::getFalse(), Condition, ICmpInst::ICMP_EQ);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002446 VRP.solve();
Nick Lewyckye635cc42007-07-10 03:28:21 +00002447 DEBUG(VN.dump());
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002448 DEBUG(IG.dump());
Nick Lewyckye635cc42007-07-10 03:28:21 +00002449 DEBUG(VR.dump());
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002450 }
2451
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002452 PS->proceedToSuccessor(*I);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002453 }
2454 }
2455
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002456 void PredicateSimplifier::Forwards::visitSwitchInst(SwitchInst &SI) {
2457 Value *Condition = SI.getCondition();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002458
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002459 // Set the EQProperty in each of the cases BBs, and the NEProperties
2460 // in the default BB.
Owen Anderson510fefc2007-04-25 04:18:54 +00002461
Nick Lewycky26e25d32007-06-24 04:36:20 +00002462 for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
Owen Anderson510fefc2007-04-25 04:18:54 +00002463 I != E; ++I) {
2464 BasicBlock *BB = (*I)->getBlock();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002465 DOUT << "Switch thinking about BB %" << BB->getName()
Nick Lewycky26e25d32007-06-24 04:36:20 +00002466 << "(" << PS->DTDFS->getNodeForBlock(BB)->getDFSNumIn() << ")\n";
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002467
Nick Lewycky73dd6922007-07-05 03:15:00 +00002468 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, BB);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002469 if (BB == SI.getDefaultDest()) {
2470 for (unsigned i = 1, e = SI.getNumCases(); i < e; ++i)
2471 if (SI.getSuccessor(i) != BB)
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002472 VRP.add(Condition, SI.getCaseValue(i), ICmpInst::ICMP_NE);
2473 VRP.solve();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002474 } else if (ConstantInt *CI = SI.findCaseDest(BB)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002475 VRP.add(Condition, CI, ICmpInst::ICMP_EQ);
2476 VRP.solve();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002477 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002478 PS->proceedToSuccessor(*I);
Nick Lewycky1d00f3e2006-10-03 15:19:11 +00002479 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002480 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002481
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002482 void PredicateSimplifier::Forwards::visitAllocaInst(AllocaInst &AI) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002483 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &AI);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002484 VRP.add(Constant::getNullValue(AI.getType()), &AI, ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002485 VRP.solve();
2486 }
Nick Lewyckyf3450082006-10-22 19:53:27 +00002487
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002488 void PredicateSimplifier::Forwards::visitLoadInst(LoadInst &LI) {
2489 Value *Ptr = LI.getPointerOperand();
2490 // avoid "load uint* null" -> null NE null.
2491 if (isa<Constant>(Ptr)) return;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002492
Nick Lewycky73dd6922007-07-05 03:15:00 +00002493 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &LI);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002494 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002495 VRP.solve();
2496 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002497
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002498 void PredicateSimplifier::Forwards::visitStoreInst(StoreInst &SI) {
2499 Value *Ptr = SI.getPointerOperand();
2500 if (isa<Constant>(Ptr)) return;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002501
Nick Lewycky73dd6922007-07-05 03:15:00 +00002502 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002503 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002504 VRP.solve();
2505 }
2506
Nick Lewycky15245952007-02-04 23:43:05 +00002507 void PredicateSimplifier::Forwards::visitSExtInst(SExtInst &SI) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002508 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
Reid Spencerc34dedf2007-03-03 00:48:31 +00002509 uint32_t SrcBitWidth = cast<IntegerType>(SI.getSrcTy())->getBitWidth();
2510 uint32_t DstBitWidth = cast<IntegerType>(SI.getDestTy())->getBitWidth();
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00002511 APInt Min(APInt::getHighBitsSet(DstBitWidth, DstBitWidth-SrcBitWidth+1));
2512 APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth-1));
Reid Spencerc34dedf2007-03-03 00:48:31 +00002513 VRP.add(ConstantInt::get(Min), &SI, ICmpInst::ICMP_SLE);
2514 VRP.add(ConstantInt::get(Max), &SI, ICmpInst::ICMP_SGE);
Nick Lewycky15245952007-02-04 23:43:05 +00002515 VRP.solve();
2516 }
2517
2518 void PredicateSimplifier::Forwards::visitZExtInst(ZExtInst &ZI) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002519 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &ZI);
Reid Spencerc34dedf2007-03-03 00:48:31 +00002520 uint32_t SrcBitWidth = cast<IntegerType>(ZI.getSrcTy())->getBitWidth();
2521 uint32_t DstBitWidth = cast<IntegerType>(ZI.getDestTy())->getBitWidth();
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00002522 APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth));
Reid Spencerc34dedf2007-03-03 00:48:31 +00002523 VRP.add(ConstantInt::get(Max), &ZI, ICmpInst::ICMP_UGE);
Nick Lewycky15245952007-02-04 23:43:05 +00002524 VRP.solve();
2525 }
2526
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002527 void PredicateSimplifier::Forwards::visitBinaryOperator(BinaryOperator &BO) {
2528 Instruction::BinaryOps ops = BO.getOpcode();
2529
2530 switch (ops) {
Nick Lewycky4f73de22007-03-16 02:37:39 +00002531 default: break;
Nick Lewycky15245952007-02-04 23:43:05 +00002532 case Instruction::URem:
2533 case Instruction::SRem:
2534 case Instruction::UDiv:
2535 case Instruction::SDiv: {
2536 Value *Divisor = BO.getOperand(1);
Nick Lewycky73dd6922007-07-05 03:15:00 +00002537 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky15245952007-02-04 23:43:05 +00002538 VRP.add(Constant::getNullValue(Divisor->getType()), Divisor,
2539 ICmpInst::ICMP_NE);
2540 VRP.solve();
2541 break;
2542 }
Nick Lewycky4f73de22007-03-16 02:37:39 +00002543 }
2544
2545 switch (ops) {
2546 default: break;
2547 case Instruction::Shl: {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002548 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002549 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
2550 VRP.solve();
2551 } break;
2552 case Instruction::AShr: {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002553 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002554 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_SLE);
2555 VRP.solve();
2556 } break;
2557 case Instruction::LShr:
2558 case Instruction::UDiv: {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002559 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002560 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
2561 VRP.solve();
2562 } break;
2563 case Instruction::URem: {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002564 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002565 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
2566 VRP.solve();
2567 } break;
2568 case Instruction::And: {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002569 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002570 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
2571 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
2572 VRP.solve();
2573 } break;
2574 case Instruction::Or: {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002575 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002576 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
2577 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_UGE);
2578 VRP.solve();
2579 } break;
2580 }
2581 }
2582
2583 void PredicateSimplifier::Forwards::visitICmpInst(ICmpInst &IC) {
2584 // If possible, squeeze the ICmp predicate into something simpler.
2585 // Eg., if x = [0, 4) and we're being asked icmp uge %x, 3 then change
2586 // the predicate to eq.
2587
Nick Lewyckyeeb01b42007-04-07 02:30:14 +00002588 // XXX: once we do full PHI handling, modifying the instruction in the
2589 // Forwards visitor will cause missed optimizations.
2590
Nick Lewycky4f73de22007-03-16 02:37:39 +00002591 ICmpInst::Predicate Pred = IC.getPredicate();
2592
Nick Lewyckyeeb01b42007-04-07 02:30:14 +00002593 switch (Pred) {
2594 default: break;
2595 case ICmpInst::ICMP_ULE: Pred = ICmpInst::ICMP_ULT; break;
2596 case ICmpInst::ICMP_UGE: Pred = ICmpInst::ICMP_UGT; break;
2597 case ICmpInst::ICMP_SLE: Pred = ICmpInst::ICMP_SLT; break;
2598 case ICmpInst::ICMP_SGE: Pred = ICmpInst::ICMP_SGT; break;
2599 }
2600 if (Pred != IC.getPredicate()) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002601 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &IC);
Nick Lewyckyeeb01b42007-04-07 02:30:14 +00002602 if (VRP.isRelatedBy(IC.getOperand(1), IC.getOperand(0),
2603 ICmpInst::ICMP_NE)) {
2604 ++NumSnuggle;
2605 PS->modified = true;
2606 IC.setPredicate(Pred);
2607 }
2608 }
2609
2610 Pred = IC.getPredicate();
2611
Nick Lewycky4f73de22007-03-16 02:37:39 +00002612 if (ConstantInt *Op1 = dyn_cast<ConstantInt>(IC.getOperand(1))) {
2613 ConstantInt *NextVal = 0;
Nick Lewyckyeeb01b42007-04-07 02:30:14 +00002614 switch (Pred) {
Nick Lewycky4f73de22007-03-16 02:37:39 +00002615 default: break;
2616 case ICmpInst::ICMP_SLT:
2617 case ICmpInst::ICMP_ULT:
2618 if (Op1->getValue() != 0)
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00002619 NextVal = ConstantInt::get(Op1->getValue()-1);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002620 break;
2621 case ICmpInst::ICMP_SGT:
2622 case ICmpInst::ICMP_UGT:
2623 if (!Op1->getValue().isAllOnesValue())
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00002624 NextVal = ConstantInt::get(Op1->getValue()+1);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002625 break;
2626
2627 }
2628 if (NextVal) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002629 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &IC);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002630 if (VRP.isRelatedBy(IC.getOperand(0), NextVal,
2631 ICmpInst::getInversePredicate(Pred))) {
2632 ICmpInst *NewIC = new ICmpInst(ICmpInst::ICMP_EQ, IC.getOperand(0),
2633 NextVal, "", &IC);
2634 NewIC->takeName(&IC);
2635 IC.replaceAllUsesWith(NewIC);
Nick Lewycky73dd6922007-07-05 03:15:00 +00002636
2637 // XXX: prove this isn't necessary
2638 if (unsigned n = VN.valueNumber(&IC, PS->DTDFS->getRootNode()))
2639 if (VN.value(n) == &IC) IG.remove(n);
2640 VN.remove(&IC);
2641
Nick Lewycky4f73de22007-03-16 02:37:39 +00002642 IC.eraseFromParent();
2643 ++NumSnuggle;
2644 PS->modified = true;
Nick Lewycky4f73de22007-03-16 02:37:39 +00002645 }
2646 }
2647 }
Nick Lewycky5f8f9af2006-08-30 02:46:48 +00002648 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002649
Devang Patel8c78a0b2007-05-03 01:11:54 +00002650 char PredicateSimplifier::ID = 0;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002651 RegisterPass<PredicateSimplifier> X("predsimplify",
2652 "Predicate Simplifier");
2653}
2654
2655FunctionPass *llvm::createPredicateSimplifierPass() {
2656 return new PredicateSimplifier();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002657}