blob: 6b5af293dc040b06df07972f1340d05467e44a34 [file] [log] [blame]
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001//===-- PredicateSimplifier.cpp - Path Sensitive Simplifier ---------------===//
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Nick Lewycky and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00008//===----------------------------------------------------------------------===//
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00009//
10// Path-sensitive optimizer. In a branch where x == y, replace uses of
11// x with y. Permits further optimization, such as the elimination of
12// the unreachable call:
13//
14// void test(int *p, int *q)
15// {
16// if (p != q)
17// return;
18//
19// if (*p != *q)
20// foo(); // unreachable
21// }
22//
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000023//===----------------------------------------------------------------------===//
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000024//
Nick Lewycky4f73de22007-03-16 02:37:39 +000025// The InequalityGraph focusses on four properties; equals, not equals,
26// less-than and less-than-or-equals-to. The greater-than forms are also held
27// just to allow walking from a lesser node to a greater one. These properties
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000028// are stored in a lattice; LE can become LT or EQ, NE can become LT or GT.
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000029//
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000030// These relationships define a graph between values of the same type. Each
31// Value is stored in a map table that retrieves the associated Node. This
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +000032// is how EQ relationships are stored; the map contains pointers from equal
33// Value to the same node. The node contains a most canonical Value* form
34// and the list of known relationships with other nodes.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000035//
36// If two nodes are known to be inequal, then they will contain pointers to
37// each other with an "NE" relationship. If node getNode(%x) is less than
38// getNode(%y), then the %x node will contain <%y, GT> and %y will contain
39// <%x, LT>. This allows us to tie nodes together into a graph like this:
40//
41// %a < %b < %c < %d
42//
43// with four nodes representing the properties. The InequalityGraph provides
Nick Lewycky2fc338f2007-01-11 02:32:38 +000044// querying with "isRelatedBy" and mutators "addEquality" and "addInequality".
45// To find a relationship, we start with one of the nodes any binary search
46// through its list to find where the relationships with the second node start.
47// Then we iterate through those to find the first relationship that dominates
48// our context node.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000049//
50// To create these properties, we wait until a branch or switch instruction
51// implies that a particular value is true (or false). The VRPSolver is
52// responsible for analyzing the variable and seeing what new inferences
53// can be made from each property. For example:
54//
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +000055// %P = icmp ne i32* %ptr, null
56// %a = and i1 %P, %Q
57// br i1 %a label %cond_true, label %cond_false
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000058//
59// For the true branch, the VRPSolver will start with %a EQ true and look at
60// the definition of %a and find that it can infer that %P and %Q are both
61// true. From %P being true, it can infer that %ptr NE null. For the false
Nick Lewycky56639802007-01-29 02:56:54 +000062// branch it can't infer anything from the "and" instruction.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000063//
64// Besides branches, we can also infer properties from instruction that may
65// have undefined behaviour in certain cases. For example, the dividend of
66// a division may never be zero. After the division instruction, we may assume
67// that the dividend is not equal to zero.
68//
69//===----------------------------------------------------------------------===//
Nick Lewycky4f73de22007-03-16 02:37:39 +000070//
71// The ValueRanges class stores the known integer bounds of a Value. When we
72// encounter i8 %a u< %b, the ValueRanges stores that %a = [1, 255] and
73// %b = [0, 254]. Because we store these by Value*, you should always
74// canonicalize through the InequalityGraph first.
75//
76// It never stores an empty range, because that means that the code is
77// unreachable. It never stores a single-element range since that's an equality
Nick Lewycky12d44ab2007-04-07 03:16:12 +000078// relationship and better stored in the InequalityGraph, nor an empty range
79// since that is better stored in UnreachableBlocks.
Nick Lewycky4f73de22007-03-16 02:37:39 +000080//
81//===----------------------------------------------------------------------===//
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000082
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000083#define DEBUG_TYPE "predsimplify"
84#include "llvm/Transforms/Scalar.h"
85#include "llvm/Constants.h"
Nick Lewyckyf3450082006-10-22 19:53:27 +000086#include "llvm/DerivedTypes.h"
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000087#include "llvm/Instructions.h"
88#include "llvm/Pass.h"
Nick Lewycky2fc338f2007-01-11 02:32:38 +000089#include "llvm/ADT/DepthFirstIterator.h"
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000090#include "llvm/ADT/SetOperations.h"
Reid Spencer3f4e6e82007-02-04 00:40:42 +000091#include "llvm/ADT/SetVector.h"
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000092#include "llvm/ADT/Statistic.h"
93#include "llvm/ADT/STLExtras.h"
94#include "llvm/Analysis/Dominators.h"
95#include "llvm/Support/CFG.h"
Chris Lattnerf06bb652006-12-06 18:14:47 +000096#include "llvm/Support/Compiler.h"
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +000097#include "llvm/Support/ConstantRange.h"
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000098#include "llvm/Support/Debug.h"
Nick Lewycky77e030b2006-10-12 02:02:44 +000099#include "llvm/Support/InstVisitor.h"
Nick Lewycky12d44ab2007-04-07 03:16:12 +0000100#include "llvm/Target/TargetData.h"
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000101#include "llvm/Transforms/Utils/Local.h"
102#include <algorithm>
103#include <deque>
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000104#include <sstream>
Nick Lewycky26e25d32007-06-24 04:36:20 +0000105#include <stack>
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000106using namespace llvm;
107
Chris Lattner0e5255b2006-12-19 21:49:03 +0000108STATISTIC(NumVarsReplaced, "Number of argument substitutions");
109STATISTIC(NumInstruction , "Number of instructions removed");
110STATISTIC(NumSimple , "Number of simple replacements");
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000111STATISTIC(NumBlocks , "Number of blocks marked unreachable");
Nick Lewycky4f73de22007-03-16 02:37:39 +0000112STATISTIC(NumSnuggle , "Number of comparisons snuggled");
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000113
Chris Lattner0e5255b2006-12-19 21:49:03 +0000114namespace {
Nick Lewycky26e25d32007-06-24 04:36:20 +0000115 class DomTreeDFS {
116 public:
117 class Node {
118 friend class DomTreeDFS;
119 public:
120 typedef std::vector<Node *>::iterator iterator;
121 typedef std::vector<Node *>::const_iterator const_iterator;
122
123 unsigned getDFSNumIn() const { return DFSin; }
124 unsigned getDFSNumOut() const { return DFSout; }
125
126 BasicBlock *getBlock() const { return BB; }
127
128 iterator begin() { return Children.begin(); }
129 iterator end() { return Children.end(); }
130
131 const_iterator begin() const { return Children.begin(); }
132 const_iterator end() const { return Children.end(); }
133
134 bool dominates(const Node *N) const {
135 return DFSin <= N->DFSin && DFSout >= N->DFSout;
136 }
137
138 bool DominatedBy(const Node *N) const {
139 return N->dominates(this);
140 }
141
142 /// Sorts by the number of descendants. With this, you can iterate
143 /// through a sorted list and the first matching entry is the most
144 /// specific match for your basic block. The order provided is stable;
145 /// DomTreeDFS::Nodes with the same number of descendants are sorted by
146 /// DFS in number.
147 bool operator<(const Node &N) const {
148 unsigned spread = DFSout - DFSin;
149 unsigned N_spread = N.DFSout - N.DFSin;
150 if (spread == N_spread) return DFSin < N.DFSin;
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
214 Node *getRootNode() const { return Entry; }
215
216 Node *getNodeForBlock(BasicBlock *BB) const {
217 if (!NodeMap.count(BB)) return 0;
Nick Lewycky73dd6922007-07-05 03:15:00 +0000218 return const_cast<DomTreeDFS*>(this)->NodeMap[BB];
Nick Lewycky26e25d32007-06-24 04:36:20 +0000219 }
220
221 bool dominates(Instruction *I1, Instruction *I2) {
222 BasicBlock *BB1 = I1->getParent(),
223 *BB2 = I2->getParent();
224 if (BB1 == BB2) {
225 if (isa<TerminatorInst>(I1)) return false;
226 if (isa<TerminatorInst>(I2)) return true;
227 if ( isa<PHINode>(I1) && !isa<PHINode>(I2)) return true;
228 if (!isa<PHINode>(I1) && isa<PHINode>(I2)) return false;
229
230 for (BasicBlock::const_iterator I = BB2->begin(), E = BB2->end();
231 I != E; ++I) {
232 if (&*I == I1) return true;
233 else if (&*I == I2) return false;
234 }
235 assert(!"Instructions not found in parent BasicBlock?");
236 } else {
Nick Lewycky0f986fd2007-06-24 04:40:16 +0000237 Node *Node1 = getNodeForBlock(BB1),
Nick Lewycky26e25d32007-06-24 04:36:20 +0000238 *Node2 = getNodeForBlock(BB2);
Nick Lewycky73dd6922007-07-05 03:15:00 +0000239 return Node1 && Node2 && Node1->dominates(Node2);
Nick Lewycky26e25d32007-06-24 04:36:20 +0000240 }
241 }
242 private:
243 void renumber() {
244 std::stack<std::pair<Node *, Node::iterator> > S;
245 unsigned n = 0;
246
247 Entry->DFSin = ++n;
248 S.push(std::make_pair(Entry, Entry->begin()));
249
250 while (!S.empty()) {
251 std::pair<Node *, Node::iterator> &Pair = S.top();
252 Node *N = Pair.first;
253 Node::iterator &I = Pair.second;
254
255 if (I == N->end()) {
256 N->DFSout = ++n;
257 S.pop();
258 } else {
259 Node *Next = *I++;
260 Next->DFSin = ++n;
261 S.push(std::make_pair(Next, Next->begin()));
262 }
263 }
264 }
265
266#ifndef NDEBUG
267 virtual void dump() const {
268 dump(*cerr.stream());
269 }
270
271 void dump(std::ostream &os) const {
272 os << "Predicate simplifier DomTreeDFS: \n";
273 dump(Entry, 0, os);
274 os << "\n\n";
275 }
276
277 void dump(Node *N, int depth, std::ostream &os) const {
278 ++depth;
279 for (int i = 0; i < depth; ++i) { os << " "; }
280 os << "[" << depth << "] ";
281
282 os << N->getBlock()->getName() << " (" << N->getDFSNumIn()
283 << ", " << N->getDFSNumOut() << ")\n";
284
285 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I)
286 dump(*I, depth, os);
287 }
288#endif
289
290 Node *Entry;
291 std::map<BasicBlock *, Node *> NodeMap;
292 };
293
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000294 // SLT SGT ULT UGT EQ
295 // 0 1 0 1 0 -- GT 10
296 // 0 1 0 1 1 -- GE 11
297 // 0 1 1 0 0 -- SGTULT 12
298 // 0 1 1 0 1 -- SGEULE 13
Nick Lewycky56639802007-01-29 02:56:54 +0000299 // 0 1 1 1 0 -- SGT 14
300 // 0 1 1 1 1 -- SGE 15
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000301 // 1 0 0 1 0 -- SLTUGT 18
302 // 1 0 0 1 1 -- SLEUGE 19
303 // 1 0 1 0 0 -- LT 20
304 // 1 0 1 0 1 -- LE 21
Nick Lewycky56639802007-01-29 02:56:54 +0000305 // 1 0 1 1 0 -- SLT 22
306 // 1 0 1 1 1 -- SLE 23
307 // 1 1 0 1 0 -- UGT 26
308 // 1 1 0 1 1 -- UGE 27
309 // 1 1 1 0 0 -- ULT 28
310 // 1 1 1 0 1 -- ULE 29
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000311 // 1 1 1 1 0 -- NE 30
312 enum LatticeBits {
313 EQ_BIT = 1, UGT_BIT = 2, ULT_BIT = 4, SGT_BIT = 8, SLT_BIT = 16
314 };
315 enum LatticeVal {
316 GT = SGT_BIT | UGT_BIT,
317 GE = GT | EQ_BIT,
318 LT = SLT_BIT | ULT_BIT,
319 LE = LT | EQ_BIT,
320 NE = SLT_BIT | SGT_BIT | ULT_BIT | UGT_BIT,
321 SGTULT = SGT_BIT | ULT_BIT,
322 SGEULE = SGTULT | EQ_BIT,
323 SLTUGT = SLT_BIT | UGT_BIT,
324 SLEUGE = SLTUGT | EQ_BIT,
Nick Lewycky56639802007-01-29 02:56:54 +0000325 ULT = SLT_BIT | SGT_BIT | ULT_BIT,
326 UGT = SLT_BIT | SGT_BIT | UGT_BIT,
327 SLT = SLT_BIT | ULT_BIT | UGT_BIT,
328 SGT = SGT_BIT | ULT_BIT | UGT_BIT,
329 SLE = SLT | EQ_BIT,
330 SGE = SGT | EQ_BIT,
331 ULE = ULT | EQ_BIT,
332 UGE = UGT | EQ_BIT
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000333 };
334
335 static bool validPredicate(LatticeVal LV) {
336 switch (LV) {
Nick Lewycky15245952007-02-04 23:43:05 +0000337 case GT: case GE: case LT: case LE: case NE:
338 case SGTULT: case SGT: case SGEULE:
339 case SLTUGT: case SLT: case SLEUGE:
340 case ULT: case UGT:
341 case SLE: case SGE: case ULE: case UGE:
342 return true;
343 default:
344 return false;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000345 }
346 }
347
348 /// reversePredicate - reverse the direction of the inequality
349 static LatticeVal reversePredicate(LatticeVal LV) {
350 unsigned reverse = LV ^ (SLT_BIT|SGT_BIT|ULT_BIT|UGT_BIT); //preserve EQ_BIT
Nick Lewycky4f73de22007-03-16 02:37:39 +0000351
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000352 if ((reverse & (SLT_BIT|SGT_BIT)) == 0)
353 reverse |= (SLT_BIT|SGT_BIT);
354
355 if ((reverse & (ULT_BIT|UGT_BIT)) == 0)
356 reverse |= (ULT_BIT|UGT_BIT);
357
358 LatticeVal Rev = static_cast<LatticeVal>(reverse);
359 assert(validPredicate(Rev) && "Failed reversing predicate.");
360 return Rev;
361 }
362
Nick Lewycky73dd6922007-07-05 03:15:00 +0000363 /// ValueNumbering stores the scope-specific value numbers for a given Value.
364 class VISIBILITY_HIDDEN ValueNumbering {
365 class VISIBILITY_HIDDEN VNPair {
366 public:
367 Value *V;
368 unsigned index;
369 DomTreeDFS::Node *Subtree;
370
371 VNPair(Value *V, unsigned index, DomTreeDFS::Node *Subtree)
372 : V(V), index(index), Subtree(Subtree) {}
373
374 bool operator==(const VNPair &RHS) const {
375 return V == RHS.V && Subtree == RHS.Subtree;
376 }
377
378 bool operator<(const VNPair &RHS) const {
379 if (V != RHS.V) return V < RHS.V;
380 return *Subtree < *RHS.Subtree;
381 }
382
383 bool operator<(Value *RHS) const {
384 return V < RHS;
385 }
386 };
387
388 typedef std::vector<VNPair> VNMapType;
389 VNMapType VNMap;
390
391 std::vector<Value *> Values;
392
393 DomTreeDFS *DTDFS;
394
395 public:
396 /// compare - returns true if V1 is a better canonical value than V2.
397 bool compare(Value *V1, Value *V2) const {
398 if (isa<Constant>(V1))
399 return !isa<Constant>(V2);
400 else if (isa<Constant>(V2))
401 return false;
402 else if (isa<Argument>(V1))
403 return !isa<Argument>(V2);
404 else if (isa<Argument>(V2))
405 return false;
406
407 Instruction *I1 = dyn_cast<Instruction>(V1);
408 Instruction *I2 = dyn_cast<Instruction>(V2);
409
410 if (!I1 || !I2)
411 return V1->getNumUses() < V2->getNumUses();
412
413 return DTDFS->dominates(I1, I2);
414 }
415
416 ValueNumbering(DomTreeDFS *DTDFS) : DTDFS(DTDFS) {}
417
418 /// valueNumber - finds the value number for V under the Subtree. If
419 /// there is no value number, returns zero.
420 unsigned valueNumber(Value *V, DomTreeDFS::Node *Subtree) {
421 VNMapType::iterator E = VNMap.end();
422 VNPair pair(V, 0, Subtree);
423 VNMapType::iterator I = std::lower_bound(VNMap.begin(), E, pair);
424 while (I != E && I->V == V) {
425 if (I->Subtree->dominates(Subtree))
426 return I->index;
427 ++I;
428 }
429 return 0;
430 }
431
432 /// newVN - creates a new value number. Value V must not already have a
433 /// value number assigned.
434 unsigned newVN(Value *V) {
435 Values.push_back(V);
436
437 VNPair pair = VNPair(V, Values.size(), DTDFS->getRootNode());
438 assert(!std::binary_search(VNMap.begin(), VNMap.end(), pair) &&
439 "Attempt to create a duplicate value number.");
440 VNMap.insert(std::lower_bound(VNMap.begin(), VNMap.end(), pair), pair);
441
442 return Values.size();
443 }
444
445 /// value - returns the Value associated with a value number.
446 Value *value(unsigned index) const {
447 assert(index != 0 && "Zero index is reserved for not found.");
448 assert(index <= Values.size() && "Index out of range.");
449 return Values[index-1];
450 }
451
452 /// canonicalize - return a Value that is equal to V under Subtree.
453 Value *canonicalize(Value *V, DomTreeDFS::Node *Subtree) {
454 if (isa<Constant>(V)) return V;
455
456 if (unsigned n = valueNumber(V, Subtree))
457 return value(n);
458 else
459 return V;
460 }
461
462 /// addEquality - adds that value V belongs to the set of equivalent
463 /// values defined by value number n under Subtree.
464 void addEquality(unsigned n, Value *V, DomTreeDFS::Node *Subtree) {
465 assert(canonicalize(value(n), Subtree) == value(n) &&
466 "Node's 'canonical' choice isn't best within this subtree.");
467
468 // Suppose that we are given "%x -> node #1 (%y)". The problem is that
469 // we may already have "%z -> node #2 (%x)" somewhere above us in the
470 // graph. We need to find those edges and add "%z -> node #1 (%y)"
471 // to keep the lookups canonical.
472
473 std::vector<Value *> ToRepoint(1, V);
474
475 if (unsigned Conflict = valueNumber(V, Subtree)) {
476 for (VNMapType::iterator I = VNMap.begin(), E = VNMap.end();
477 I != E; ++I) {
478 if (I->index == Conflict && I->Subtree->dominates(Subtree))
479 ToRepoint.push_back(I->V);
480 }
481 }
482
483 for (std::vector<Value *>::iterator VI = ToRepoint.begin(),
484 VE = ToRepoint.end(); VI != VE; ++VI) {
485 Value *V = *VI;
486
487 VNPair pair(V, n, Subtree);
488 VNMapType::iterator B = VNMap.begin(), E = VNMap.end();
489 VNMapType::iterator I = std::lower_bound(B, E, pair);
490 if (I != E && I->V == V && I->Subtree == Subtree)
491 I->index = n; // Update best choice
492 else
493 VNMap.insert(I, pair); // New Value
494
495 // XXX: we currently don't have to worry about updating values with
496 // more specific Subtrees, but we will need to for PHI node support.
497
498#ifndef NDEBUG
499 Value *V_n = value(n);
500 if (isa<Constant>(V) && isa<Constant>(V_n)) {
501 assert(V == V_n && "Constant equals different constant?");
502 }
503#endif
504 }
505 }
506
507 /// remove - removes all references to value V.
508 void remove(Value *V) {
509 VNMapType::iterator B = VNMap.begin();
510 VNPair pair(V, 0, DTDFS->getRootNode());
511 VNMapType::iterator J = std::upper_bound(B, VNMap.end(), pair);
512 VNMapType::iterator I = J;
513
514 while (I != B && I->V == V) --I;
515
516 VNMap.erase(I, J);
517 }
518 };
519
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000520 /// The InequalityGraph stores the relationships between values.
521 /// Each Value in the graph is assigned to a Node. Nodes are pointer
522 /// comparable for equality. The caller is expected to maintain the logical
523 /// consistency of the system.
524 ///
525 /// The InequalityGraph class may invalidate Node*s after any mutator call.
526 /// @brief The InequalityGraph stores the relationships between values.
527 class VISIBILITY_HIDDEN InequalityGraph {
Nick Lewycky73dd6922007-07-05 03:15:00 +0000528 ValueNumbering &VN;
Nick Lewycky26e25d32007-06-24 04:36:20 +0000529 DomTreeDFS::Node *TreeRoot;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000530
531 InequalityGraph(); // DO NOT IMPLEMENT
532 InequalityGraph(InequalityGraph &); // DO NOT IMPLEMENT
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000533 public:
Nick Lewycky73dd6922007-07-05 03:15:00 +0000534 InequalityGraph(ValueNumbering &VN, DomTreeDFS::Node *TreeRoot)
535 : VN(VN), TreeRoot(TreeRoot) {}
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000536
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000537 class Node;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000538
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000539 /// An Edge is contained inside a Node making one end of the edge implicit
540 /// and contains a pointer to the other end. The edge contains a lattice
Nick Lewycky26e25d32007-06-24 04:36:20 +0000541 /// value specifying the relationship and an DomTreeDFS::Node specifying
542 /// the root in the dominator tree to which this edge applies.
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000543 class VISIBILITY_HIDDEN Edge {
544 public:
Nick Lewycky26e25d32007-06-24 04:36:20 +0000545 Edge(unsigned T, LatticeVal V, DomTreeDFS::Node *ST)
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000546 : To(T), LV(V), Subtree(ST) {}
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000547
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000548 unsigned To;
549 LatticeVal LV;
Nick Lewycky26e25d32007-06-24 04:36:20 +0000550 DomTreeDFS::Node *Subtree;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000551
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000552 bool operator<(const Edge &edge) const {
553 if (To != edge.To) return To < edge.To;
Nick Lewycky73dd6922007-07-05 03:15:00 +0000554 return *Subtree < *edge.Subtree;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000555 }
Nick Lewycky26e25d32007-06-24 04:36:20 +0000556
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000557 bool operator<(unsigned to) const {
558 return To < to;
559 }
Nick Lewycky26e25d32007-06-24 04:36:20 +0000560
Bill Wendling6357bf22007-06-04 23:52:59 +0000561 bool operator>(unsigned to) const {
562 return To > to;
563 }
564
565 friend bool operator<(unsigned to, const Edge &edge) {
566 return edge.operator>(to);
567 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000568 };
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000569
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000570 /// A single node in the InequalityGraph. This stores the canonical Value
571 /// for the node, as well as the relationships with the neighbours.
572 ///
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000573 /// @brief A single node in the InequalityGraph.
574 class VISIBILITY_HIDDEN Node {
575 friend class InequalityGraph;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000576
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000577 typedef SmallVector<Edge, 4> RelationsType;
578 RelationsType Relations;
579
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000580 // TODO: can this idea improve performance?
581 //friend class std::vector<Node>;
582 //Node(Node &N) { RelationsType.swap(N.RelationsType); }
583
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000584 public:
585 typedef RelationsType::iterator iterator;
586 typedef RelationsType::const_iterator const_iterator;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000587
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000588#ifndef NDEBUG
Nick Lewycky5d6ede52007-01-11 02:38:21 +0000589 virtual ~Node() {}
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000590 virtual void dump() const {
591 dump(*cerr.stream());
592 }
593 private:
Nick Lewycky73dd6922007-07-05 03:15:00 +0000594 void dump(std::ostream &os) const {
595 static const std::string names[32] =
596 { "000000", "000001", "000002", "000003", "000004", "000005",
597 "000006", "000007", "000008", "000009", " >", " >=",
598 " s>u<", "s>=u<=", " s>", " s>=", "000016", "000017",
599 " s<u>", "s<=u>=", " <", " <=", " s<", " s<=",
600 "000024", "000025", " u>", " u>=", " u<", " u<=",
601 " !=", "000031" };
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000602 for (Node::const_iterator NI = begin(), NE = end(); NI != NE; ++NI) {
Nick Lewycky73dd6922007-07-05 03:15:00 +0000603 os << names[NI->LV] << " " << NI->To
604 << " (" << NI->Subtree->getDFSNumIn() << ")";
605 if (NI != NE) os << ", ";
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000606 }
607 }
Nick Lewycky73dd6922007-07-05 03:15:00 +0000608 public:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000609#endif
610
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000611 iterator begin() { return Relations.begin(); }
612 iterator end() { return Relations.end(); }
613 const_iterator begin() const { return Relations.begin(); }
614 const_iterator end() const { return Relations.end(); }
615
Nick Lewycky26e25d32007-06-24 04:36:20 +0000616 iterator find(unsigned n, DomTreeDFS::Node *Subtree) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000617 iterator E = end();
618 for (iterator I = std::lower_bound(begin(), E, n);
619 I != E && I->To == n; ++I) {
620 if (Subtree->DominatedBy(I->Subtree))
621 return I;
622 }
623 return E;
624 }
625
Nick Lewycky26e25d32007-06-24 04:36:20 +0000626 const_iterator find(unsigned n, DomTreeDFS::Node *Subtree) const {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000627 const_iterator E = end();
628 for (const_iterator I = std::lower_bound(begin(), E, n);
629 I != E && I->To == n; ++I) {
630 if (Subtree->DominatedBy(I->Subtree))
631 return I;
632 }
633 return E;
634 }
635
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000636 /// Updates the lattice value for a given node. Create a new entry if
637 /// one doesn't exist, otherwise it merges the values. The new lattice
638 /// value must not be inconsistent with any previously existing value.
Nick Lewycky26e25d32007-06-24 04:36:20 +0000639 void update(unsigned n, LatticeVal R, DomTreeDFS::Node *Subtree) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000640 assert(validPredicate(R) && "Invalid predicate.");
641 iterator I = find(n, Subtree);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000642 if (I == end()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000643 Edge edge(n, R, Subtree);
644 iterator Insert = std::lower_bound(begin(), end(), edge);
645 Relations.insert(Insert, edge);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000646 } else {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000647 LatticeVal LV = static_cast<LatticeVal>(I->LV & R);
648 assert(validPredicate(LV) && "Invalid union of lattice values.");
649 if (LV != I->LV) {
Nick Lewycky6ce36cf2007-01-15 14:30:07 +0000650 if (Subtree != I->Subtree) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000651 assert(Subtree->DominatedBy(I->Subtree) &&
652 "Find returned subtree that doesn't apply.");
653
654 Edge edge(n, R, Subtree);
655 iterator Insert = std::lower_bound(begin(), end(), edge);
Nick Lewycky6ce36cf2007-01-15 14:30:07 +0000656 Relations.insert(Insert, edge); // invalidates I
657 I = find(n, Subtree);
658 }
659
660 // Also, we have to tighten any edge that Subtree dominates.
661 for (iterator B = begin(); I->To == n; --I) {
662 if (I->Subtree->DominatedBy(Subtree)) {
663 LatticeVal LV = static_cast<LatticeVal>(I->LV & R);
Chris Lattner28d921d2007-04-14 23:32:02 +0000664 assert(validPredicate(LV) && "Invalid union of lattice values");
Nick Lewycky6ce36cf2007-01-15 14:30:07 +0000665 I->LV = LV;
666 }
667 if (I == B) break;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000668 }
669 }
Nick Lewycky51ce8d62006-09-13 19:24:01 +0000670 }
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000671 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000672 };
673
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000674 private:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000675
676 std::vector<Node> Nodes;
677
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000678 public:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000679 /// node - returns the node object at a given index retrieved from getNode.
680 /// Index zero is reserved and may not be passed in here. The pointer
681 /// returned is valid until the next call to newNode or getOrInsertNode.
682 Node *node(unsigned index) {
683 assert(index != 0 && "Zero index is reserved for not found.");
684 assert(index <= Nodes.size() && "Index out of range.");
685 return &Nodes[index-1];
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000686 }
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000687
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000688 /// newNode - creates a new node for a given Value and returns the index.
689 unsigned newNode(Value *V) {
Nick Lewycky73dd6922007-07-05 03:15:00 +0000690 assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
691 "Bad Value for node.");
Nick Lewycky26e25d32007-06-24 04:36:20 +0000692 assert(V->getType() != Type::VoidTy && "Void node?");
693
Nick Lewycky73dd6922007-07-05 03:15:00 +0000694 unsigned n = VN.newVN(V);
695 if (Nodes.size() < n) Nodes.resize(n);
696 return n;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000697 }
698
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000699 /// isRelatedBy - true iff n1 op n2
Nick Lewycky26e25d32007-06-24 04:36:20 +0000700 bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
701 LatticeVal LV) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000702 if (n1 == n2) return LV & EQ_BIT;
703
704 Node *N1 = node(n1);
705 Node::iterator I = N1->find(n2, Subtree), E = N1->end();
706 if (I != E) return (I->LV & LV) == I->LV;
707
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000708 return false;
709 }
710
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000711 // The add* methods assume that your input is logically valid and may
712 // assertion-fail or infinitely loop if you attempt a contradiction.
Nick Lewycky9d17c822006-10-25 23:48:24 +0000713
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000714 /// addInequality - Sets n1 op n2.
715 /// It is also an error to call this on an inequality that is already true.
Nick Lewycky26e25d32007-06-24 04:36:20 +0000716 void addInequality(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000717 LatticeVal LV1) {
718 assert(n1 != n2 && "A node can't be inequal to itself.");
719
720 if (LV1 != NE)
721 assert(!isRelatedBy(n1, n2, Subtree, reversePredicate(LV1)) &&
722 "Contradictory inequality.");
723
724 Node *N1 = node(n1);
725 Node *N2 = node(n2);
726
727 // Suppose we're adding %n1 < %n2. Find all the %a < %n1 and
728 // add %a < %n2 too. This keeps the graph fully connected.
729 if (LV1 != NE) {
Nick Lewycky3bb6de82007-04-07 03:36:51 +0000730 // Break up the relationship into signed and unsigned comparison parts.
731 // If the signed parts of %a op1 %n1 match that of %n1 op2 %n2, and
732 // op1 and op2 aren't NE, then add %a op3 %n2. The new relationship
733 // should have the EQ_BIT iff it's set for both op1 and op2.
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000734
735 unsigned LV1_s = LV1 & (SLT_BIT|SGT_BIT);
736 unsigned LV1_u = LV1 & (ULT_BIT|UGT_BIT);
Nick Lewycky3bb6de82007-04-07 03:36:51 +0000737
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000738 for (Node::iterator I = N1->begin(), E = N1->end(); I != E; ++I) {
739 if (I->LV != NE && I->To != n2) {
Nick Lewycky3bb6de82007-04-07 03:36:51 +0000740
Nick Lewycky26e25d32007-06-24 04:36:20 +0000741 DomTreeDFS::Node *Local_Subtree = NULL;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000742 if (Subtree->DominatedBy(I->Subtree))
743 Local_Subtree = Subtree;
744 else if (I->Subtree->DominatedBy(Subtree))
745 Local_Subtree = I->Subtree;
746
747 if (Local_Subtree) {
748 unsigned new_relationship = 0;
749 LatticeVal ILV = reversePredicate(I->LV);
750 unsigned ILV_s = ILV & (SLT_BIT|SGT_BIT);
751 unsigned ILV_u = ILV & (ULT_BIT|UGT_BIT);
752
753 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
754 new_relationship |= ILV_s;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000755 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
756 new_relationship |= ILV_u;
757
758 if (new_relationship) {
759 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
760 new_relationship |= (SLT_BIT|SGT_BIT);
761 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
762 new_relationship |= (ULT_BIT|UGT_BIT);
763 if ((LV1 & EQ_BIT) && (ILV & EQ_BIT))
764 new_relationship |= EQ_BIT;
765
766 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
767
768 node(I->To)->update(n2, NewLV, Local_Subtree);
769 N2->update(I->To, reversePredicate(NewLV), Local_Subtree);
770 }
771 }
772 }
773 }
774
775 for (Node::iterator I = N2->begin(), E = N2->end(); I != E; ++I) {
776 if (I->LV != NE && I->To != n1) {
Nick Lewycky26e25d32007-06-24 04:36:20 +0000777 DomTreeDFS::Node *Local_Subtree = NULL;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000778 if (Subtree->DominatedBy(I->Subtree))
779 Local_Subtree = Subtree;
780 else if (I->Subtree->DominatedBy(Subtree))
781 Local_Subtree = I->Subtree;
782
783 if (Local_Subtree) {
784 unsigned new_relationship = 0;
785 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
786 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
787
788 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
789 new_relationship |= ILV_s;
790
791 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
792 new_relationship |= ILV_u;
793
794 if (new_relationship) {
795 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
796 new_relationship |= (SLT_BIT|SGT_BIT);
797 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
798 new_relationship |= (ULT_BIT|UGT_BIT);
799 if ((LV1 & EQ_BIT) && (I->LV & EQ_BIT))
800 new_relationship |= EQ_BIT;
801
802 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
803
804 N1->update(I->To, NewLV, Local_Subtree);
805 node(I->To)->update(n1, reversePredicate(NewLV), Local_Subtree);
806 }
807 }
808 }
809 }
810 }
811
812 N1->update(n2, LV1, Subtree);
813 N2->update(n1, reversePredicate(LV1), Subtree);
814 }
Nick Lewycky51ce8d62006-09-13 19:24:01 +0000815
Nick Lewycky73dd6922007-07-05 03:15:00 +0000816 /// remove - removes a node from the graph by removing all references to
817 /// and from it.
818 void remove(unsigned n) {
819 Node *N = node(n);
820 for (Node::iterator NI = N->begin(), NE = N->end(); NI != NE; ++NI) {
821 Node::iterator Iter = node(NI->To)->find(n, TreeRoot);
822 do {
823 node(NI->To)->Relations.erase(Iter);
824 Iter = node(NI->To)->find(n, TreeRoot);
825 } while (Iter != node(NI->To)->end());
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000826 }
Nick Lewycky73dd6922007-07-05 03:15:00 +0000827 N->Relations.clear();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000828 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000829
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000830#ifndef NDEBUG
Nick Lewycky5d6ede52007-01-11 02:38:21 +0000831 virtual ~InequalityGraph() {}
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000832 virtual void dump() {
833 dump(*cerr.stream());
834 }
835
836 void dump(std::ostream &os) {
Nick Lewycky73dd6922007-07-05 03:15:00 +0000837 for (unsigned i = 1; i <= Nodes.size(); ++i) {
838 os << i << " = {";
839 node(i)->dump(os);
840 os << "}\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000841 }
842 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000843#endif
844 };
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000845
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000846 class VRPSolver;
847
848 /// ValueRanges tracks the known integer ranges and anti-ranges of the nodes
849 /// in the InequalityGraph.
850 class VISIBILITY_HIDDEN ValueRanges {
851
852 /// A ScopedRange ties an InequalityGraph node with a ConstantRange under
853 /// the scope of a rooted subtree in the dominator tree.
854 class VISIBILITY_HIDDEN ScopedRange {
855 public:
Nick Lewycky26e25d32007-06-24 04:36:20 +0000856 ScopedRange(Value *V, ConstantRange CR, DomTreeDFS::Node *ST)
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000857 : V(V), CR(CR), Subtree(ST) {}
858
859 Value *V;
860 ConstantRange CR;
Nick Lewycky26e25d32007-06-24 04:36:20 +0000861 DomTreeDFS::Node *Subtree;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000862
863 bool operator<(const ScopedRange &range) const {
864 if (V != range.V) return V < range.V;
Nick Lewycky73dd6922007-07-05 03:15:00 +0000865 return *Subtree < *range.Subtree;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000866 }
867
868 bool operator<(const Value *value) const {
869 return V < value;
870 }
Bill Wendling6357bf22007-06-04 23:52:59 +0000871
872 bool operator>(const Value *value) const {
873 return V > value;
874 }
875
876 friend bool operator<(const Value *value, const ScopedRange &range) {
877 return range.operator>(value);
878 }
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000879 };
880
Nick Lewycky12d44ab2007-04-07 03:16:12 +0000881 TargetData *TD;
882
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000883 std::vector<ScopedRange> Ranges;
884 typedef std::vector<ScopedRange>::iterator iterator;
885
886 // XXX: this is a copy of the code in InequalityGraph::Node. Perhaps a
887 // intrusive domtree-scoped container is in order?
888
889 iterator begin() { return Ranges.begin(); }
890 iterator end() { return Ranges.end(); }
891
Nick Lewycky26e25d32007-06-24 04:36:20 +0000892 iterator find(Value *V, DomTreeDFS::Node *Subtree) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000893 iterator E = end();
894 for (iterator I = std::lower_bound(begin(), E, V);
895 I != E && I->V == V; ++I) {
896 if (Subtree->DominatedBy(I->Subtree))
897 return I;
898 }
899 return E;
900 }
901
Nick Lewycky26e25d32007-06-24 04:36:20 +0000902 void update(Value *V, ConstantRange CR, DomTreeDFS::Node *Subtree) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000903 assert(!CR.isEmptySet() && "Empty ConstantRange!");
904 if (CR.isFullSet()) return;
905
906 iterator I = find(V, Subtree);
907 if (I == end()) {
908 ScopedRange range(V, CR, Subtree);
909 iterator Insert = std::lower_bound(begin(), end(), range);
910 Ranges.insert(Insert, range);
911 } else {
912 CR = CR.intersectWith(I->CR);
913 assert(!CR.isEmptySet() && "Empty intersection of ConstantRanges!");
914
915 if (CR != I->CR) {
916 if (Subtree != I->Subtree) {
917 assert(Subtree->DominatedBy(I->Subtree) &&
918 "Find returned subtree that doesn't apply.");
919
920 ScopedRange range(V, CR, Subtree);
921 iterator Insert = std::lower_bound(begin(), end(), range);
922 Ranges.insert(Insert, range); // invalidates I
923 I = find(V, Subtree);
924 }
925
926 // Also, we have to tighten any edge that Subtree dominates.
927 for (iterator B = begin(); I->V == V; --I) {
928 if (I->Subtree->DominatedBy(Subtree)) {
Nick Lewycky3bb6de82007-04-07 03:36:51 +0000929 I->CR = CR.intersectWith(I->CR);
930 assert(!I->CR.isEmptySet() &&
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000931 "Empty intersection of ConstantRanges!");
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000932 }
933 if (I == B) break;
934 }
935 }
936 }
937 }
938
939 /// range - Creates a ConstantRange representing the set of all values
940 /// that match the ICmpInst::Predicate with any of the values in CR.
941 ConstantRange range(ICmpInst::Predicate ICmpOpcode,
942 const ConstantRange &CR) {
943 uint32_t W = CR.getBitWidth();
944 switch (ICmpOpcode) {
945 default: assert(!"Invalid ICmp opcode to range()");
946 case ICmpInst::ICMP_EQ:
947 return ConstantRange(CR.getLower(), CR.getUpper());
948 case ICmpInst::ICMP_NE:
949 if (CR.isSingleElement())
950 return ConstantRange(CR.getUpper(), CR.getLower());
951 return ConstantRange(W);
952 case ICmpInst::ICMP_ULT:
953 return ConstantRange(APInt::getMinValue(W), CR.getUnsignedMax());
954 case ICmpInst::ICMP_SLT:
955 return ConstantRange(APInt::getSignedMinValue(W), CR.getSignedMax());
956 case ICmpInst::ICMP_ULE: {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +0000957 APInt UMax(CR.getUnsignedMax());
Zhou Sheng31787362007-04-26 16:42:07 +0000958 if (UMax.isMaxValue())
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000959 return ConstantRange(W);
960 return ConstantRange(APInt::getMinValue(W), UMax + 1);
961 }
962 case ICmpInst::ICMP_SLE: {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +0000963 APInt SMax(CR.getSignedMax());
Zhou Sheng31787362007-04-26 16:42:07 +0000964 if (SMax.isMaxSignedValue() || (SMax+1).isMaxSignedValue())
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000965 return ConstantRange(W);
966 return ConstantRange(APInt::getSignedMinValue(W), SMax + 1);
967 }
968 case ICmpInst::ICMP_UGT:
Zhou Sheng82fcf3c2007-04-19 05:35:00 +0000969 return ConstantRange(CR.getUnsignedMin() + 1, APInt::getNullValue(W));
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000970 case ICmpInst::ICMP_SGT:
971 return ConstantRange(CR.getSignedMin() + 1,
Zhou Sheng82fcf3c2007-04-19 05:35:00 +0000972 APInt::getSignedMinValue(W));
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000973 case ICmpInst::ICMP_UGE: {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +0000974 APInt UMin(CR.getUnsignedMin());
Zhou Sheng31787362007-04-26 16:42:07 +0000975 if (UMin.isMinValue())
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000976 return ConstantRange(W);
Zhou Sheng82fcf3c2007-04-19 05:35:00 +0000977 return ConstantRange(UMin, APInt::getNullValue(W));
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000978 }
979 case ICmpInst::ICMP_SGE: {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +0000980 APInt SMin(CR.getSignedMin());
Zhou Sheng31787362007-04-26 16:42:07 +0000981 if (SMin.isMinSignedValue())
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000982 return ConstantRange(W);
Zhou Sheng82fcf3c2007-04-19 05:35:00 +0000983 return ConstantRange(SMin, APInt::getSignedMinValue(W));
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000984 }
985 }
986 }
987
988 /// create - Creates a ConstantRange that matches the given LatticeVal
989 /// relation with a given integer.
990 ConstantRange create(LatticeVal LV, const ConstantRange &CR) {
991 assert(!CR.isEmptySet() && "Can't deal with empty set.");
992
993 if (LV == NE)
994 return range(ICmpInst::ICMP_NE, CR);
995
996 unsigned LV_s = LV & (SGT_BIT|SLT_BIT);
997 unsigned LV_u = LV & (UGT_BIT|ULT_BIT);
998 bool hasEQ = LV & EQ_BIT;
999
1000 ConstantRange Range(CR.getBitWidth());
1001
1002 if (LV_s == SGT_BIT) {
1003 Range = Range.intersectWith(range(
1004 hasEQ ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_SGT, CR));
1005 } else if (LV_s == SLT_BIT) {
1006 Range = Range.intersectWith(range(
1007 hasEQ ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_SLT, CR));
1008 }
1009
1010 if (LV_u == UGT_BIT) {
1011 Range = Range.intersectWith(range(
1012 hasEQ ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_UGT, CR));
1013 } else if (LV_u == ULT_BIT) {
1014 Range = Range.intersectWith(range(
1015 hasEQ ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT, CR));
1016 }
1017
1018 return Range;
1019 }
1020
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001021#ifndef NDEBUG
Nick Lewycky26e25d32007-06-24 04:36:20 +00001022 bool isCanonical(Value *V, DomTreeDFS::Node *Subtree, VRPSolver *VRP);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001023#endif
1024
1025 public:
1026
1027 explicit ValueRanges(TargetData *TD) : TD(TD) {}
1028
Nick Lewycky12d44ab2007-04-07 03:16:12 +00001029 // rangeFromValue - converts a Value into a range. If the value is a
1030 // constant it constructs the single element range, otherwise it performs
1031 // a lookup. The width W must be retrieved from typeToWidth and may not
1032 // be zero.
Nick Lewycky26e25d32007-06-24 04:36:20 +00001033 ConstantRange rangeFromValue(Value *V, DomTreeDFS::Node *Subtree,
1034 uint32_t W) {
Nick Lewycky12d44ab2007-04-07 03:16:12 +00001035 if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001036 return ConstantRange(C->getValue());
Nick Lewycky12d44ab2007-04-07 03:16:12 +00001037 } else if (isa<ConstantPointerNull>(V)) {
1038 return ConstantRange(APInt::getNullValue(W));
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001039 } else {
1040 iterator I = find(V, Subtree);
1041 if (I != end())
1042 return I->CR;
1043 }
1044 return ConstantRange(W);
1045 }
1046
Nick Lewycky12d44ab2007-04-07 03:16:12 +00001047 // typeToWidth - returns the number of bits necessary to store a value of
1048 // this type, or zero if unknown.
1049 uint32_t typeToWidth(const Type *Ty) const {
1050 if (TD)
1051 return TD->getTypeSizeInBits(Ty);
1052
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001053 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
1054 return ITy->getBitWidth();
1055
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001056 return 0;
1057 }
1058
Nick Lewycky26e25d32007-06-24 04:36:20 +00001059 bool isRelatedBy(Value *V1, Value *V2, DomTreeDFS::Node *Subtree,
1060 LatticeVal LV) {
Nick Lewycky12d44ab2007-04-07 03:16:12 +00001061 uint32_t W = typeToWidth(V1->getType());
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001062 if (!W) return false;
1063
1064 ConstantRange CR1 = rangeFromValue(V1, Subtree, W);
1065 ConstantRange CR2 = rangeFromValue(V2, Subtree, W);
1066
1067 // True iff all values in CR1 are LV to all values in CR2.
Nick Lewycky4f73de22007-03-16 02:37:39 +00001068 switch (LV) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001069 default: assert(!"Impossible lattice value!");
1070 case NE:
1071 return CR1.intersectWith(CR2).isEmptySet();
1072 case ULT:
1073 return CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
1074 case ULE:
1075 return CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
1076 case UGT:
1077 return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
1078 case UGE:
1079 return CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
1080 case SLT:
1081 return CR1.getSignedMax().slt(CR2.getSignedMin());
1082 case SLE:
1083 return CR1.getSignedMax().sle(CR2.getSignedMin());
1084 case SGT:
1085 return CR1.getSignedMin().sgt(CR2.getSignedMax());
1086 case SGE:
1087 return CR1.getSignedMin().sge(CR2.getSignedMax());
1088 case LT:
1089 return CR1.getUnsignedMax().ult(CR2.getUnsignedMin()) &&
1090 CR1.getSignedMax().slt(CR2.getUnsignedMin());
1091 case LE:
1092 return CR1.getUnsignedMax().ule(CR2.getUnsignedMin()) &&
1093 CR1.getSignedMax().sle(CR2.getUnsignedMin());
1094 case GT:
1095 return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax()) &&
1096 CR1.getSignedMin().sgt(CR2.getSignedMax());
1097 case GE:
1098 return CR1.getUnsignedMin().uge(CR2.getUnsignedMax()) &&
1099 CR1.getSignedMin().sge(CR2.getSignedMax());
1100 case SLTUGT:
1101 return CR1.getSignedMax().slt(CR2.getSignedMin()) &&
1102 CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
1103 case SLEUGE:
1104 return CR1.getSignedMax().sle(CR2.getSignedMin()) &&
1105 CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
1106 case SGTULT:
1107 return CR1.getSignedMin().sgt(CR2.getSignedMax()) &&
1108 CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
1109 case SGEULE:
1110 return CR1.getSignedMin().sge(CR2.getSignedMax()) &&
1111 CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
1112 }
1113 }
1114
Nick Lewycky3bb6de82007-04-07 03:36:51 +00001115 void addToWorklist(Value *V, Constant *C, ICmpInst::Predicate Pred,
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001116 VRPSolver *VRP);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001117 void markBlock(VRPSolver *VRP);
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001118
Nick Lewycky26e25d32007-06-24 04:36:20 +00001119 void mergeInto(Value **I, unsigned n, Value *New,
1120 DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001121 assert(isCanonical(New, Subtree, VRP) && "Best choice not canonical?");
1122
Nick Lewycky12d44ab2007-04-07 03:16:12 +00001123 uint32_t W = typeToWidth(New->getType());
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001124 if (!W) return;
1125
1126 ConstantRange CR_New = rangeFromValue(New, Subtree, W);
1127 ConstantRange Merged = CR_New;
1128
1129 for (; n != 0; ++I, --n) {
1130 ConstantRange CR_Kill = rangeFromValue(*I, Subtree, W);
1131 if (CR_Kill.isFullSet()) continue;
1132 Merged = Merged.intersectWith(CR_Kill);
1133 }
1134
1135 if (Merged.isFullSet() || Merged == CR_New) return;
1136
Nick Lewycky3bb6de82007-04-07 03:36:51 +00001137 applyRange(New, Merged, Subtree, VRP);
1138 }
1139
Nick Lewycky26e25d32007-06-24 04:36:20 +00001140 void applyRange(Value *V, const ConstantRange &CR,
1141 DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
Nick Lewycky3bb6de82007-04-07 03:36:51 +00001142 assert(isCanonical(V, Subtree, VRP) && "Value not canonical.");
1143
1144 if (const APInt *I = CR.getSingleElement()) {
1145 const Type *Ty = V->getType();
1146 if (Ty->isInteger()) {
1147 addToWorklist(V, ConstantInt::get(*I), ICmpInst::ICMP_EQ, VRP);
1148 return;
1149 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1150 assert(*I == 0 && "Pointer is null but not zero?");
1151 addToWorklist(V, ConstantPointerNull::get(PTy),
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001152 ICmpInst::ICMP_EQ, VRP);
Nick Lewycky3bb6de82007-04-07 03:36:51 +00001153 return;
1154 }
1155 }
1156
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001157 ConstantRange Merged = CR.intersectWith(
1158 rangeFromValue(V, Subtree, CR.getBitWidth()));
1159 if (Merged.isEmptySet()) {
1160 markBlock(VRP);
1161 return;
1162 }
1163
1164 update(V, Merged, Subtree);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001165 }
1166
Nick Lewycky26e25d32007-06-24 04:36:20 +00001167 void addNotEquals(Value *V1, Value *V2, DomTreeDFS::Node *Subtree,
1168 VRPSolver *VRP) {
Nick Lewycky93f54102007-04-07 04:49:12 +00001169 uint32_t W = typeToWidth(V1->getType());
1170 if (!W) return;
1171
1172 ConstantRange CR1 = rangeFromValue(V1, Subtree, W);
1173 ConstantRange CR2 = rangeFromValue(V2, Subtree, W);
1174
1175 if (const APInt *I = CR1.getSingleElement()) {
1176 if (CR2.isFullSet()) {
1177 ConstantRange NewCR2(CR1.getUpper(), CR1.getLower());
1178 applyRange(V2, NewCR2, Subtree, VRP);
1179 } else if (*I == CR2.getLower()) {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001180 APInt NewLower(CR2.getLower() + 1),
1181 NewUpper(CR2.getUpper());
Nick Lewycky93f54102007-04-07 04:49:12 +00001182 if (NewLower == NewUpper)
1183 NewLower = NewUpper = APInt::getMinValue(W);
1184
1185 ConstantRange NewCR2(NewLower, NewUpper);
1186 applyRange(V2, NewCR2, Subtree, VRP);
1187 } else if (*I == CR2.getUpper() - 1) {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001188 APInt NewLower(CR2.getLower()),
1189 NewUpper(CR2.getUpper() - 1);
Nick Lewycky93f54102007-04-07 04:49:12 +00001190 if (NewLower == NewUpper)
1191 NewLower = NewUpper = APInt::getMinValue(W);
1192
1193 ConstantRange NewCR2(NewLower, NewUpper);
1194 applyRange(V2, NewCR2, Subtree, VRP);
1195 }
1196 }
1197
1198 if (const APInt *I = CR2.getSingleElement()) {
1199 if (CR1.isFullSet()) {
1200 ConstantRange NewCR1(CR2.getUpper(), CR2.getLower());
1201 applyRange(V1, NewCR1, Subtree, VRP);
1202 } else if (*I == CR1.getLower()) {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001203 APInt NewLower(CR1.getLower() + 1),
1204 NewUpper(CR1.getUpper());
Nick Lewycky93f54102007-04-07 04:49:12 +00001205 if (NewLower == NewUpper)
1206 NewLower = NewUpper = APInt::getMinValue(W);
1207
1208 ConstantRange NewCR1(NewLower, NewUpper);
1209 applyRange(V1, NewCR1, Subtree, VRP);
1210 } else if (*I == CR1.getUpper() - 1) {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001211 APInt NewLower(CR1.getLower()),
1212 NewUpper(CR1.getUpper() - 1);
Nick Lewycky93f54102007-04-07 04:49:12 +00001213 if (NewLower == NewUpper)
1214 NewLower = NewUpper = APInt::getMinValue(W);
1215
1216 ConstantRange NewCR1(NewLower, NewUpper);
1217 applyRange(V1, NewCR1, Subtree, VRP);
1218 }
1219 }
1220 }
1221
Nick Lewycky26e25d32007-06-24 04:36:20 +00001222 void addInequality(Value *V1, Value *V2, DomTreeDFS::Node *Subtree,
1223 LatticeVal LV, VRPSolver *VRP) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001224 assert(!isRelatedBy(V1, V2, Subtree, LV) && "Asked to do useless work.");
1225
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001226 assert(isCanonical(V1, Subtree, VRP) && "Value not canonical.");
1227 assert(isCanonical(V2, Subtree, VRP) && "Value not canonical.");
1228
Nick Lewycky93f54102007-04-07 04:49:12 +00001229 if (LV == NE) {
1230 addNotEquals(V1, V2, Subtree, VRP);
1231 return;
1232 }
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001233
Nick Lewycky12d44ab2007-04-07 03:16:12 +00001234 uint32_t W = typeToWidth(V1->getType());
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001235 if (!W) return;
1236
1237 ConstantRange CR1 = rangeFromValue(V1, Subtree, W);
1238 ConstantRange CR2 = rangeFromValue(V2, Subtree, W);
1239
1240 if (!CR1.isSingleElement()) {
1241 ConstantRange NewCR1 = CR1.intersectWith(create(LV, CR2));
Nick Lewycky3bb6de82007-04-07 03:36:51 +00001242 if (NewCR1 != CR1)
1243 applyRange(V1, NewCR1, Subtree, VRP);
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001244 }
1245
1246 if (!CR2.isSingleElement()) {
1247 ConstantRange NewCR2 = CR2.intersectWith(create(reversePredicate(LV),
1248 CR1));
Nick Lewycky3bb6de82007-04-07 03:36:51 +00001249 if (NewCR2 != CR2)
1250 applyRange(V2, NewCR2, Subtree, VRP);
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001251 }
1252 }
1253 };
1254
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001255 /// UnreachableBlocks keeps tracks of blocks that are for one reason or
1256 /// another discovered to be unreachable. This is used to cull the graph when
1257 /// analyzing instructions, and to mark blocks with the "unreachable"
1258 /// terminator instruction after the function has executed.
1259 class VISIBILITY_HIDDEN UnreachableBlocks {
1260 private:
1261 std::vector<BasicBlock *> DeadBlocks;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001262
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001263 public:
1264 /// mark - mark a block as dead
1265 void mark(BasicBlock *BB) {
1266 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
1267 std::vector<BasicBlock *>::iterator I =
1268 std::lower_bound(DeadBlocks.begin(), E, BB);
1269
1270 if (I == E || *I != BB) DeadBlocks.insert(I, BB);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001271 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001272
1273 /// isDead - returns whether a block is known to be dead already
1274 bool isDead(BasicBlock *BB) {
1275 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
1276 std::vector<BasicBlock *>::iterator I =
1277 std::lower_bound(DeadBlocks.begin(), E, BB);
1278
1279 return I != E && *I == BB;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001280 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001281
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001282 /// kill - replace the dead blocks' terminator with an UnreachableInst.
1283 bool kill() {
1284 bool modified = false;
1285 for (std::vector<BasicBlock *>::iterator I = DeadBlocks.begin(),
1286 E = DeadBlocks.end(); I != E; ++I) {
1287 BasicBlock *BB = *I;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001288
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001289 DOUT << "unreachable block: " << BB->getName() << "\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001290
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001291 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
1292 SI != SE; ++SI) {
1293 BasicBlock *Succ = *SI;
1294 Succ->removePredecessor(BB);
Nick Lewycky9d17c822006-10-25 23:48:24 +00001295 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001296
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001297 TerminatorInst *TI = BB->getTerminator();
1298 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1299 TI->eraseFromParent();
1300 new UnreachableInst(BB);
1301 ++NumBlocks;
1302 modified = true;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001303 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001304 DeadBlocks.clear();
1305 return modified;
Nick Lewycky9d17c822006-10-25 23:48:24 +00001306 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001307 };
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001308
1309 /// VRPSolver keeps track of how changes to one variable affect other
1310 /// variables, and forwards changes along to the InequalityGraph. It
1311 /// also maintains the correct choice for "canonical" in the IG.
1312 /// @brief VRPSolver calculates inferences from a new relationship.
1313 class VISIBILITY_HIDDEN VRPSolver {
1314 private:
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001315 friend class ValueRanges;
1316
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001317 struct Operation {
1318 Value *LHS, *RHS;
1319 ICmpInst::Predicate Op;
1320
Nick Lewycky26e25d32007-06-24 04:36:20 +00001321 BasicBlock *ContextBB; // XXX use a DomTreeDFS::Node instead
Nick Lewycky42944462007-01-13 02:05:28 +00001322 Instruction *ContextInst;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001323 };
1324 std::deque<Operation> WorkList;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001325
Nick Lewycky73dd6922007-07-05 03:15:00 +00001326 ValueNumbering &VN;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001327 InequalityGraph &IG;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001328 UnreachableBlocks &UB;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001329 ValueRanges &VR;
Nick Lewycky26e25d32007-06-24 04:36:20 +00001330 DomTreeDFS *DTDFS;
1331 DomTreeDFS::Node *Top;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001332 BasicBlock *TopBB;
1333 Instruction *TopInst;
1334 bool &modified;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001335
1336 typedef InequalityGraph::Node Node;
1337
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001338 // below - true if the Instruction is dominated by the current context
1339 // block or instruction
1340 bool below(Instruction *I) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00001341 BasicBlock *BB = I->getParent();
1342 if (TopInst && TopInst->getParent() == BB) {
1343 if (isa<TerminatorInst>(TopInst)) return false;
1344 if (isa<TerminatorInst>(I)) return true;
1345 if ( isa<PHINode>(TopInst) && !isa<PHINode>(I)) return true;
1346 if (!isa<PHINode>(TopInst) && isa<PHINode>(I)) return false;
1347
1348 for (BasicBlock::const_iterator Iter = BB->begin(), E = BB->end();
1349 Iter != E; ++Iter) {
1350 if (&*Iter == TopInst) return true;
1351 else if (&*Iter == I) return false;
1352 }
1353 assert(!"Instructions not found in parent BasicBlock?");
1354 } else {
Nick Lewycky0f986fd2007-06-24 04:40:16 +00001355 DomTreeDFS::Node *Node = DTDFS->getNodeForBlock(BB);
Nick Lewycky26e25d32007-06-24 04:36:20 +00001356 if (!Node) return false;
1357 return Top->dominates(Node);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001358 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001359 }
1360
Nick Lewycky26e25d32007-06-24 04:36:20 +00001361 // aboveOrBelow - true if the Instruction either dominates or is dominated
1362 // by the current context block or instruction
1363 bool aboveOrBelow(Instruction *I) {
1364 BasicBlock *BB = I->getParent();
1365 DomTreeDFS::Node *Node = DTDFS->getNodeForBlock(BB);
1366 if (!Node) return false;
1367
1368 return Top == Node || Top->dominates(Node) || Node->dominates(Top);
1369 }
1370
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001371 bool makeEqual(Value *V1, Value *V2) {
1372 DOUT << "makeEqual(" << *V1 << ", " << *V2 << ")\n";
Nick Lewycky26e25d32007-06-24 04:36:20 +00001373 DOUT << "context is ";
1374 if (TopInst) DOUT << "I: " << *TopInst << "\n";
1375 else DOUT << "BB: " << TopBB->getName()
1376 << "(" << Top->getDFSNumIn() << ")\n";
Nick Lewycky9d17c822006-10-25 23:48:24 +00001377
Nick Lewycky12d44ab2007-04-07 03:16:12 +00001378 assert(V1->getType() == V2->getType() &&
1379 "Can't make two values with different types equal.");
1380
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001381 if (V1 == V2) return true;
Nick Lewycky9d17c822006-10-25 23:48:24 +00001382
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001383 if (isa<Constant>(V1) && isa<Constant>(V2))
1384 return false;
1385
Nick Lewycky73dd6922007-07-05 03:15:00 +00001386 unsigned n1 = VN.valueNumber(V1, Top), n2 = VN.valueNumber(V2, Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001387
1388 if (n1 && n2) {
1389 if (n1 == n2) return true;
1390 if (IG.isRelatedBy(n1, n2, Top, NE)) return false;
1391 }
1392
Nick Lewycky73dd6922007-07-05 03:15:00 +00001393 if (n1) assert(V1 == VN.value(n1) && "Value isn't canonical.");
1394 if (n2) assert(V2 == VN.value(n2) && "Value isn't canonical.");
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001395
Nick Lewycky73dd6922007-07-05 03:15:00 +00001396 assert(!VN.compare(V2, V1) && "Please order parameters to makeEqual.");
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001397
1398 assert(!isa<Constant>(V2) && "Tried to remove a constant.");
1399
1400 SetVector<unsigned> Remove;
1401 if (n2) Remove.insert(n2);
1402
1403 if (n1 && n2) {
1404 // Suppose we're being told that %x == %y, and %x <= %z and %y >= %z.
1405 // We can't just merge %x and %y because the relationship with %z would
1406 // be EQ and that's invalid. What we're doing is looking for any nodes
1407 // %z such that %x <= %z and %y >= %z, and vice versa.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001408
1409 Node *N1 = IG.node(n1);
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001410 Node *N2 = IG.node(n2);
1411 Node::iterator end = N2->end();
1412
1413 // Find the intersection between N1 and N2 which is dominated by
1414 // Top. If we find %x where N1 <= %x <= N2 (or >=) then add %x to
1415 // Remove.
1416 for (Node::iterator I = N1->begin(), E = N1->end(); I != E; ++I) {
1417 if (!(I->LV & EQ_BIT) || !Top->DominatedBy(I->Subtree)) continue;
1418
1419 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
1420 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
1421 Node::iterator NI = N2->find(I->To, Top);
1422 if (NI != end) {
1423 LatticeVal NILV = reversePredicate(NI->LV);
1424 unsigned NILV_s = NILV & (SLT_BIT|SGT_BIT);
1425 unsigned NILV_u = NILV & (ULT_BIT|UGT_BIT);
1426
1427 if ((ILV_s != (SLT_BIT|SGT_BIT) && ILV_s == NILV_s) ||
1428 (ILV_u != (ULT_BIT|UGT_BIT) && ILV_u == NILV_u))
1429 Remove.insert(I->To);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001430 }
1431 }
1432
1433 // See if one of the nodes about to be removed is actually a better
1434 // canonical choice than n1.
1435 unsigned orig_n1 = n1;
Reid Spencera8a15472007-01-17 02:23:37 +00001436 SetVector<unsigned>::iterator DontRemove = Remove.end();
1437 for (SetVector<unsigned>::iterator I = Remove.begin()+1 /* skip n2 */,
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001438 E = Remove.end(); I != E; ++I) {
1439 unsigned n = *I;
Nick Lewycky73dd6922007-07-05 03:15:00 +00001440 Value *V = VN.value(n);
1441 if (VN.compare(V, V1)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001442 V1 = V;
1443 n1 = n;
1444 DontRemove = I;
1445 }
1446 }
1447 if (DontRemove != Remove.end()) {
1448 unsigned n = *DontRemove;
1449 Remove.remove(n);
1450 Remove.insert(orig_n1);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001451 }
1452 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001453
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001454 // We'd like to allow makeEqual on two values to perform a simple
1455 // substitution without every creating nodes in the IG whenever possible.
1456 //
1457 // The first iteration through this loop operates on V2 before going
1458 // through the Remove list and operating on those too. If all of the
1459 // iterations performed simple replacements then we exit early.
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001460 bool mergeIGNode = false;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001461 unsigned i = 0;
1462 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00001463 if (i) R = VN.value(Remove[i]); // skip n2.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001464
1465 // Try to replace the whole instruction. If we can, we're done.
1466 Instruction *I2 = dyn_cast<Instruction>(R);
1467 if (I2 && below(I2)) {
1468 std::vector<Instruction *> ToNotify;
1469 for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
1470 UI != UE;) {
1471 Use &TheUse = UI.getUse();
1472 ++UI;
1473 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser()))
1474 ToNotify.push_back(I);
1475 }
1476
1477 DOUT << "Simply removing " << *I2
1478 << ", replacing with " << *V1 << "\n";
1479 I2->replaceAllUsesWith(V1);
1480 // leave it dead; it'll get erased later.
1481 ++NumInstruction;
1482 modified = true;
1483
1484 for (std::vector<Instruction *>::iterator II = ToNotify.begin(),
1485 IE = ToNotify.end(); II != IE; ++II) {
1486 opsToDef(*II);
1487 }
1488
1489 continue;
1490 }
1491
1492 // Otherwise, replace all dominated uses.
1493 for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
1494 UI != UE;) {
1495 Use &TheUse = UI.getUse();
1496 ++UI;
1497 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
1498 if (below(I)) {
1499 TheUse.set(V1);
1500 modified = true;
1501 ++NumVarsReplaced;
1502 opsToDef(I);
1503 }
1504 }
1505 }
1506
1507 // If that killed the instruction, stop here.
1508 if (I2 && isInstructionTriviallyDead(I2)) {
1509 DOUT << "Killed all uses of " << *I2
1510 << ", replacing with " << *V1 << "\n";
1511 continue;
1512 }
1513
1514 // If we make it to here, then we will need to create a node for N1.
1515 // Otherwise, we can skip out early!
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001516 mergeIGNode = true;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001517 }
1518
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001519 if (!isa<Constant>(V1)) {
1520 if (Remove.empty()) {
1521 VR.mergeInto(&V2, 1, V1, Top, this);
1522 } else {
1523 std::vector<Value*> RemoveVals;
1524 RemoveVals.reserve(Remove.size());
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001525
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001526 for (SetVector<unsigned>::iterator I = Remove.begin(),
1527 E = Remove.end(); I != E; ++I) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00001528 Value *V = VN.value(*I);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001529 if (!V->use_empty())
1530 RemoveVals.push_back(V);
1531 }
1532 VR.mergeInto(&RemoveVals[0], RemoveVals.size(), V1, Top, this);
1533 }
1534 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001535
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001536 if (mergeIGNode) {
1537 // Create N1.
1538 if (!n1) n1 = IG.newNode(V1);
1539
1540 // Migrate relationships from removed nodes to N1.
1541 Node *N1 = IG.node(n1);
1542 for (SetVector<unsigned>::iterator I = Remove.begin(), E = Remove.end();
1543 I != E; ++I) {
1544 unsigned n = *I;
1545 Node *N = IG.node(n);
1546 for (Node::iterator NI = N->begin(), NE = N->end(); NI != NE; ++NI) {
1547 if (NI->Subtree->DominatedBy(Top)) {
1548 if (NI->To == n1) {
1549 assert((NI->LV & EQ_BIT) && "Node inequal to itself.");
1550 continue;
1551 }
1552 if (Remove.count(NI->To))
1553 continue;
1554
1555 IG.node(NI->To)->update(n1, reversePredicate(NI->LV), Top);
1556 N1->update(NI->To, NI->LV, Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001557 }
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001558 }
1559 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001560
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001561 // Point V2 (and all items in Remove) to N1.
1562 if (!n2)
Nick Lewycky73dd6922007-07-05 03:15:00 +00001563 VN.addEquality(n1, V2, Top);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001564 else {
1565 for (SetVector<unsigned>::iterator I = Remove.begin(),
1566 E = Remove.end(); I != E; ++I) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00001567 VN.addEquality(n1, VN.value(*I), Top);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001568 }
1569 }
1570
1571 // If !Remove.empty() then V2 = Remove[0]->getValue().
1572 // Even when Remove is empty, we still want to process V2.
1573 i = 0;
1574 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00001575 if (i) R = VN.value(Remove[i]); // skip n2.
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001576
1577 if (Instruction *I2 = dyn_cast<Instruction>(R)) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00001578 if (aboveOrBelow(I2))
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001579 defToOps(I2);
1580 }
1581 for (Value::use_iterator UI = V2->use_begin(), UE = V2->use_end();
1582 UI != UE;) {
1583 Use &TheUse = UI.getUse();
1584 ++UI;
1585 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00001586 if (aboveOrBelow(I))
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001587 opsToDef(I);
1588 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001589 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001590 }
1591 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001592
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001593 // re-opsToDef all dominated users of V1.
1594 if (Instruction *I = dyn_cast<Instruction>(V1)) {
1595 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001596 UI != UE;) {
1597 Use &TheUse = UI.getUse();
1598 ++UI;
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001599 Value *V = TheUse.getUser();
1600 if (!V->use_empty()) {
1601 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00001602 if (aboveOrBelow(Inst))
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001603 opsToDef(Inst);
1604 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001605 }
1606 }
1607 }
1608
1609 return true;
1610 }
1611
1612 /// cmpInstToLattice - converts an CmpInst::Predicate to lattice value
1613 /// Requires that the lattice value be valid; does not accept ICMP_EQ.
1614 static LatticeVal cmpInstToLattice(ICmpInst::Predicate Pred) {
1615 switch (Pred) {
1616 case ICmpInst::ICMP_EQ:
1617 assert(!"No matching lattice value.");
1618 return static_cast<LatticeVal>(EQ_BIT);
1619 default:
1620 assert(!"Invalid 'icmp' predicate.");
1621 case ICmpInst::ICMP_NE:
1622 return NE;
1623 case ICmpInst::ICMP_UGT:
Nick Lewycky56639802007-01-29 02:56:54 +00001624 return UGT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001625 case ICmpInst::ICMP_UGE:
Nick Lewycky56639802007-01-29 02:56:54 +00001626 return UGE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001627 case ICmpInst::ICMP_ULT:
Nick Lewycky56639802007-01-29 02:56:54 +00001628 return ULT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001629 case ICmpInst::ICMP_ULE:
Nick Lewycky56639802007-01-29 02:56:54 +00001630 return ULE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001631 case ICmpInst::ICMP_SGT:
Nick Lewycky56639802007-01-29 02:56:54 +00001632 return SGT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001633 case ICmpInst::ICMP_SGE:
Nick Lewycky56639802007-01-29 02:56:54 +00001634 return SGE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001635 case ICmpInst::ICMP_SLT:
Nick Lewycky56639802007-01-29 02:56:54 +00001636 return SLT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001637 case ICmpInst::ICMP_SLE:
Nick Lewycky56639802007-01-29 02:56:54 +00001638 return SLE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001639 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001640 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001641
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001642 public:
Nick Lewycky73dd6922007-07-05 03:15:00 +00001643 VRPSolver(ValueNumbering &VN, InequalityGraph &IG, UnreachableBlocks &UB,
1644 ValueRanges &VR, DomTreeDFS *DTDFS, bool &modified,
1645 BasicBlock *TopBB)
1646 : VN(VN),
1647 IG(IG),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001648 UB(UB),
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001649 VR(VR),
Nick Lewycky26e25d32007-06-24 04:36:20 +00001650 DTDFS(DTDFS),
1651 Top(DTDFS->getNodeForBlock(TopBB)),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001652 TopBB(TopBB),
1653 TopInst(NULL),
Nick Lewycky26e25d32007-06-24 04:36:20 +00001654 modified(modified)
1655 {
1656 assert(Top && "VRPSolver created for unreachable basic block.");
1657 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001658
Nick Lewycky73dd6922007-07-05 03:15:00 +00001659 VRPSolver(ValueNumbering &VN, InequalityGraph &IG, UnreachableBlocks &UB,
1660 ValueRanges &VR, DomTreeDFS *DTDFS, bool &modified,
1661 Instruction *TopInst)
1662 : VN(VN),
1663 IG(IG),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001664 UB(UB),
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001665 VR(VR),
Nick Lewycky26e25d32007-06-24 04:36:20 +00001666 DTDFS(DTDFS),
1667 Top(DTDFS->getNodeForBlock(TopInst->getParent())),
1668 TopBB(TopInst->getParent()),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001669 TopInst(TopInst),
1670 modified(modified)
1671 {
Nick Lewycky26e25d32007-06-24 04:36:20 +00001672 assert(Top && "VRPSolver created for unreachable basic block.");
1673 assert(Top->getBlock() == TopInst->getParent() && "Context mismatch.");
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001674 }
1675
1676 bool isRelatedBy(Value *V1, Value *V2, ICmpInst::Predicate Pred) const {
1677 if (Constant *C1 = dyn_cast<Constant>(V1))
1678 if (Constant *C2 = dyn_cast<Constant>(V2))
1679 return ConstantExpr::getCompare(Pred, C1, C2) ==
Zhou Sheng75b871f2007-01-11 12:24:14 +00001680 ConstantInt::getTrue();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001681
Nick Lewycky73dd6922007-07-05 03:15:00 +00001682 if (unsigned n1 = VN.valueNumber(V1, Top))
1683 if (unsigned n2 = VN.valueNumber(V2, Top)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001684 if (n1 == n2) return Pred == ICmpInst::ICMP_EQ ||
1685 Pred == ICmpInst::ICMP_ULE ||
1686 Pred == ICmpInst::ICMP_UGE ||
1687 Pred == ICmpInst::ICMP_SLE ||
1688 Pred == ICmpInst::ICMP_SGE;
1689 if (Pred == ICmpInst::ICMP_EQ) return false;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001690 if (IG.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001691 }
1692
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001693 if (Pred == ICmpInst::ICMP_EQ) return V1 == V2;
1694 return VR.isRelatedBy(V1, V2, Top, cmpInstToLattice(Pred));
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001695 }
1696
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001697 /// add - adds a new property to the work queue
1698 void add(Value *V1, Value *V2, ICmpInst::Predicate Pred,
1699 Instruction *I = NULL) {
1700 DOUT << "adding " << *V1 << " " << Pred << " " << *V2;
1701 if (I) DOUT << " context: " << *I;
Nick Lewycky26e25d32007-06-24 04:36:20 +00001702 else DOUT << " default context (" << Top->getDFSNumIn() << ")";
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001703 DOUT << "\n";
1704
Nick Lewycky12d44ab2007-04-07 03:16:12 +00001705 assert(V1->getType() == V2->getType() &&
1706 "Can't relate two values with different types.");
1707
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001708 WorkList.push_back(Operation());
1709 Operation &O = WorkList.back();
Nick Lewycky42944462007-01-13 02:05:28 +00001710 O.LHS = V1, O.RHS = V2, O.Op = Pred, O.ContextInst = I;
1711 O.ContextBB = I ? I->getParent() : TopBB;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001712 }
1713
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001714 /// defToOps - Given an instruction definition that we've learned something
1715 /// new about, find any new relationships between its operands.
1716 void defToOps(Instruction *I) {
1717 Instruction *NewContext = below(I) ? I : TopInst;
Nick Lewycky73dd6922007-07-05 03:15:00 +00001718 Value *Canonical = VN.canonicalize(I, Top);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001719
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001720 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1721 const Type *Ty = BO->getType();
1722 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001723
Nick Lewycky73dd6922007-07-05 03:15:00 +00001724 Value *Op0 = VN.canonicalize(BO->getOperand(0), Top);
1725 Value *Op1 = VN.canonicalize(BO->getOperand(1), Top);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001726
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001727 // TODO: "and i32 -1, %x" EQ %y then %x EQ %y.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001728
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001729 switch (BO->getOpcode()) {
1730 case Instruction::And: {
Nick Lewycky4f73de22007-03-16 02:37:39 +00001731 // "and i32 %a, %b" EQ -1 then %a EQ -1 and %b EQ -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00001732 ConstantInt *CI = ConstantInt::getAllOnesValue(Ty);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001733 if (Canonical == CI) {
1734 add(CI, Op0, ICmpInst::ICMP_EQ, NewContext);
1735 add(CI, Op1, ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001736 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001737 } break;
1738 case Instruction::Or: {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001739 // "or i32 %a, %b" EQ 0 then %a EQ 0 and %b EQ 0
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001740 Constant *Zero = Constant::getNullValue(Ty);
1741 if (Canonical == Zero) {
1742 add(Zero, Op0, ICmpInst::ICMP_EQ, NewContext);
1743 add(Zero, Op1, ICmpInst::ICMP_EQ, NewContext);
1744 }
1745 } break;
1746 case Instruction::Xor: {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001747 // "xor i32 %c, %a" EQ %b then %a EQ %c ^ %b
1748 // "xor i32 %c, %a" EQ %c then %a EQ 0
1749 // "xor i32 %c, %a" NE %c then %a NE 0
1750 // Repeat the above, with order of operands reversed.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001751 Value *LHS = Op0;
1752 Value *RHS = Op1;
1753 if (!isa<Constant>(LHS)) std::swap(LHS, RHS);
1754
Nick Lewycky4a74a752007-01-12 00:02:12 +00001755 if (ConstantInt *CI = dyn_cast<ConstantInt>(Canonical)) {
1756 if (ConstantInt *Arg = dyn_cast<ConstantInt>(LHS)) {
Reid Spencerc34dedf2007-03-03 00:48:31 +00001757 add(RHS, ConstantInt::get(CI->getValue() ^ Arg->getValue()),
Nick Lewycky4a74a752007-01-12 00:02:12 +00001758 ICmpInst::ICMP_EQ, NewContext);
1759 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001760 }
1761 if (Canonical == LHS) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001762 if (isa<ConstantInt>(Canonical))
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001763 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_EQ,
1764 NewContext);
1765 } else if (isRelatedBy(LHS, Canonical, ICmpInst::ICMP_NE)) {
1766 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_NE,
1767 NewContext);
1768 }
1769 } break;
1770 default:
1771 break;
1772 }
1773 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001774 // "icmp ult i32 %a, %y" EQ true then %a u< y
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001775 // etc.
1776
Zhou Sheng75b871f2007-01-11 12:24:14 +00001777 if (Canonical == ConstantInt::getTrue()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001778 add(IC->getOperand(0), IC->getOperand(1), IC->getPredicate(),
1779 NewContext);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001780 } else if (Canonical == ConstantInt::getFalse()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001781 add(IC->getOperand(0), IC->getOperand(1),
1782 ICmpInst::getInversePredicate(IC->getPredicate()), NewContext);
1783 }
1784 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
1785 if (I->getType()->isFPOrFPVector()) return;
1786
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001787 // Given: "%a = select i1 %x, i32 %b, i32 %c"
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001788 // %a EQ %b and %b NE %c then %x EQ true
1789 // %a EQ %c and %b NE %c then %x EQ false
1790
1791 Value *True = SI->getTrueValue();
1792 Value *False = SI->getFalseValue();
1793 if (isRelatedBy(True, False, ICmpInst::ICMP_NE)) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00001794 if (Canonical == VN.canonicalize(True, Top) ||
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001795 isRelatedBy(Canonical, False, ICmpInst::ICMP_NE))
Zhou Sheng75b871f2007-01-11 12:24:14 +00001796 add(SI->getCondition(), ConstantInt::getTrue(),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001797 ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky73dd6922007-07-05 03:15:00 +00001798 else if (Canonical == VN.canonicalize(False, Top) ||
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001799 isRelatedBy(Canonical, True, ICmpInst::ICMP_NE))
Zhou Sheng75b871f2007-01-11 12:24:14 +00001800 add(SI->getCondition(), ConstantInt::getFalse(),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001801 ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001802 }
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001803 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1804 for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
1805 OE = GEPI->idx_end(); OI != OE; ++OI) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00001806 ConstantInt *Op = dyn_cast<ConstantInt>(VN.canonicalize(*OI, Top));
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001807 if (!Op || !Op->isZero()) return;
1808 }
1809 // TODO: The GEPI indices are all zero. Copy from definition to operand,
1810 // jumping the type plane as needed.
1811 if (isRelatedBy(GEPI, Constant::getNullValue(GEPI->getType()),
1812 ICmpInst::ICMP_NE)) {
1813 Value *Ptr = GEPI->getPointerOperand();
1814 add(Ptr, Constant::getNullValue(Ptr->getType()), ICmpInst::ICMP_NE,
1815 NewContext);
1816 }
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001817 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
1818 const Type *SrcTy = CI->getSrcTy();
1819
Nick Lewycky73dd6922007-07-05 03:15:00 +00001820 Value *TheCI = VN.canonicalize(CI, Top);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001821 uint32_t W = VR.typeToWidth(SrcTy);
1822 if (!W) return;
1823 ConstantRange CR = VR.rangeFromValue(TheCI, Top, W);
1824
1825 if (CR.isFullSet()) return;
1826
1827 switch (CI->getOpcode()) {
1828 default: break;
1829 case Instruction::ZExt:
1830 case Instruction::SExt:
Nick Lewycky73dd6922007-07-05 03:15:00 +00001831 VR.applyRange(VN.canonicalize(CI->getOperand(0), Top),
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001832 CR.truncate(W), Top, this);
1833 break;
1834 case Instruction::BitCast:
Nick Lewycky73dd6922007-07-05 03:15:00 +00001835 VR.applyRange(VN.canonicalize(CI->getOperand(0), Top),
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001836 CR, Top, this);
1837 break;
1838 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001839 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001840 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001841
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001842 /// opsToDef - A new relationship was discovered involving one of this
1843 /// instruction's operands. Find any new relationship involving the
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001844 /// definition, or another operand.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001845 void opsToDef(Instruction *I) {
1846 Instruction *NewContext = below(I) ? I : TopInst;
1847
1848 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00001849 Value *Op0 = VN.canonicalize(BO->getOperand(0), Top);
1850 Value *Op1 = VN.canonicalize(BO->getOperand(1), Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001851
Zhou Sheng75b871f2007-01-11 12:24:14 +00001852 if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0))
1853 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001854 add(BO, ConstantExpr::get(BO->getOpcode(), CI0, CI1),
1855 ICmpInst::ICMP_EQ, NewContext);
1856 return;
1857 }
1858
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001859 // "%y = and i1 true, %x" then %x EQ %y
1860 // "%y = or i1 false, %x" then %x EQ %y
1861 // "%x = add i32 %y, 0" then %x EQ %y
1862 // "%x = mul i32 %y, 0" then %x EQ 0
1863
1864 Instruction::BinaryOps Opcode = BO->getOpcode();
Nick Lewyckydb204ec2007-03-18 22:58:46 +00001865 const Type *Ty = BO->getType();
1866 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
1867
1868 Constant *Zero = Constant::getNullValue(Ty);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001869 ConstantInt *AllOnes = ConstantInt::getAllOnesValue(Ty);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001870
1871 switch (Opcode) {
1872 default: break;
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001873 case Instruction::LShr:
1874 case Instruction::AShr:
1875 case Instruction::Shl:
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001876 case Instruction::Sub:
Nick Lewyckydb204ec2007-03-18 22:58:46 +00001877 if (Op1 == Zero) {
1878 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1879 return;
1880 }
1881 break;
1882 case Instruction::Or:
1883 if (Op0 == AllOnes || Op1 == AllOnes) {
1884 add(BO, AllOnes, ICmpInst::ICMP_EQ, NewContext);
1885 return;
1886 } // fall-through
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001887 case Instruction::Xor:
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001888 case Instruction::Add:
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001889 if (Op0 == Zero) {
1890 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1891 return;
1892 } else if (Op1 == Zero) {
1893 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1894 return;
1895 }
Nick Lewyckydb204ec2007-03-18 22:58:46 +00001896 break;
1897 case Instruction::And:
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001898 if (Op0 == AllOnes) {
1899 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1900 return;
1901 } else if (Op1 == AllOnes) {
1902 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1903 return;
1904 }
Nick Lewyckydb204ec2007-03-18 22:58:46 +00001905 // fall-through
1906 case Instruction::Mul:
1907 if (Op0 == Zero || Op1 == Zero) {
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001908 add(BO, Zero, ICmpInst::ICMP_EQ, NewContext);
1909 return;
1910 }
Nick Lewyckydb204ec2007-03-18 22:58:46 +00001911 break;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001912 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001913
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001914 // "%x = add i32 %y, %z" and %x EQ %y then %z EQ 0
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001915 // "%x = add i32 %y, %z" and %x EQ %z then %y EQ 0
1916 // "%x = shl i32 %y, %z" and %x EQ %y and %y NE 0 then %z EQ 0
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001917 // "%x = udiv i32 %y, %z" and %x EQ %y then %z EQ 1
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001918
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001919 Value *Known = Op0, *Unknown = Op1,
Nick Lewycky73dd6922007-07-05 03:15:00 +00001920 *TheBO = VN.canonicalize(BO, Top);
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001921 if (Known != TheBO) std::swap(Known, Unknown);
1922 if (Known == TheBO) {
Nick Lewycky4f73de22007-03-16 02:37:39 +00001923 switch (Opcode) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001924 default: break;
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001925 case Instruction::LShr:
1926 case Instruction::AShr:
1927 case Instruction::Shl:
1928 if (!isRelatedBy(Known, Zero, ICmpInst::ICMP_NE)) break;
1929 // otherwise, fall-through.
1930 case Instruction::Sub:
1931 if (Unknown == Op1) break;
1932 // otherwise, fall-through.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001933 case Instruction::Xor:
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001934 case Instruction::Add:
Nick Lewyckydb204ec2007-03-18 22:58:46 +00001935 add(Unknown, Zero, ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001936 break;
1937 case Instruction::UDiv:
1938 case Instruction::SDiv:
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001939 if (Unknown == Op1) break;
1940 if (isRelatedBy(Known, Zero, ICmpInst::ICMP_NE)) {
Nick Lewycky4a74a752007-01-12 00:02:12 +00001941 Constant *One = ConstantInt::get(Ty, 1);
1942 add(Unknown, One, ICmpInst::ICMP_EQ, NewContext);
1943 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001944 break;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001945 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001946 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001947
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001948 // TODO: "%a = add i32 %b, 1" and %b > %z then %a >= %z.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001949
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001950 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
Nick Lewycky4f73de22007-03-16 02:37:39 +00001951 // "%a = icmp ult i32 %b, %c" and %b u< %c then %a EQ true
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001952 // "%a = icmp ult i32 %b, %c" and %b u>= %c then %a EQ false
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001953 // etc.
1954
Nick Lewycky73dd6922007-07-05 03:15:00 +00001955 Value *Op0 = VN.canonicalize(IC->getOperand(0), Top);
1956 Value *Op1 = VN.canonicalize(IC->getOperand(1), Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001957
1958 ICmpInst::Predicate Pred = IC->getPredicate();
1959 if (isRelatedBy(Op0, Op1, Pred)) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001960 add(IC, ConstantInt::getTrue(), ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001961 } else if (isRelatedBy(Op0, Op1, ICmpInst::getInversePredicate(Pred))) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001962 add(IC, ConstantInt::getFalse(), ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001963 }
1964
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001965 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001966 if (I->getType()->isFPOrFPVector()) return;
1967
Nick Lewycky4f73de22007-03-16 02:37:39 +00001968 // Given: "%a = select i1 %x, i32 %b, i32 %c"
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001969 // %x EQ true then %a EQ %b
1970 // %x EQ false then %a EQ %c
1971 // %b EQ %c then %a EQ %b
1972
Nick Lewycky73dd6922007-07-05 03:15:00 +00001973 Value *Canonical = VN.canonicalize(SI->getCondition(), Top);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001974 if (Canonical == ConstantInt::getTrue()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001975 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001976 } else if (Canonical == ConstantInt::getFalse()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001977 add(SI, SI->getFalseValue(), ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky73dd6922007-07-05 03:15:00 +00001978 } else if (VN.canonicalize(SI->getTrueValue(), Top) ==
1979 VN.canonicalize(SI->getFalseValue(), Top)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001980 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
1981 }
Nick Lewyckyee32ee02007-01-12 01:23:53 +00001982 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001983 const Type *DestTy = CI->getDestTy();
1984 if (DestTy->isFPOrFPVector()) return;
Nick Lewyckyee32ee02007-01-12 01:23:53 +00001985
Nick Lewycky73dd6922007-07-05 03:15:00 +00001986 Value *Op = VN.canonicalize(CI->getOperand(0), Top);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001987 Instruction::CastOps Opcode = CI->getOpcode();
1988
1989 if (Constant *C = dyn_cast<Constant>(Op)) {
1990 add(CI, ConstantExpr::getCast(Opcode, C, DestTy),
Nick Lewyckyee32ee02007-01-12 01:23:53 +00001991 ICmpInst::ICMP_EQ, NewContext);
1992 }
1993
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001994 uint32_t W = VR.typeToWidth(DestTy);
Nick Lewycky73dd6922007-07-05 03:15:00 +00001995 Value *TheCI = VN.canonicalize(CI, Top);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001996 ConstantRange CR = VR.rangeFromValue(Op, Top, W);
1997
1998 if (!CR.isFullSet()) {
1999 switch (Opcode) {
2000 default: break;
2001 case Instruction::ZExt:
2002 VR.applyRange(TheCI, CR.zeroExtend(W), Top, this);
2003 break;
2004 case Instruction::SExt:
2005 VR.applyRange(TheCI, CR.signExtend(W), Top, this);
2006 break;
2007 case Instruction::Trunc: {
2008 ConstantRange Result = CR.truncate(W);
2009 if (!Result.isFullSet())
2010 VR.applyRange(TheCI, Result, Top, this);
2011 } break;
2012 case Instruction::BitCast:
2013 VR.applyRange(TheCI, CR, Top, this);
2014 break;
2015 // TODO: other casts?
2016 }
2017 }
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00002018 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
2019 for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
2020 OE = GEPI->idx_end(); OI != OE; ++OI) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002021 ConstantInt *Op = dyn_cast<ConstantInt>(VN.canonicalize(*OI, Top));
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00002022 if (!Op || !Op->isZero()) return;
2023 }
2024 // TODO: The GEPI indices are all zero. Copy from operand to definition,
2025 // jumping the type plane as needed.
2026 Value *Ptr = GEPI->getPointerOperand();
2027 if (isRelatedBy(Ptr, Constant::getNullValue(Ptr->getType()),
2028 ICmpInst::ICMP_NE)) {
2029 add(GEPI, Constant::getNullValue(GEPI->getType()), ICmpInst::ICMP_NE,
2030 NewContext);
2031 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002032 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002033 }
2034
2035 /// solve - process the work queue
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002036 void solve() {
2037 //DOUT << "WorkList entry, size: " << WorkList.size() << "\n";
2038 while (!WorkList.empty()) {
2039 //DOUT << "WorkList size: " << WorkList.size() << "\n";
2040
2041 Operation &O = WorkList.front();
Nick Lewycky42944462007-01-13 02:05:28 +00002042 TopInst = O.ContextInst;
2043 TopBB = O.ContextBB;
Nick Lewycky26e25d32007-06-24 04:36:20 +00002044 Top = DTDFS->getNodeForBlock(TopBB); // XXX move this into Context
Nick Lewycky42944462007-01-13 02:05:28 +00002045
Nick Lewycky73dd6922007-07-05 03:15:00 +00002046 O.LHS = VN.canonicalize(O.LHS, Top);
2047 O.RHS = VN.canonicalize(O.RHS, Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002048
Nick Lewycky73dd6922007-07-05 03:15:00 +00002049 assert(O.LHS == VN.canonicalize(O.LHS, Top) && "Canonicalize isn't.");
2050 assert(O.RHS == VN.canonicalize(O.RHS, Top) && "Canonicalize isn't.");
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002051
2052 DOUT << "solving " << *O.LHS << " " << O.Op << " " << *O.RHS;
Nick Lewycky42944462007-01-13 02:05:28 +00002053 if (O.ContextInst) DOUT << " context inst: " << *O.ContextInst;
2054 else DOUT << " context block: " << O.ContextBB->getName();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002055 DOUT << "\n";
2056
2057 DEBUG(IG.dump());
2058
Nick Lewycky15245952007-02-04 23:43:05 +00002059 // If they're both Constant, skip it. Check for contradiction and mark
2060 // the BB as unreachable if so.
2061 if (Constant *CI_L = dyn_cast<Constant>(O.LHS)) {
2062 if (Constant *CI_R = dyn_cast<Constant>(O.RHS)) {
2063 if (ConstantExpr::getCompare(O.Op, CI_L, CI_R) ==
2064 ConstantInt::getFalse())
2065 UB.mark(TopBB);
2066
2067 WorkList.pop_front();
2068 continue;
2069 }
2070 }
2071
Nick Lewycky73dd6922007-07-05 03:15:00 +00002072 if (VN.compare(O.LHS, O.RHS)) {
Nick Lewycky15245952007-02-04 23:43:05 +00002073 std::swap(O.LHS, O.RHS);
2074 O.Op = ICmpInst::getSwappedPredicate(O.Op);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002075 }
2076
2077 if (O.Op == ICmpInst::ICMP_EQ) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002078 if (!makeEqual(O.RHS, O.LHS))
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002079 UB.mark(TopBB);
2080 } else {
2081 LatticeVal LV = cmpInstToLattice(O.Op);
2082
2083 if ((LV & EQ_BIT) &&
2084 isRelatedBy(O.LHS, O.RHS, ICmpInst::getSwappedPredicate(O.Op))) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002085 if (!makeEqual(O.RHS, O.LHS))
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002086 UB.mark(TopBB);
2087 } else {
2088 if (isRelatedBy(O.LHS, O.RHS, ICmpInst::getInversePredicate(O.Op))){
Nick Lewycky15245952007-02-04 23:43:05 +00002089 UB.mark(TopBB);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002090 WorkList.pop_front();
2091 continue;
2092 }
2093
Nick Lewycky73dd6922007-07-05 03:15:00 +00002094 unsigned n1 = VN.valueNumber(O.LHS, Top);
2095 unsigned n2 = VN.valueNumber(O.RHS, Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002096
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002097 if (n1 && n1 == n2) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002098 if (O.Op != ICmpInst::ICMP_UGE && O.Op != ICmpInst::ICMP_ULE &&
2099 O.Op != ICmpInst::ICMP_SGE && O.Op != ICmpInst::ICMP_SLE)
2100 UB.mark(TopBB);
2101
2102 WorkList.pop_front();
2103 continue;
2104 }
2105
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002106 if (VR.isRelatedBy(O.LHS, O.RHS, Top, LV) ||
2107 (n1 && n2 && IG.isRelatedBy(n1, n2, Top, LV))) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002108 WorkList.pop_front();
2109 continue;
2110 }
2111
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002112 VR.addInequality(O.LHS, O.RHS, Top, LV, this);
2113 if ((!isa<ConstantInt>(O.RHS) && !isa<ConstantInt>(O.LHS)) ||
2114 LV == NE) {
2115 if (!n1) n1 = IG.newNode(O.LHS);
2116 if (!n2) n2 = IG.newNode(O.RHS);
2117 IG.addInequality(n1, n2, Top, LV);
Nick Lewycky15245952007-02-04 23:43:05 +00002118 }
2119
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002120 if (Instruction *I1 = dyn_cast<Instruction>(O.LHS)) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002121 if (aboveOrBelow(I1))
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002122 defToOps(I1);
2123 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002124 if (isa<Instruction>(O.LHS) || isa<Argument>(O.LHS)) {
2125 for (Value::use_iterator UI = O.LHS->use_begin(),
2126 UE = O.LHS->use_end(); UI != UE;) {
2127 Use &TheUse = UI.getUse();
2128 ++UI;
2129 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002130 if (aboveOrBelow(I))
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002131 opsToDef(I);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002132 }
2133 }
2134 }
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002135 if (Instruction *I2 = dyn_cast<Instruction>(O.RHS)) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002136 if (aboveOrBelow(I2))
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002137 defToOps(I2);
2138 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002139 if (isa<Instruction>(O.RHS) || isa<Argument>(O.RHS)) {
2140 for (Value::use_iterator UI = O.RHS->use_begin(),
2141 UE = O.RHS->use_end(); UI != UE;) {
2142 Use &TheUse = UI.getUse();
2143 ++UI;
2144 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002145 if (aboveOrBelow(I))
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002146 opsToDef(I);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002147 }
2148 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00002149 }
2150 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00002151 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002152 WorkList.pop_front();
Nick Lewycky9d17c822006-10-25 23:48:24 +00002153 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00002154 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002155 };
2156
Nick Lewycky3bb6de82007-04-07 03:36:51 +00002157 void ValueRanges::addToWorklist(Value *V, Constant *C,
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002158 ICmpInst::Predicate Pred, VRPSolver *VRP) {
Nick Lewycky3bb6de82007-04-07 03:36:51 +00002159 VRP->add(V, C, Pred, VRP->TopInst);
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002160 }
2161
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00002162 void ValueRanges::markBlock(VRPSolver *VRP) {
2163 VRP->UB.mark(VRP->TopBB);
2164 }
2165
Nick Lewycky17d20fd2007-03-18 01:09:32 +00002166#ifndef NDEBUG
Nick Lewycky26e25d32007-06-24 04:36:20 +00002167 bool ValueRanges::isCanonical(Value *V, DomTreeDFS::Node *Subtree,
2168 VRPSolver *VRP) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002169 return V == VRP->VN.canonicalize(V, Subtree);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00002170 }
2171#endif
2172
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002173 /// PredicateSimplifier - This class is a simplifier that replaces
2174 /// one equivalent variable with another. It also tracks what
2175 /// can't be equal and will solve setcc instructions when possible.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002176 /// @brief Root of the predicate simplifier optimization.
2177 class VISIBILITY_HIDDEN PredicateSimplifier : public FunctionPass {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002178 DomTreeDFS *DTDFS;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002179 bool modified;
Nick Lewycky73dd6922007-07-05 03:15:00 +00002180 ValueNumbering *VN;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002181 InequalityGraph *IG;
2182 UnreachableBlocks UB;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002183 ValueRanges *VR;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002184
Nick Lewycky26e25d32007-06-24 04:36:20 +00002185 std::vector<DomTreeDFS::Node *> WorkList;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002186
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002187 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +00002188 static char ID; // Pass identification, replacement for typeid
Devang Patel09f162c2007-05-01 21:15:47 +00002189 PredicateSimplifier() : FunctionPass((intptr_t)&ID) {}
2190
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002191 bool runOnFunction(Function &F);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002192
2193 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
2194 AU.addRequiredID(BreakCriticalEdgesID);
Owen Anderson510fefc2007-04-25 04:18:54 +00002195 AU.addRequired<DominatorTree>();
Nick Lewycky12d44ab2007-04-07 03:16:12 +00002196 AU.addRequired<TargetData>();
2197 AU.addPreserved<TargetData>();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002198 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002199
2200 private:
Nick Lewycky77e030b2006-10-12 02:02:44 +00002201 /// Forwards - Adds new properties into PropertySet and uses them to
2202 /// simplify instructions. Because new properties sometimes apply to
2203 /// a transition from one BasicBlock to another, this will use the
2204 /// PredicateSimplifier::proceedToSuccessor(s) interface to enter the
2205 /// basic block with the new PropertySet.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002206 /// @brief Performs abstract execution of the program.
2207 class VISIBILITY_HIDDEN Forwards : public InstVisitor<Forwards> {
Nick Lewycky77e030b2006-10-12 02:02:44 +00002208 friend class InstVisitor<Forwards>;
2209 PredicateSimplifier *PS;
Nick Lewycky26e25d32007-06-24 04:36:20 +00002210 DomTreeDFS::Node *DTNode;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002211
Nick Lewycky77e030b2006-10-12 02:02:44 +00002212 public:
Nick Lewycky73dd6922007-07-05 03:15:00 +00002213 ValueNumbering &VN;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002214 InequalityGraph &IG;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002215 UnreachableBlocks &UB;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002216 ValueRanges &VR;
Nick Lewycky77e030b2006-10-12 02:02:44 +00002217
Nick Lewycky26e25d32007-06-24 04:36:20 +00002218 Forwards(PredicateSimplifier *PS, DomTreeDFS::Node *DTNode)
Nick Lewycky73dd6922007-07-05 03:15:00 +00002219 : PS(PS), DTNode(DTNode), VN(*PS->VN), IG(*PS->IG), UB(PS->UB),
2220 VR(*PS->VR) {}
Nick Lewycky77e030b2006-10-12 02:02:44 +00002221
2222 void visitTerminatorInst(TerminatorInst &TI);
2223 void visitBranchInst(BranchInst &BI);
2224 void visitSwitchInst(SwitchInst &SI);
2225
Nick Lewyckyf3450082006-10-22 19:53:27 +00002226 void visitAllocaInst(AllocaInst &AI);
Nick Lewycky77e030b2006-10-12 02:02:44 +00002227 void visitLoadInst(LoadInst &LI);
2228 void visitStoreInst(StoreInst &SI);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002229
Nick Lewycky15245952007-02-04 23:43:05 +00002230 void visitSExtInst(SExtInst &SI);
2231 void visitZExtInst(ZExtInst &ZI);
2232
Nick Lewycky77e030b2006-10-12 02:02:44 +00002233 void visitBinaryOperator(BinaryOperator &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002234 void visitICmpInst(ICmpInst &IC);
Nick Lewycky77e030b2006-10-12 02:02:44 +00002235 };
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002236
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002237 // Used by terminator instructions to proceed from the current basic
2238 // block to the next. Verifies that "current" dominates "next",
2239 // then calls visitBasicBlock.
Nick Lewycky26e25d32007-06-24 04:36:20 +00002240 void proceedToSuccessors(DomTreeDFS::Node *Current) {
2241 for (DomTreeDFS::Node::iterator I = Current->begin(),
Owen Anderson510fefc2007-04-25 04:18:54 +00002242 E = Current->end(); I != E; ++I) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002243 WorkList.push_back(*I);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002244 }
2245 }
2246
Nick Lewycky26e25d32007-06-24 04:36:20 +00002247 void proceedToSuccessor(DomTreeDFS::Node *Next) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002248 WorkList.push_back(Next);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002249 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002250
2251 // Visits each instruction in the basic block.
Nick Lewycky26e25d32007-06-24 04:36:20 +00002252 void visitBasicBlock(DomTreeDFS::Node *Node) {
Owen Anderson510fefc2007-04-25 04:18:54 +00002253 BasicBlock *BB = Node->getBlock();
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002254 DOUT << "Entering Basic Block: " << BB->getName()
Nick Lewycky26e25d32007-06-24 04:36:20 +00002255 << " (" << Node->getDFSNumIn() << ")\n";
Bill Wendling22e978a2006-12-07 20:04:42 +00002256 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002257 visitInstruction(I++, Node);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002258 }
2259 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002260
Nick Lewycky9a22d7b2006-09-10 02:27:07 +00002261 // Tries to simplify each Instruction and add new properties to
Nick Lewycky77e030b2006-10-12 02:02:44 +00002262 // the PropertySet.
Nick Lewycky26e25d32007-06-24 04:36:20 +00002263 void visitInstruction(Instruction *I, DomTreeDFS::Node *DT) {
Bill Wendling22e978a2006-12-07 20:04:42 +00002264 DOUT << "Considering instruction " << *I << "\n";
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002265 DEBUG(IG->dump());
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002266
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002267 // Sometimes instructions are killed in earlier analysis.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002268 if (isInstructionTriviallyDead(I)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002269 ++NumSimple;
2270 modified = true;
Nick Lewycky73dd6922007-07-05 03:15:00 +00002271 if (unsigned n = VN->valueNumber(I, DTDFS->getRootNode()))
2272 if (VN->value(n) == I) IG->remove(n);
2273 VN->remove(I);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002274 I->eraseFromParent();
2275 return;
2276 }
2277
Nick Lewycky42944462007-01-13 02:05:28 +00002278#ifndef NDEBUG
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002279 // Try to replace the whole instruction.
Nick Lewycky73dd6922007-07-05 03:15:00 +00002280 Value *V = VN->canonicalize(I, DT);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002281 assert(V == I && "Late instruction canonicalization.");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002282 if (V != I) {
2283 modified = true;
2284 ++NumInstruction;
Bill Wendling22e978a2006-12-07 20:04:42 +00002285 DOUT << "Removing " << *I << ", replacing with " << *V << "\n";
Nick Lewycky73dd6922007-07-05 03:15:00 +00002286 if (unsigned n = VN->valueNumber(I, DTDFS->getRootNode()))
2287 if (VN->value(n) == I) IG->remove(n);
2288 VN->remove(I);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002289 I->replaceAllUsesWith(V);
2290 I->eraseFromParent();
2291 return;
2292 }
2293
2294 // Try to substitute operands.
2295 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2296 Value *Oper = I->getOperand(i);
Nick Lewycky73dd6922007-07-05 03:15:00 +00002297 Value *V = VN->canonicalize(Oper, DT);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002298 assert(V == Oper && "Late operand canonicalization.");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002299 if (V != Oper) {
2300 modified = true;
2301 ++NumVarsReplaced;
Bill Wendling22e978a2006-12-07 20:04:42 +00002302 DOUT << "Resolving " << *I;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002303 I->setOperand(i, V);
Bill Wendling22e978a2006-12-07 20:04:42 +00002304 DOUT << " into " << *I;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002305 }
2306 }
Nick Lewycky42944462007-01-13 02:05:28 +00002307#endif
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002308
Nick Lewycky4f73de22007-03-16 02:37:39 +00002309 std::string name = I->getParent()->getName();
2310 DOUT << "push (%" << name << ")\n";
Owen Anderson510fefc2007-04-25 04:18:54 +00002311 Forwards visit(this, DT);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002312 visit.visit(*I);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002313 DOUT << "pop (%" << name << ")\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002314 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002315 };
2316
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002317 bool PredicateSimplifier::runOnFunction(Function &F) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002318 DominatorTree *DT = &getAnalysis<DominatorTree>();
2319 DTDFS = new DomTreeDFS(DT);
Nick Lewycky12d44ab2007-04-07 03:16:12 +00002320 TargetData *TD = &getAnalysis<TargetData>();
2321
Bill Wendling22e978a2006-12-07 20:04:42 +00002322 DOUT << "Entering Function: " << F.getName() << "\n";
Nick Lewyckycfff1c32006-09-20 17:04:01 +00002323
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002324 modified = false;
Nick Lewycky26e25d32007-06-24 04:36:20 +00002325 DomTreeDFS::Node *Root = DTDFS->getRootNode();
Nick Lewycky73dd6922007-07-05 03:15:00 +00002326 VN = new ValueNumbering(DTDFS);
2327 IG = new InequalityGraph(*VN, Root);
Nick Lewycky12d44ab2007-04-07 03:16:12 +00002328 VR = new ValueRanges(TD);
Nick Lewycky26e25d32007-06-24 04:36:20 +00002329 WorkList.push_back(Root);
Nick Lewyckycfff1c32006-09-20 17:04:01 +00002330
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002331 do {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002332 DomTreeDFS::Node *DTNode = WorkList.back();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002333 WorkList.pop_back();
Owen Anderson510fefc2007-04-25 04:18:54 +00002334 if (!UB.isDead(DTNode->getBlock())) visitBasicBlock(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002335 } while (!WorkList.empty());
Nick Lewyckycfff1c32006-09-20 17:04:01 +00002336
Nick Lewycky26e25d32007-06-24 04:36:20 +00002337 delete DTDFS;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002338 delete VR;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002339 delete IG;
2340
2341 modified |= UB.kill();
Nick Lewyckycfff1c32006-09-20 17:04:01 +00002342
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002343 return modified;
Nick Lewycky8e559932006-09-02 19:40:38 +00002344 }
2345
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002346 void PredicateSimplifier::Forwards::visitTerminatorInst(TerminatorInst &TI) {
Owen Anderson510fefc2007-04-25 04:18:54 +00002347 PS->proceedToSuccessors(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002348 }
2349
2350 void PredicateSimplifier::Forwards::visitBranchInst(BranchInst &BI) {
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002351 if (BI.isUnconditional()) {
Owen Anderson510fefc2007-04-25 04:18:54 +00002352 PS->proceedToSuccessors(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002353 return;
2354 }
2355
2356 Value *Condition = BI.getCondition();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002357 BasicBlock *TrueDest = BI.getSuccessor(0);
2358 BasicBlock *FalseDest = BI.getSuccessor(1);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002359
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002360 if (isa<Constant>(Condition) || TrueDest == FalseDest) {
Owen Anderson510fefc2007-04-25 04:18:54 +00002361 PS->proceedToSuccessors(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002362 return;
2363 }
2364
Nick Lewycky26e25d32007-06-24 04:36:20 +00002365 for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
Owen Anderson510fefc2007-04-25 04:18:54 +00002366 I != E; ++I) {
2367 BasicBlock *Dest = (*I)->getBlock();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002368 DOUT << "Branch thinking about %" << Dest->getName()
Nick Lewycky26e25d32007-06-24 04:36:20 +00002369 << "(" << PS->DTDFS->getNodeForBlock(Dest)->getDFSNumIn() << ")\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002370
2371 if (Dest == TrueDest) {
Owen Anderson510fefc2007-04-25 04:18:54 +00002372 DOUT << "(" << DTNode->getBlock()->getName() << ") true set:\n";
Nick Lewycky73dd6922007-07-05 03:15:00 +00002373 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002374 VRP.add(ConstantInt::getTrue(), Condition, ICmpInst::ICMP_EQ);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002375 VRP.solve();
2376 DEBUG(IG.dump());
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002377 } else if (Dest == FalseDest) {
Owen Anderson510fefc2007-04-25 04:18:54 +00002378 DOUT << "(" << DTNode->getBlock()->getName() << ") false set:\n";
Nick Lewycky73dd6922007-07-05 03:15:00 +00002379 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002380 VRP.add(ConstantInt::getFalse(), Condition, ICmpInst::ICMP_EQ);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002381 VRP.solve();
2382 DEBUG(IG.dump());
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002383 }
2384
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002385 PS->proceedToSuccessor(*I);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002386 }
2387 }
2388
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002389 void PredicateSimplifier::Forwards::visitSwitchInst(SwitchInst &SI) {
2390 Value *Condition = SI.getCondition();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002391
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002392 // Set the EQProperty in each of the cases BBs, and the NEProperties
2393 // in the default BB.
Owen Anderson510fefc2007-04-25 04:18:54 +00002394
Nick Lewycky26e25d32007-06-24 04:36:20 +00002395 for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
Owen Anderson510fefc2007-04-25 04:18:54 +00002396 I != E; ++I) {
2397 BasicBlock *BB = (*I)->getBlock();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002398 DOUT << "Switch thinking about BB %" << BB->getName()
Nick Lewycky26e25d32007-06-24 04:36:20 +00002399 << "(" << PS->DTDFS->getNodeForBlock(BB)->getDFSNumIn() << ")\n";
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002400
Nick Lewycky73dd6922007-07-05 03:15:00 +00002401 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, BB);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002402 if (BB == SI.getDefaultDest()) {
2403 for (unsigned i = 1, e = SI.getNumCases(); i < e; ++i)
2404 if (SI.getSuccessor(i) != BB)
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002405 VRP.add(Condition, SI.getCaseValue(i), ICmpInst::ICMP_NE);
2406 VRP.solve();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002407 } else if (ConstantInt *CI = SI.findCaseDest(BB)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002408 VRP.add(Condition, CI, ICmpInst::ICMP_EQ);
2409 VRP.solve();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002410 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002411 PS->proceedToSuccessor(*I);
Nick Lewycky1d00f3e2006-10-03 15:19:11 +00002412 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002413 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002414
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002415 void PredicateSimplifier::Forwards::visitAllocaInst(AllocaInst &AI) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002416 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &AI);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002417 VRP.add(Constant::getNullValue(AI.getType()), &AI, ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002418 VRP.solve();
2419 }
Nick Lewyckyf3450082006-10-22 19:53:27 +00002420
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002421 void PredicateSimplifier::Forwards::visitLoadInst(LoadInst &LI) {
2422 Value *Ptr = LI.getPointerOperand();
2423 // avoid "load uint* null" -> null NE null.
2424 if (isa<Constant>(Ptr)) return;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002425
Nick Lewycky73dd6922007-07-05 03:15:00 +00002426 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &LI);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002427 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002428 VRP.solve();
2429 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002430
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002431 void PredicateSimplifier::Forwards::visitStoreInst(StoreInst &SI) {
2432 Value *Ptr = SI.getPointerOperand();
2433 if (isa<Constant>(Ptr)) return;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002434
Nick Lewycky73dd6922007-07-05 03:15:00 +00002435 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002436 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002437 VRP.solve();
2438 }
2439
Nick Lewycky15245952007-02-04 23:43:05 +00002440 void PredicateSimplifier::Forwards::visitSExtInst(SExtInst &SI) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002441 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
Reid Spencerc34dedf2007-03-03 00:48:31 +00002442 uint32_t SrcBitWidth = cast<IntegerType>(SI.getSrcTy())->getBitWidth();
2443 uint32_t DstBitWidth = cast<IntegerType>(SI.getDestTy())->getBitWidth();
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00002444 APInt Min(APInt::getHighBitsSet(DstBitWidth, DstBitWidth-SrcBitWidth+1));
2445 APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth-1));
Reid Spencerc34dedf2007-03-03 00:48:31 +00002446 VRP.add(ConstantInt::get(Min), &SI, ICmpInst::ICMP_SLE);
2447 VRP.add(ConstantInt::get(Max), &SI, ICmpInst::ICMP_SGE);
Nick Lewycky15245952007-02-04 23:43:05 +00002448 VRP.solve();
2449 }
2450
2451 void PredicateSimplifier::Forwards::visitZExtInst(ZExtInst &ZI) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002452 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &ZI);
Reid Spencerc34dedf2007-03-03 00:48:31 +00002453 uint32_t SrcBitWidth = cast<IntegerType>(ZI.getSrcTy())->getBitWidth();
2454 uint32_t DstBitWidth = cast<IntegerType>(ZI.getDestTy())->getBitWidth();
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00002455 APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth));
Reid Spencerc34dedf2007-03-03 00:48:31 +00002456 VRP.add(ConstantInt::get(Max), &ZI, ICmpInst::ICMP_UGE);
Nick Lewycky15245952007-02-04 23:43:05 +00002457 VRP.solve();
2458 }
2459
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002460 void PredicateSimplifier::Forwards::visitBinaryOperator(BinaryOperator &BO) {
2461 Instruction::BinaryOps ops = BO.getOpcode();
2462
2463 switch (ops) {
Nick Lewycky4f73de22007-03-16 02:37:39 +00002464 default: break;
Nick Lewycky15245952007-02-04 23:43:05 +00002465 case Instruction::URem:
2466 case Instruction::SRem:
2467 case Instruction::UDiv:
2468 case Instruction::SDiv: {
2469 Value *Divisor = BO.getOperand(1);
Nick Lewycky73dd6922007-07-05 03:15:00 +00002470 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky15245952007-02-04 23:43:05 +00002471 VRP.add(Constant::getNullValue(Divisor->getType()), Divisor,
2472 ICmpInst::ICMP_NE);
2473 VRP.solve();
2474 break;
2475 }
Nick Lewycky4f73de22007-03-16 02:37:39 +00002476 }
2477
2478 switch (ops) {
2479 default: break;
2480 case Instruction::Shl: {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002481 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002482 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
2483 VRP.solve();
2484 } break;
2485 case Instruction::AShr: {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002486 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002487 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_SLE);
2488 VRP.solve();
2489 } break;
2490 case Instruction::LShr:
2491 case Instruction::UDiv: {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002492 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002493 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
2494 VRP.solve();
2495 } break;
2496 case Instruction::URem: {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002497 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002498 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
2499 VRP.solve();
2500 } break;
2501 case Instruction::And: {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002502 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002503 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
2504 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
2505 VRP.solve();
2506 } break;
2507 case Instruction::Or: {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002508 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002509 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
2510 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_UGE);
2511 VRP.solve();
2512 } break;
2513 }
2514 }
2515
2516 void PredicateSimplifier::Forwards::visitICmpInst(ICmpInst &IC) {
2517 // If possible, squeeze the ICmp predicate into something simpler.
2518 // Eg., if x = [0, 4) and we're being asked icmp uge %x, 3 then change
2519 // the predicate to eq.
2520
Nick Lewyckyeeb01b42007-04-07 02:30:14 +00002521 // XXX: once we do full PHI handling, modifying the instruction in the
2522 // Forwards visitor will cause missed optimizations.
2523
Nick Lewycky4f73de22007-03-16 02:37:39 +00002524 ICmpInst::Predicate Pred = IC.getPredicate();
2525
Nick Lewyckyeeb01b42007-04-07 02:30:14 +00002526 switch (Pred) {
2527 default: break;
2528 case ICmpInst::ICMP_ULE: Pred = ICmpInst::ICMP_ULT; break;
2529 case ICmpInst::ICMP_UGE: Pred = ICmpInst::ICMP_UGT; break;
2530 case ICmpInst::ICMP_SLE: Pred = ICmpInst::ICMP_SLT; break;
2531 case ICmpInst::ICMP_SGE: Pred = ICmpInst::ICMP_SGT; break;
2532 }
2533 if (Pred != IC.getPredicate()) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002534 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &IC);
Nick Lewyckyeeb01b42007-04-07 02:30:14 +00002535 if (VRP.isRelatedBy(IC.getOperand(1), IC.getOperand(0),
2536 ICmpInst::ICMP_NE)) {
2537 ++NumSnuggle;
2538 PS->modified = true;
2539 IC.setPredicate(Pred);
2540 }
2541 }
2542
2543 Pred = IC.getPredicate();
2544
Nick Lewycky4f73de22007-03-16 02:37:39 +00002545 if (ConstantInt *Op1 = dyn_cast<ConstantInt>(IC.getOperand(1))) {
2546 ConstantInt *NextVal = 0;
Nick Lewyckyeeb01b42007-04-07 02:30:14 +00002547 switch (Pred) {
Nick Lewycky4f73de22007-03-16 02:37:39 +00002548 default: break;
2549 case ICmpInst::ICMP_SLT:
2550 case ICmpInst::ICMP_ULT:
2551 if (Op1->getValue() != 0)
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00002552 NextVal = ConstantInt::get(Op1->getValue()-1);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002553 break;
2554 case ICmpInst::ICMP_SGT:
2555 case ICmpInst::ICMP_UGT:
2556 if (!Op1->getValue().isAllOnesValue())
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00002557 NextVal = ConstantInt::get(Op1->getValue()+1);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002558 break;
2559
2560 }
2561 if (NextVal) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002562 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &IC);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002563 if (VRP.isRelatedBy(IC.getOperand(0), NextVal,
2564 ICmpInst::getInversePredicate(Pred))) {
2565 ICmpInst *NewIC = new ICmpInst(ICmpInst::ICMP_EQ, IC.getOperand(0),
2566 NextVal, "", &IC);
2567 NewIC->takeName(&IC);
2568 IC.replaceAllUsesWith(NewIC);
Nick Lewycky73dd6922007-07-05 03:15:00 +00002569
2570 // XXX: prove this isn't necessary
2571 if (unsigned n = VN.valueNumber(&IC, PS->DTDFS->getRootNode()))
2572 if (VN.value(n) == &IC) IG.remove(n);
2573 VN.remove(&IC);
2574
Nick Lewycky4f73de22007-03-16 02:37:39 +00002575 IC.eraseFromParent();
2576 ++NumSnuggle;
2577 PS->modified = true;
Nick Lewycky4f73de22007-03-16 02:37:39 +00002578 }
2579 }
2580 }
Nick Lewycky5f8f9af2006-08-30 02:46:48 +00002581 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002582
Devang Patel8c78a0b2007-05-03 01:11:54 +00002583 char PredicateSimplifier::ID = 0;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002584 RegisterPass<PredicateSimplifier> X("predsimplify",
2585 "Predicate Simplifier");
2586}
2587
2588FunctionPass *llvm::createPredicateSimplifierPass() {
2589 return new PredicateSimplifier();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002590}