blob: 3723bcbb0a6d9451645f448a3d930f19468c3d6d [file] [log] [blame]
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001//===-- PredicateSimplifier.cpp - Path Sensitive Simplifier ---------------===//
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Nick Lewycky and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00008//===----------------------------------------------------------------------===//
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00009//
10// Path-sensitive optimizer. In a branch where x == y, replace uses of
11// x with y. Permits further optimization, such as the elimination of
12// the unreachable call:
13//
14// void test(int *p, int *q)
15// {
16// if (p != q)
17// return;
18//
19// if (*p != *q)
20// foo(); // unreachable
21// }
22//
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000023//===----------------------------------------------------------------------===//
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000024//
Nick Lewycky4f73de22007-03-16 02:37:39 +000025// The InequalityGraph focusses on four properties; equals, not equals,
26// less-than and less-than-or-equals-to. The greater-than forms are also held
27// just to allow walking from a lesser node to a greater one. These properties
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000028// are stored in a lattice; LE can become LT or EQ, NE can become LT or GT.
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000029//
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000030// These relationships define a graph between values of the same type. Each
31// Value is stored in a map table that retrieves the associated Node. This
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +000032// is how EQ relationships are stored; the map contains pointers from equal
33// Value to the same node. The node contains a most canonical Value* form
34// and the list of known relationships with other nodes.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000035//
36// If two nodes are known to be inequal, then they will contain pointers to
37// each other with an "NE" relationship. If node getNode(%x) is less than
38// getNode(%y), then the %x node will contain <%y, GT> and %y will contain
39// <%x, LT>. This allows us to tie nodes together into a graph like this:
40//
41// %a < %b < %c < %d
42//
43// with four nodes representing the properties. The InequalityGraph provides
Nick Lewycky2fc338f2007-01-11 02:32:38 +000044// querying with "isRelatedBy" and mutators "addEquality" and "addInequality".
45// To find a relationship, we start with one of the nodes any binary search
46// through its list to find where the relationships with the second node start.
47// Then we iterate through those to find the first relationship that dominates
48// our context node.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000049//
50// To create these properties, we wait until a branch or switch instruction
51// implies that a particular value is true (or false). The VRPSolver is
52// responsible for analyzing the variable and seeing what new inferences
53// can be made from each property. For example:
54//
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +000055// %P = icmp ne i32* %ptr, null
56// %a = and i1 %P, %Q
57// br i1 %a label %cond_true, label %cond_false
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000058//
59// For the true branch, the VRPSolver will start with %a EQ true and look at
60// the definition of %a and find that it can infer that %P and %Q are both
61// true. From %P being true, it can infer that %ptr NE null. For the false
Nick Lewycky56639802007-01-29 02:56:54 +000062// branch it can't infer anything from the "and" instruction.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000063//
64// Besides branches, we can also infer properties from instruction that may
65// have undefined behaviour in certain cases. For example, the dividend of
66// a division may never be zero. After the division instruction, we may assume
67// that the dividend is not equal to zero.
68//
69//===----------------------------------------------------------------------===//
Nick Lewycky4f73de22007-03-16 02:37:39 +000070//
71// The ValueRanges class stores the known integer bounds of a Value. When we
72// encounter i8 %a u< %b, the ValueRanges stores that %a = [1, 255] and
Nick Lewycky20f08112007-08-04 18:45:32 +000073// %b = [0, 254].
Nick Lewycky4f73de22007-03-16 02:37:39 +000074//
75// It never stores an empty range, because that means that the code is
76// unreachable. It never stores a single-element range since that's an equality
Nick Lewycky12d44ab2007-04-07 03:16:12 +000077// relationship and better stored in the InequalityGraph, nor an empty range
78// since that is better stored in UnreachableBlocks.
Nick Lewycky4f73de22007-03-16 02:37:39 +000079//
80//===----------------------------------------------------------------------===//
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000081
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000082#define DEBUG_TYPE "predsimplify"
83#include "llvm/Transforms/Scalar.h"
84#include "llvm/Constants.h"
Nick Lewyckyf3450082006-10-22 19:53:27 +000085#include "llvm/DerivedTypes.h"
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000086#include "llvm/Instructions.h"
87#include "llvm/Pass.h"
Nick Lewycky2fc338f2007-01-11 02:32:38 +000088#include "llvm/ADT/DepthFirstIterator.h"
Nick Lewycky09b7e4d2006-11-22 23:49:16 +000089#include "llvm/ADT/SetOperations.h"
Reid Spencer3f4e6e82007-02-04 00:40:42 +000090#include "llvm/ADT/SetVector.h"
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000091#include "llvm/ADT/Statistic.h"
92#include "llvm/ADT/STLExtras.h"
93#include "llvm/Analysis/Dominators.h"
Nick Lewyckye635cc42007-07-10 03:28:21 +000094#include "llvm/Assembly/Writer.h"
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000095#include "llvm/Support/CFG.h"
Chris Lattnerf06bb652006-12-06 18:14:47 +000096#include "llvm/Support/Compiler.h"
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +000097#include "llvm/Support/ConstantRange.h"
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +000098#include "llvm/Support/Debug.h"
Nick Lewycky77e030b2006-10-12 02:02:44 +000099#include "llvm/Support/InstVisitor.h"
Nick Lewycky12d44ab2007-04-07 03:16:12 +0000100#include "llvm/Target/TargetData.h"
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000101#include "llvm/Transforms/Utils/Local.h"
102#include <algorithm>
103#include <deque>
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000104#include <sstream>
Nick Lewycky26e25d32007-06-24 04:36:20 +0000105#include <stack>
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000106using namespace llvm;
107
Chris Lattner0e5255b2006-12-19 21:49:03 +0000108STATISTIC(NumVarsReplaced, "Number of argument substitutions");
109STATISTIC(NumInstruction , "Number of instructions removed");
110STATISTIC(NumSimple , "Number of simple replacements");
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000111STATISTIC(NumBlocks , "Number of blocks marked unreachable");
Nick Lewycky4f73de22007-03-16 02:37:39 +0000112STATISTIC(NumSnuggle , "Number of comparisons snuggled");
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000113
Chris Lattner0e5255b2006-12-19 21:49:03 +0000114namespace {
Nick Lewycky26e25d32007-06-24 04:36:20 +0000115 class DomTreeDFS {
116 public:
117 class Node {
118 friend class DomTreeDFS;
119 public:
120 typedef std::vector<Node *>::iterator iterator;
121 typedef std::vector<Node *>::const_iterator const_iterator;
122
123 unsigned getDFSNumIn() const { return DFSin; }
124 unsigned getDFSNumOut() const { return DFSout; }
125
126 BasicBlock *getBlock() const { return BB; }
127
128 iterator begin() { return Children.begin(); }
129 iterator end() { return Children.end(); }
130
131 const_iterator begin() const { return Children.begin(); }
132 const_iterator end() const { return Children.end(); }
133
134 bool dominates(const Node *N) const {
135 return DFSin <= N->DFSin && DFSout >= N->DFSout;
136 }
137
138 bool DominatedBy(const Node *N) const {
139 return N->dominates(this);
140 }
141
142 /// Sorts by the number of descendants. With this, you can iterate
143 /// through a sorted list and the first matching entry is the most
144 /// specific match for your basic block. The order provided is stable;
145 /// DomTreeDFS::Nodes with the same number of descendants are sorted by
146 /// DFS in number.
147 bool operator<(const Node &N) const {
148 unsigned spread = DFSout - DFSin;
149 unsigned N_spread = N.DFSout - N.DFSin;
150 if (spread == N_spread) return DFSin < N.DFSin;
Nick Lewycky73dd6922007-07-05 03:15:00 +0000151 return spread < N_spread;
Nick Lewycky26e25d32007-06-24 04:36:20 +0000152 }
153 bool operator>(const Node &N) const { return N < *this; }
154
155 private:
156 unsigned DFSin, DFSout;
157 BasicBlock *BB;
158
159 std::vector<Node *> Children;
160 };
161
162 // XXX: this may be slow. Instead of using "new" for each node, consider
163 // putting them in a vector to keep them contiguous.
164 explicit DomTreeDFS(DominatorTree *DT) {
165 std::stack<std::pair<Node *, DomTreeNode *> > S;
166
167 Entry = new Node;
168 Entry->BB = DT->getRootNode()->getBlock();
169 S.push(std::make_pair(Entry, DT->getRootNode()));
170
171 NodeMap[Entry->BB] = Entry;
172
173 while (!S.empty()) {
174 std::pair<Node *, DomTreeNode *> &Pair = S.top();
175 Node *N = Pair.first;
176 DomTreeNode *DTNode = Pair.second;
177 S.pop();
178
179 for (DomTreeNode::iterator I = DTNode->begin(), E = DTNode->end();
180 I != E; ++I) {
181 Node *NewNode = new Node;
182 NewNode->BB = (*I)->getBlock();
183 N->Children.push_back(NewNode);
184 S.push(std::make_pair(NewNode, *I));
185
186 NodeMap[NewNode->BB] = NewNode;
187 }
188 }
189
190 renumber();
191
192#ifndef NDEBUG
193 DEBUG(dump());
194#endif
195 }
196
197#ifndef NDEBUG
198 virtual
199#endif
200 ~DomTreeDFS() {
201 std::stack<Node *> S;
202
203 S.push(Entry);
204 while (!S.empty()) {
205 Node *N = S.top(); S.pop();
206
207 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I)
208 S.push(*I);
209
210 delete N;
211 }
212 }
213
Nick Lewyckyb7c0c8a2007-07-16 02:58:37 +0000214 /// getRootNode - This returns the entry node for the CFG of the function.
Nick Lewycky26e25d32007-06-24 04:36:20 +0000215 Node *getRootNode() const { return Entry; }
216
Nick Lewyckyb7c0c8a2007-07-16 02:58:37 +0000217 /// getNodeForBlock - return the node for the specified basic block.
Nick Lewycky26e25d32007-06-24 04:36:20 +0000218 Node *getNodeForBlock(BasicBlock *BB) const {
219 if (!NodeMap.count(BB)) return 0;
Nick Lewycky73dd6922007-07-05 03:15:00 +0000220 return const_cast<DomTreeDFS*>(this)->NodeMap[BB];
Nick Lewycky26e25d32007-06-24 04:36:20 +0000221 }
222
Nick Lewyckyb7c0c8a2007-07-16 02:58:37 +0000223 /// dominates - returns true if the basic block for I1 dominates that of
224 /// the basic block for I2. If the instructions belong to the same basic
225 /// block, the instruction first instruction sequentially in the block is
226 /// considered dominating.
Nick Lewycky26e25d32007-06-24 04:36:20 +0000227 bool dominates(Instruction *I1, Instruction *I2) {
228 BasicBlock *BB1 = I1->getParent(),
229 *BB2 = I2->getParent();
230 if (BB1 == BB2) {
231 if (isa<TerminatorInst>(I1)) return false;
232 if (isa<TerminatorInst>(I2)) return true;
233 if ( isa<PHINode>(I1) && !isa<PHINode>(I2)) return true;
234 if (!isa<PHINode>(I1) && isa<PHINode>(I2)) return false;
235
236 for (BasicBlock::const_iterator I = BB2->begin(), E = BB2->end();
237 I != E; ++I) {
238 if (&*I == I1) return true;
239 else if (&*I == I2) return false;
240 }
241 assert(!"Instructions not found in parent BasicBlock?");
242 } else {
Nick Lewycky0f986fd2007-06-24 04:40:16 +0000243 Node *Node1 = getNodeForBlock(BB1),
Nick Lewycky26e25d32007-06-24 04:36:20 +0000244 *Node2 = getNodeForBlock(BB2);
Nick Lewycky73dd6922007-07-05 03:15:00 +0000245 return Node1 && Node2 && Node1->dominates(Node2);
Nick Lewycky26e25d32007-06-24 04:36:20 +0000246 }
247 }
Nick Lewyckyb7c0c8a2007-07-16 02:58:37 +0000248
Nick Lewycky26e25d32007-06-24 04:36:20 +0000249 private:
Nick Lewyckyb7c0c8a2007-07-16 02:58:37 +0000250 /// renumber - calculates the depth first search numberings and applies
251 /// them onto the nodes.
Nick Lewycky26e25d32007-06-24 04:36:20 +0000252 void renumber() {
253 std::stack<std::pair<Node *, Node::iterator> > S;
254 unsigned n = 0;
255
256 Entry->DFSin = ++n;
257 S.push(std::make_pair(Entry, Entry->begin()));
258
259 while (!S.empty()) {
260 std::pair<Node *, Node::iterator> &Pair = S.top();
261 Node *N = Pair.first;
262 Node::iterator &I = Pair.second;
263
264 if (I == N->end()) {
265 N->DFSout = ++n;
266 S.pop();
267 } else {
268 Node *Next = *I++;
269 Next->DFSin = ++n;
270 S.push(std::make_pair(Next, Next->begin()));
271 }
272 }
273 }
274
275#ifndef NDEBUG
276 virtual void dump() const {
277 dump(*cerr.stream());
278 }
279
280 void dump(std::ostream &os) const {
281 os << "Predicate simplifier DomTreeDFS: \n";
282 dump(Entry, 0, os);
283 os << "\n\n";
284 }
285
286 void dump(Node *N, int depth, std::ostream &os) const {
287 ++depth;
288 for (int i = 0; i < depth; ++i) { os << " "; }
289 os << "[" << depth << "] ";
290
291 os << N->getBlock()->getName() << " (" << N->getDFSNumIn()
292 << ", " << N->getDFSNumOut() << ")\n";
293
294 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I)
295 dump(*I, depth, os);
296 }
297#endif
298
299 Node *Entry;
300 std::map<BasicBlock *, Node *> NodeMap;
301 };
302
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000303 // SLT SGT ULT UGT EQ
304 // 0 1 0 1 0 -- GT 10
305 // 0 1 0 1 1 -- GE 11
306 // 0 1 1 0 0 -- SGTULT 12
307 // 0 1 1 0 1 -- SGEULE 13
Nick Lewycky56639802007-01-29 02:56:54 +0000308 // 0 1 1 1 0 -- SGT 14
309 // 0 1 1 1 1 -- SGE 15
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000310 // 1 0 0 1 0 -- SLTUGT 18
311 // 1 0 0 1 1 -- SLEUGE 19
312 // 1 0 1 0 0 -- LT 20
313 // 1 0 1 0 1 -- LE 21
Nick Lewycky56639802007-01-29 02:56:54 +0000314 // 1 0 1 1 0 -- SLT 22
315 // 1 0 1 1 1 -- SLE 23
316 // 1 1 0 1 0 -- UGT 26
317 // 1 1 0 1 1 -- UGE 27
318 // 1 1 1 0 0 -- ULT 28
319 // 1 1 1 0 1 -- ULE 29
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000320 // 1 1 1 1 0 -- NE 30
321 enum LatticeBits {
322 EQ_BIT = 1, UGT_BIT = 2, ULT_BIT = 4, SGT_BIT = 8, SLT_BIT = 16
323 };
324 enum LatticeVal {
325 GT = SGT_BIT | UGT_BIT,
326 GE = GT | EQ_BIT,
327 LT = SLT_BIT | ULT_BIT,
328 LE = LT | EQ_BIT,
329 NE = SLT_BIT | SGT_BIT | ULT_BIT | UGT_BIT,
330 SGTULT = SGT_BIT | ULT_BIT,
331 SGEULE = SGTULT | EQ_BIT,
332 SLTUGT = SLT_BIT | UGT_BIT,
333 SLEUGE = SLTUGT | EQ_BIT,
Nick Lewycky56639802007-01-29 02:56:54 +0000334 ULT = SLT_BIT | SGT_BIT | ULT_BIT,
335 UGT = SLT_BIT | SGT_BIT | UGT_BIT,
336 SLT = SLT_BIT | ULT_BIT | UGT_BIT,
337 SGT = SGT_BIT | ULT_BIT | UGT_BIT,
338 SLE = SLT | EQ_BIT,
339 SGE = SGT | EQ_BIT,
340 ULE = ULT | EQ_BIT,
341 UGE = UGT | EQ_BIT
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000342 };
343
Nick Lewycky20f08112007-08-04 18:45:32 +0000344 /// validPredicate - determines whether a given value is actually a lattice
345 /// value. Only used in assertions or debugging.
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000346 static bool validPredicate(LatticeVal LV) {
347 switch (LV) {
Nick Lewycky15245952007-02-04 23:43:05 +0000348 case GT: case GE: case LT: case LE: case NE:
349 case SGTULT: case SGT: case SGEULE:
350 case SLTUGT: case SLT: case SLEUGE:
351 case ULT: case UGT:
352 case SLE: case SGE: case ULE: case UGE:
353 return true;
354 default:
355 return false;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000356 }
357 }
358
359 /// reversePredicate - reverse the direction of the inequality
360 static LatticeVal reversePredicate(LatticeVal LV) {
361 unsigned reverse = LV ^ (SLT_BIT|SGT_BIT|ULT_BIT|UGT_BIT); //preserve EQ_BIT
Nick Lewycky4f73de22007-03-16 02:37:39 +0000362
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000363 if ((reverse & (SLT_BIT|SGT_BIT)) == 0)
364 reverse |= (SLT_BIT|SGT_BIT);
365
366 if ((reverse & (ULT_BIT|UGT_BIT)) == 0)
367 reverse |= (ULT_BIT|UGT_BIT);
368
369 LatticeVal Rev = static_cast<LatticeVal>(reverse);
370 assert(validPredicate(Rev) && "Failed reversing predicate.");
371 return Rev;
372 }
373
Nick Lewycky73dd6922007-07-05 03:15:00 +0000374 /// ValueNumbering stores the scope-specific value numbers for a given Value.
375 class VISIBILITY_HIDDEN ValueNumbering {
Nick Lewycky20f08112007-08-04 18:45:32 +0000376
377 /// VNPair is a tuple of {Value, index number, DomTreeDFS::Node}. It
378 /// includes the comparison operators necessary to allow you to store it
379 /// in a sorted vector.
Nick Lewycky73dd6922007-07-05 03:15:00 +0000380 class VISIBILITY_HIDDEN VNPair {
381 public:
382 Value *V;
383 unsigned index;
384 DomTreeDFS::Node *Subtree;
385
386 VNPair(Value *V, unsigned index, DomTreeDFS::Node *Subtree)
387 : V(V), index(index), Subtree(Subtree) {}
388
389 bool operator==(const VNPair &RHS) const {
390 return V == RHS.V && Subtree == RHS.Subtree;
391 }
392
393 bool operator<(const VNPair &RHS) const {
394 if (V != RHS.V) return V < RHS.V;
395 return *Subtree < *RHS.Subtree;
396 }
397
398 bool operator<(Value *RHS) const {
399 return V < RHS;
400 }
Nick Lewycky20f08112007-08-04 18:45:32 +0000401
402 bool operator>(Value *RHS) const {
403 return V > RHS;
404 }
405
406 friend bool operator<(Value *RHS, const VNPair &pair) {
407 return pair.operator>(RHS);
408 }
Nick Lewycky73dd6922007-07-05 03:15:00 +0000409 };
410
411 typedef std::vector<VNPair> VNMapType;
412 VNMapType VNMap;
413
Nick Lewycky20f08112007-08-04 18:45:32 +0000414 /// The canonical choice for value number at index.
Nick Lewycky73dd6922007-07-05 03:15:00 +0000415 std::vector<Value *> Values;
416
417 DomTreeDFS *DTDFS;
418
419 public:
Nick Lewyckye635cc42007-07-10 03:28:21 +0000420#ifndef NDEBUG
421 virtual ~ValueNumbering() {}
422 virtual void dump() {
423 dump(*cerr.stream());
424 }
425
426 void dump(std::ostream &os) {
427 for (unsigned i = 1; i <= Values.size(); ++i) {
428 os << i << " = ";
429 WriteAsOperand(os, Values[i-1]);
430 os << " {";
431 for (unsigned j = 0; j < VNMap.size(); ++j) {
432 if (VNMap[j].index == i) {
433 WriteAsOperand(os, VNMap[j].V);
434 os << " (" << VNMap[j].Subtree->getDFSNumIn() << ") ";
435 }
436 }
437 os << "}\n";
438 }
439 }
440#endif
441
Nick Lewycky73dd6922007-07-05 03:15:00 +0000442 /// compare - returns true if V1 is a better canonical value than V2.
443 bool compare(Value *V1, Value *V2) const {
444 if (isa<Constant>(V1))
445 return !isa<Constant>(V2);
446 else if (isa<Constant>(V2))
447 return false;
448 else if (isa<Argument>(V1))
449 return !isa<Argument>(V2);
450 else if (isa<Argument>(V2))
451 return false;
452
453 Instruction *I1 = dyn_cast<Instruction>(V1);
454 Instruction *I2 = dyn_cast<Instruction>(V2);
455
456 if (!I1 || !I2)
457 return V1->getNumUses() < V2->getNumUses();
458
459 return DTDFS->dominates(I1, I2);
460 }
461
462 ValueNumbering(DomTreeDFS *DTDFS) : DTDFS(DTDFS) {}
463
464 /// valueNumber - finds the value number for V under the Subtree. If
465 /// there is no value number, returns zero.
466 unsigned valueNumber(Value *V, DomTreeDFS::Node *Subtree) {
Nick Lewyckye635cc42007-07-10 03:28:21 +0000467 if (!(isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V))
468 || V->getType() == Type::VoidTy) return 0;
469
Nick Lewycky73dd6922007-07-05 03:15:00 +0000470 VNMapType::iterator E = VNMap.end();
471 VNPair pair(V, 0, Subtree);
472 VNMapType::iterator I = std::lower_bound(VNMap.begin(), E, pair);
473 while (I != E && I->V == V) {
474 if (I->Subtree->dominates(Subtree))
475 return I->index;
476 ++I;
477 }
478 return 0;
479 }
480
Nick Lewyckye635cc42007-07-10 03:28:21 +0000481 /// getOrInsertVN - always returns a value number, creating it if necessary.
482 unsigned getOrInsertVN(Value *V, DomTreeDFS::Node *Subtree) {
483 if (unsigned n = valueNumber(V, Subtree))
484 return n;
485 else
486 return newVN(V);
487 }
488
Nick Lewycky73dd6922007-07-05 03:15:00 +0000489 /// newVN - creates a new value number. Value V must not already have a
490 /// value number assigned.
491 unsigned newVN(Value *V) {
Nick Lewyckye635cc42007-07-10 03:28:21 +0000492 assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
493 "Bad Value for value numbering.");
494 assert(V->getType() != Type::VoidTy && "Won't value number a void value");
495
Nick Lewycky73dd6922007-07-05 03:15:00 +0000496 Values.push_back(V);
497
498 VNPair pair = VNPair(V, Values.size(), DTDFS->getRootNode());
Nick Lewyckye635cc42007-07-10 03:28:21 +0000499 VNMapType::iterator I = std::lower_bound(VNMap.begin(), VNMap.end(), pair);
500 assert((I == VNMap.end() || value(I->index) != V) &&
Nick Lewycky73dd6922007-07-05 03:15:00 +0000501 "Attempt to create a duplicate value number.");
Nick Lewyckye635cc42007-07-10 03:28:21 +0000502 VNMap.insert(I, pair);
Nick Lewycky73dd6922007-07-05 03:15:00 +0000503
504 return Values.size();
505 }
506
507 /// value - returns the Value associated with a value number.
508 Value *value(unsigned index) const {
509 assert(index != 0 && "Zero index is reserved for not found.");
510 assert(index <= Values.size() && "Index out of range.");
511 return Values[index-1];
512 }
513
514 /// canonicalize - return a Value that is equal to V under Subtree.
515 Value *canonicalize(Value *V, DomTreeDFS::Node *Subtree) {
516 if (isa<Constant>(V)) return V;
517
518 if (unsigned n = valueNumber(V, Subtree))
519 return value(n);
520 else
521 return V;
522 }
523
524 /// addEquality - adds that value V belongs to the set of equivalent
525 /// values defined by value number n under Subtree.
526 void addEquality(unsigned n, Value *V, DomTreeDFS::Node *Subtree) {
527 assert(canonicalize(value(n), Subtree) == value(n) &&
528 "Node's 'canonical' choice isn't best within this subtree.");
529
530 // Suppose that we are given "%x -> node #1 (%y)". The problem is that
531 // we may already have "%z -> node #2 (%x)" somewhere above us in the
532 // graph. We need to find those edges and add "%z -> node #1 (%y)"
533 // to keep the lookups canonical.
534
535 std::vector<Value *> ToRepoint(1, V);
536
537 if (unsigned Conflict = valueNumber(V, Subtree)) {
538 for (VNMapType::iterator I = VNMap.begin(), E = VNMap.end();
539 I != E; ++I) {
540 if (I->index == Conflict && I->Subtree->dominates(Subtree))
541 ToRepoint.push_back(I->V);
542 }
543 }
544
545 for (std::vector<Value *>::iterator VI = ToRepoint.begin(),
546 VE = ToRepoint.end(); VI != VE; ++VI) {
547 Value *V = *VI;
548
549 VNPair pair(V, n, Subtree);
550 VNMapType::iterator B = VNMap.begin(), E = VNMap.end();
551 VNMapType::iterator I = std::lower_bound(B, E, pair);
552 if (I != E && I->V == V && I->Subtree == Subtree)
553 I->index = n; // Update best choice
Nick Lewyckye635cc42007-07-10 03:28:21 +0000554 else
Nick Lewycky73dd6922007-07-05 03:15:00 +0000555 VNMap.insert(I, pair); // New Value
556
557 // XXX: we currently don't have to worry about updating values with
558 // more specific Subtrees, but we will need to for PHI node support.
559
560#ifndef NDEBUG
561 Value *V_n = value(n);
562 if (isa<Constant>(V) && isa<Constant>(V_n)) {
563 assert(V == V_n && "Constant equals different constant?");
564 }
565#endif
566 }
567 }
568
569 /// remove - removes all references to value V.
570 void remove(Value *V) {
Nick Lewyckye635cc42007-07-10 03:28:21 +0000571 VNMapType::iterator B = VNMap.begin(), E = VNMap.end();
Nick Lewycky73dd6922007-07-05 03:15:00 +0000572 VNPair pair(V, 0, DTDFS->getRootNode());
Nick Lewyckye635cc42007-07-10 03:28:21 +0000573 VNMapType::iterator J = std::upper_bound(B, E, pair);
Nick Lewycky73dd6922007-07-05 03:15:00 +0000574 VNMapType::iterator I = J;
575
Nick Lewyckye635cc42007-07-10 03:28:21 +0000576 while (I != B && (I == E || I->V == V)) --I;
Nick Lewycky73dd6922007-07-05 03:15:00 +0000577
578 VNMap.erase(I, J);
579 }
580 };
581
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000582 /// The InequalityGraph stores the relationships between values.
583 /// Each Value in the graph is assigned to a Node. Nodes are pointer
584 /// comparable for equality. The caller is expected to maintain the logical
585 /// consistency of the system.
586 ///
587 /// The InequalityGraph class may invalidate Node*s after any mutator call.
588 /// @brief The InequalityGraph stores the relationships between values.
589 class VISIBILITY_HIDDEN InequalityGraph {
Nick Lewycky73dd6922007-07-05 03:15:00 +0000590 ValueNumbering &VN;
Nick Lewycky26e25d32007-06-24 04:36:20 +0000591 DomTreeDFS::Node *TreeRoot;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000592
593 InequalityGraph(); // DO NOT IMPLEMENT
594 InequalityGraph(InequalityGraph &); // DO NOT IMPLEMENT
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000595 public:
Nick Lewycky73dd6922007-07-05 03:15:00 +0000596 InequalityGraph(ValueNumbering &VN, DomTreeDFS::Node *TreeRoot)
597 : VN(VN), TreeRoot(TreeRoot) {}
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000598
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000599 class Node;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000600
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000601 /// An Edge is contained inside a Node making one end of the edge implicit
602 /// and contains a pointer to the other end. The edge contains a lattice
Nick Lewycky26e25d32007-06-24 04:36:20 +0000603 /// value specifying the relationship and an DomTreeDFS::Node specifying
604 /// the root in the dominator tree to which this edge applies.
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000605 class VISIBILITY_HIDDEN Edge {
606 public:
Nick Lewycky26e25d32007-06-24 04:36:20 +0000607 Edge(unsigned T, LatticeVal V, DomTreeDFS::Node *ST)
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000608 : To(T), LV(V), Subtree(ST) {}
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000609
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000610 unsigned To;
611 LatticeVal LV;
Nick Lewycky26e25d32007-06-24 04:36:20 +0000612 DomTreeDFS::Node *Subtree;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000613
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000614 bool operator<(const Edge &edge) const {
615 if (To != edge.To) return To < edge.To;
Nick Lewycky73dd6922007-07-05 03:15:00 +0000616 return *Subtree < *edge.Subtree;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000617 }
Nick Lewycky26e25d32007-06-24 04:36:20 +0000618
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000619 bool operator<(unsigned to) const {
620 return To < to;
621 }
Nick Lewycky26e25d32007-06-24 04:36:20 +0000622
Bill Wendling6357bf22007-06-04 23:52:59 +0000623 bool operator>(unsigned to) const {
624 return To > to;
625 }
626
627 friend bool operator<(unsigned to, const Edge &edge) {
628 return edge.operator>(to);
629 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000630 };
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000631
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000632 /// A single node in the InequalityGraph. This stores the canonical Value
633 /// for the node, as well as the relationships with the neighbours.
634 ///
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000635 /// @brief A single node in the InequalityGraph.
636 class VISIBILITY_HIDDEN Node {
637 friend class InequalityGraph;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000638
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000639 typedef SmallVector<Edge, 4> RelationsType;
640 RelationsType Relations;
641
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000642 // TODO: can this idea improve performance?
643 //friend class std::vector<Node>;
644 //Node(Node &N) { RelationsType.swap(N.RelationsType); }
645
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000646 public:
647 typedef RelationsType::iterator iterator;
648 typedef RelationsType::const_iterator const_iterator;
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000649
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000650#ifndef NDEBUG
Nick Lewycky5d6ede52007-01-11 02:38:21 +0000651 virtual ~Node() {}
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000652 virtual void dump() const {
653 dump(*cerr.stream());
654 }
655 private:
Nick Lewycky73dd6922007-07-05 03:15:00 +0000656 void dump(std::ostream &os) const {
657 static const std::string names[32] =
658 { "000000", "000001", "000002", "000003", "000004", "000005",
659 "000006", "000007", "000008", "000009", " >", " >=",
660 " s>u<", "s>=u<=", " s>", " s>=", "000016", "000017",
661 " s<u>", "s<=u>=", " <", " <=", " s<", " s<=",
662 "000024", "000025", " u>", " u>=", " u<", " u<=",
663 " !=", "000031" };
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000664 for (Node::const_iterator NI = begin(), NE = end(); NI != NE; ++NI) {
Nick Lewycky73dd6922007-07-05 03:15:00 +0000665 os << names[NI->LV] << " " << NI->To
Nick Lewyckye635cc42007-07-10 03:28:21 +0000666 << " (" << NI->Subtree->getDFSNumIn() << "), ";
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000667 }
668 }
Nick Lewycky73dd6922007-07-05 03:15:00 +0000669 public:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000670#endif
671
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000672 iterator begin() { return Relations.begin(); }
673 iterator end() { return Relations.end(); }
674 const_iterator begin() const { return Relations.begin(); }
675 const_iterator end() const { return Relations.end(); }
676
Nick Lewycky26e25d32007-06-24 04:36:20 +0000677 iterator find(unsigned n, DomTreeDFS::Node *Subtree) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000678 iterator E = end();
679 for (iterator I = std::lower_bound(begin(), E, n);
680 I != E && I->To == n; ++I) {
681 if (Subtree->DominatedBy(I->Subtree))
682 return I;
683 }
684 return E;
685 }
686
Nick Lewycky26e25d32007-06-24 04:36:20 +0000687 const_iterator find(unsigned n, DomTreeDFS::Node *Subtree) const {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000688 const_iterator E = end();
689 for (const_iterator I = std::lower_bound(begin(), E, n);
690 I != E && I->To == n; ++I) {
691 if (Subtree->DominatedBy(I->Subtree))
692 return I;
693 }
694 return E;
695 }
696
Nick Lewycky20f08112007-08-04 18:45:32 +0000697 /// update - updates the lattice value for a given node, creating a new
698 /// entry if one doesn't exist. The new lattice value must not be
699 /// inconsistent with any previously existing value.
Nick Lewycky26e25d32007-06-24 04:36:20 +0000700 void update(unsigned n, LatticeVal R, DomTreeDFS::Node *Subtree) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000701 assert(validPredicate(R) && "Invalid predicate.");
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000702
Nick Lewycky20f08112007-08-04 18:45:32 +0000703 Edge edge(n, R, Subtree);
704 iterator B = begin(), E = end();
705 iterator I = std::lower_bound(B, E, edge);
Nick Lewycky6ce36cf2007-01-15 14:30:07 +0000706
Nick Lewycky20f08112007-08-04 18:45:32 +0000707 iterator J = I;
708 while (J != E && J->To == n) {
709 if (Subtree->DominatedBy(J->Subtree))
710 break;
711 ++J;
712 }
713
Nick Lewycky5b5b1ab2007-08-18 23:18:03 +0000714 if (J != E && J->To == n) {
Nick Lewycky20f08112007-08-04 18:45:32 +0000715 edge.LV = static_cast<LatticeVal>(J->LV & R);
716 assert(validPredicate(edge.LV) && "Invalid union of lattice values.");
Nick Lewycky20f08112007-08-04 18:45:32 +0000717
Nick Lewycky5b5b1ab2007-08-18 23:18:03 +0000718 if (edge.LV == J->LV)
719 return; // This update adds nothing new.
720 }
721
722 if (I != B) {
723 // We also have to tighten any edge beneath our update.
724 for (iterator K = I - 1; K->To == n; --K) {
725 if (K->Subtree->DominatedBy(Subtree)) {
726 LatticeVal LV = static_cast<LatticeVal>(K->LV & edge.LV);
727 assert(validPredicate(LV) && "Invalid union of lattice values");
728 K->LV = LV;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000729 }
Nick Lewycky5b5b1ab2007-08-18 23:18:03 +0000730 if (K == B) break;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000731 }
Nick Lewycky5b5b1ab2007-08-18 23:18:03 +0000732 }
Nick Lewycky20f08112007-08-04 18:45:32 +0000733
734 // Insert new edge at Subtree if it isn't already there.
735 if (I == E || I->To != n || Subtree != I->Subtree)
736 Relations.insert(I, edge);
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000737 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000738 };
739
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000740 private:
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000741
742 std::vector<Node> Nodes;
743
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000744 public:
Nick Lewyckye635cc42007-07-10 03:28:21 +0000745 /// node - returns the node object at a given value number. The pointer
746 /// returned may be invalidated on the next call to node().
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000747 Node *node(unsigned index) {
Nick Lewyckye635cc42007-07-10 03:28:21 +0000748 assert(VN.value(index)); // This triggers the necessary checks.
749 if (Nodes.size() < index) Nodes.resize(index);
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000750 return &Nodes[index-1];
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000751 }
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000752
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000753 /// isRelatedBy - true iff n1 op n2
Nick Lewycky26e25d32007-06-24 04:36:20 +0000754 bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
755 LatticeVal LV) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000756 if (n1 == n2) return LV & EQ_BIT;
757
758 Node *N1 = node(n1);
759 Node::iterator I = N1->find(n2, Subtree), E = N1->end();
760 if (I != E) return (I->LV & LV) == I->LV;
761
Nick Lewyckycfff1c32006-09-20 17:04:01 +0000762 return false;
763 }
764
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000765 // The add* methods assume that your input is logically valid and may
766 // assertion-fail or infinitely loop if you attempt a contradiction.
Nick Lewycky9d17c822006-10-25 23:48:24 +0000767
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000768 /// addInequality - Sets n1 op n2.
769 /// It is also an error to call this on an inequality that is already true.
Nick Lewycky26e25d32007-06-24 04:36:20 +0000770 void addInequality(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000771 LatticeVal LV1) {
772 assert(n1 != n2 && "A node can't be inequal to itself.");
773
774 if (LV1 != NE)
775 assert(!isRelatedBy(n1, n2, Subtree, reversePredicate(LV1)) &&
776 "Contradictory inequality.");
777
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000778 // Suppose we're adding %n1 < %n2. Find all the %a < %n1 and
779 // add %a < %n2 too. This keeps the graph fully connected.
780 if (LV1 != NE) {
Nick Lewycky3bb6de82007-04-07 03:36:51 +0000781 // Break up the relationship into signed and unsigned comparison parts.
782 // If the signed parts of %a op1 %n1 match that of %n1 op2 %n2, and
783 // op1 and op2 aren't NE, then add %a op3 %n2. The new relationship
784 // should have the EQ_BIT iff it's set for both op1 and op2.
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000785
786 unsigned LV1_s = LV1 & (SLT_BIT|SGT_BIT);
787 unsigned LV1_u = LV1 & (ULT_BIT|UGT_BIT);
Nick Lewycky3bb6de82007-04-07 03:36:51 +0000788
Nick Lewyckye635cc42007-07-10 03:28:21 +0000789 for (Node::iterator I = node(n1)->begin(), E = node(n1)->end(); I != E; ++I) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000790 if (I->LV != NE && I->To != n2) {
Nick Lewycky3bb6de82007-04-07 03:36:51 +0000791
Nick Lewycky26e25d32007-06-24 04:36:20 +0000792 DomTreeDFS::Node *Local_Subtree = NULL;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000793 if (Subtree->DominatedBy(I->Subtree))
794 Local_Subtree = Subtree;
795 else if (I->Subtree->DominatedBy(Subtree))
796 Local_Subtree = I->Subtree;
797
798 if (Local_Subtree) {
799 unsigned new_relationship = 0;
800 LatticeVal ILV = reversePredicate(I->LV);
801 unsigned ILV_s = ILV & (SLT_BIT|SGT_BIT);
802 unsigned ILV_u = ILV & (ULT_BIT|UGT_BIT);
803
804 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
805 new_relationship |= ILV_s;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000806 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
807 new_relationship |= ILV_u;
808
809 if (new_relationship) {
810 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
811 new_relationship |= (SLT_BIT|SGT_BIT);
812 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
813 new_relationship |= (ULT_BIT|UGT_BIT);
814 if ((LV1 & EQ_BIT) && (ILV & EQ_BIT))
815 new_relationship |= EQ_BIT;
816
817 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
818
819 node(I->To)->update(n2, NewLV, Local_Subtree);
Nick Lewyckye635cc42007-07-10 03:28:21 +0000820 node(n2)->update(I->To, reversePredicate(NewLV), Local_Subtree);
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000821 }
822 }
823 }
824 }
825
Nick Lewyckye635cc42007-07-10 03:28:21 +0000826 for (Node::iterator I = node(n2)->begin(), E = node(n2)->end(); I != E; ++I) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000827 if (I->LV != NE && I->To != n1) {
Nick Lewycky26e25d32007-06-24 04:36:20 +0000828 DomTreeDFS::Node *Local_Subtree = NULL;
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000829 if (Subtree->DominatedBy(I->Subtree))
830 Local_Subtree = Subtree;
831 else if (I->Subtree->DominatedBy(Subtree))
832 Local_Subtree = I->Subtree;
833
834 if (Local_Subtree) {
835 unsigned new_relationship = 0;
836 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
837 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
838
839 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
840 new_relationship |= ILV_s;
841
842 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
843 new_relationship |= ILV_u;
844
845 if (new_relationship) {
846 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
847 new_relationship |= (SLT_BIT|SGT_BIT);
848 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
849 new_relationship |= (ULT_BIT|UGT_BIT);
850 if ((LV1 & EQ_BIT) && (I->LV & EQ_BIT))
851 new_relationship |= EQ_BIT;
852
853 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
854
Nick Lewyckye635cc42007-07-10 03:28:21 +0000855 node(n1)->update(I->To, NewLV, Local_Subtree);
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000856 node(I->To)->update(n1, reversePredicate(NewLV), Local_Subtree);
857 }
858 }
859 }
860 }
861 }
862
Nick Lewyckye635cc42007-07-10 03:28:21 +0000863 node(n1)->update(n2, LV1, Subtree);
864 node(n2)->update(n1, reversePredicate(LV1), Subtree);
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000865 }
Nick Lewycky51ce8d62006-09-13 19:24:01 +0000866
Nick Lewycky73dd6922007-07-05 03:15:00 +0000867 /// remove - removes a node from the graph by removing all references to
868 /// and from it.
869 void remove(unsigned n) {
870 Node *N = node(n);
871 for (Node::iterator NI = N->begin(), NE = N->end(); NI != NE; ++NI) {
872 Node::iterator Iter = node(NI->To)->find(n, TreeRoot);
873 do {
874 node(NI->To)->Relations.erase(Iter);
875 Iter = node(NI->To)->find(n, TreeRoot);
876 } while (Iter != node(NI->To)->end());
Nick Lewycky9a22d7b2006-09-10 02:27:07 +0000877 }
Nick Lewycky73dd6922007-07-05 03:15:00 +0000878 N->Relations.clear();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000879 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000880
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000881#ifndef NDEBUG
Nick Lewycky5d6ede52007-01-11 02:38:21 +0000882 virtual ~InequalityGraph() {}
Nick Lewycky2fc338f2007-01-11 02:32:38 +0000883 virtual void dump() {
884 dump(*cerr.stream());
885 }
886
887 void dump(std::ostream &os) {
Nick Lewycky73dd6922007-07-05 03:15:00 +0000888 for (unsigned i = 1; i <= Nodes.size(); ++i) {
889 os << i << " = {";
890 node(i)->dump(os);
891 os << "}\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000892 }
893 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +0000894#endif
895 };
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +0000896
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000897 class VRPSolver;
898
899 /// ValueRanges tracks the known integer ranges and anti-ranges of the nodes
900 /// in the InequalityGraph.
901 class VISIBILITY_HIDDEN ValueRanges {
Nick Lewyckye635cc42007-07-10 03:28:21 +0000902 ValueNumbering &VN;
903 TargetData *TD;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000904
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000905 class VISIBILITY_HIDDEN ScopedRange {
Nick Lewyckye635cc42007-07-10 03:28:21 +0000906 typedef std::vector<std::pair<DomTreeDFS::Node *, ConstantRange> >
907 RangeListType;
908 RangeListType RangeList;
909
910 static bool swo(const std::pair<DomTreeDFS::Node *, ConstantRange> &LHS,
911 const std::pair<DomTreeDFS::Node *, ConstantRange> &RHS) {
912 return *LHS.first < *RHS.first;
913 }
914
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000915 public:
Nick Lewyckye635cc42007-07-10 03:28:21 +0000916#ifndef NDEBUG
917 virtual ~ScopedRange() {}
918 virtual void dump() const {
919 dump(*cerr.stream());
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000920 }
921
Nick Lewyckye635cc42007-07-10 03:28:21 +0000922 void dump(std::ostream &os) const {
923 os << "{";
924 for (const_iterator I = begin(), E = end(); I != E; ++I) {
925 os << I->second << " (" << I->first->getDFSNumIn() << "), ";
926 }
927 os << "}";
928 }
929#endif
930
931 typedef RangeListType::iterator iterator;
932 typedef RangeListType::const_iterator const_iterator;
933
934 iterator begin() { return RangeList.begin(); }
935 iterator end() { return RangeList.end(); }
936 const_iterator begin() const { return RangeList.begin(); }
937 const_iterator end() const { return RangeList.end(); }
938
939 iterator find(DomTreeDFS::Node *Subtree) {
940 static ConstantRange empty(1, false);
941 iterator E = end();
942 iterator I = std::lower_bound(begin(), E,
943 std::make_pair(Subtree, empty), swo);
944
945 while (I != E && !I->first->dominates(Subtree)) ++I;
946 return I;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000947 }
Bill Wendling6357bf22007-06-04 23:52:59 +0000948
Nick Lewyckye635cc42007-07-10 03:28:21 +0000949 const_iterator find(DomTreeDFS::Node *Subtree) const {
950 static const ConstantRange empty(1, false);
951 const_iterator E = end();
952 const_iterator I = std::lower_bound(begin(), E,
953 std::make_pair(Subtree, empty), swo);
954
955 while (I != E && !I->first->dominates(Subtree)) ++I;
956 return I;
Bill Wendling6357bf22007-06-04 23:52:59 +0000957 }
958
Nick Lewyckye635cc42007-07-10 03:28:21 +0000959 void update(const ConstantRange &CR, DomTreeDFS::Node *Subtree) {
960 assert(!CR.isEmptySet() && "Empty ConstantRange.");
Nick Lewycky20f08112007-08-04 18:45:32 +0000961 assert(!CR.isSingleElement() && "Refusing to store single element.");
Nick Lewyckye635cc42007-07-10 03:28:21 +0000962
963 static ConstantRange empty(1, false);
964 iterator E = end();
965 iterator I =
966 std::lower_bound(begin(), E, std::make_pair(Subtree, empty), swo);
967
968 if (I != end() && I->first == Subtree) {
Nick Lewycky39519f52007-07-14 04:28:04 +0000969 ConstantRange CR2 = I->second.maximalIntersectWith(CR);
Nick Lewyckye635cc42007-07-10 03:28:21 +0000970 assert(!CR2.isEmptySet() && !CR2.isSingleElement() &&
971 "Invalid union of ranges.");
972 I->second = CR2;
973 } else
974 RangeList.insert(I, std::make_pair(Subtree, CR));
Bill Wendling6357bf22007-06-04 23:52:59 +0000975 }
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000976 };
977
978 std::vector<ScopedRange> Ranges;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000979
Nick Lewyckye635cc42007-07-10 03:28:21 +0000980 void update(unsigned n, const ConstantRange &CR, DomTreeDFS::Node *Subtree){
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000981 if (CR.isFullSet()) return;
Nick Lewyckye635cc42007-07-10 03:28:21 +0000982 if (Ranges.size() < n) Ranges.resize(n);
983 Ranges[n-1].update(CR, Subtree);
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +0000984 }
985
Nick Lewyckye635cc42007-07-10 03:28:21 +0000986 /// create - Creates a ConstantRange that matches the given LatticeVal
987 /// relation with a given integer.
988 ConstantRange create(LatticeVal LV, const ConstantRange &CR) {
989 assert(!CR.isEmptySet() && "Can't deal with empty set.");
990
991 if (LV == NE)
992 return makeConstantRange(ICmpInst::ICMP_NE, CR);
993
994 unsigned LV_s = LV & (SGT_BIT|SLT_BIT);
995 unsigned LV_u = LV & (UGT_BIT|ULT_BIT);
996 bool hasEQ = LV & EQ_BIT;
997
998 ConstantRange Range(CR.getBitWidth());
999
1000 if (LV_s == SGT_BIT) {
Nick Lewycky39519f52007-07-14 04:28:04 +00001001 Range = Range.maximalIntersectWith(makeConstantRange(
Nick Lewyckye635cc42007-07-10 03:28:21 +00001002 hasEQ ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_SGT, CR));
1003 } else if (LV_s == SLT_BIT) {
Nick Lewycky39519f52007-07-14 04:28:04 +00001004 Range = Range.maximalIntersectWith(makeConstantRange(
Nick Lewyckye635cc42007-07-10 03:28:21 +00001005 hasEQ ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_SLT, CR));
1006 }
1007
1008 if (LV_u == UGT_BIT) {
Nick Lewycky39519f52007-07-14 04:28:04 +00001009 Range = Range.maximalIntersectWith(makeConstantRange(
Nick Lewyckye635cc42007-07-10 03:28:21 +00001010 hasEQ ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_UGT, CR));
1011 } else if (LV_u == ULT_BIT) {
Nick Lewycky39519f52007-07-14 04:28:04 +00001012 Range = Range.maximalIntersectWith(makeConstantRange(
Nick Lewyckye635cc42007-07-10 03:28:21 +00001013 hasEQ ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT, CR));
1014 }
1015
1016 return Range;
1017 }
1018
1019 /// makeConstantRange - Creates a ConstantRange representing the set of all
1020 /// value that match the ICmpInst::Predicate with any of the values in CR.
1021 ConstantRange makeConstantRange(ICmpInst::Predicate ICmpOpcode,
1022 const ConstantRange &CR) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001023 uint32_t W = CR.getBitWidth();
1024 switch (ICmpOpcode) {
Nick Lewyckye635cc42007-07-10 03:28:21 +00001025 default: assert(!"Invalid ICmp opcode to makeConstantRange()");
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001026 case ICmpInst::ICMP_EQ:
1027 return ConstantRange(CR.getLower(), CR.getUpper());
1028 case ICmpInst::ICMP_NE:
1029 if (CR.isSingleElement())
1030 return ConstantRange(CR.getUpper(), CR.getLower());
1031 return ConstantRange(W);
1032 case ICmpInst::ICMP_ULT:
1033 return ConstantRange(APInt::getMinValue(W), CR.getUnsignedMax());
1034 case ICmpInst::ICMP_SLT:
1035 return ConstantRange(APInt::getSignedMinValue(W), CR.getSignedMax());
1036 case ICmpInst::ICMP_ULE: {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001037 APInt UMax(CR.getUnsignedMax());
Zhou Sheng31787362007-04-26 16:42:07 +00001038 if (UMax.isMaxValue())
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001039 return ConstantRange(W);
1040 return ConstantRange(APInt::getMinValue(W), UMax + 1);
1041 }
1042 case ICmpInst::ICMP_SLE: {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001043 APInt SMax(CR.getSignedMax());
Zhou Sheng31787362007-04-26 16:42:07 +00001044 if (SMax.isMaxSignedValue() || (SMax+1).isMaxSignedValue())
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001045 return ConstantRange(W);
1046 return ConstantRange(APInt::getSignedMinValue(W), SMax + 1);
1047 }
1048 case ICmpInst::ICMP_UGT:
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001049 return ConstantRange(CR.getUnsignedMin() + 1, APInt::getNullValue(W));
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001050 case ICmpInst::ICMP_SGT:
1051 return ConstantRange(CR.getSignedMin() + 1,
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001052 APInt::getSignedMinValue(W));
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001053 case ICmpInst::ICMP_UGE: {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001054 APInt UMin(CR.getUnsignedMin());
Zhou Sheng31787362007-04-26 16:42:07 +00001055 if (UMin.isMinValue())
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001056 return ConstantRange(W);
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001057 return ConstantRange(UMin, APInt::getNullValue(W));
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001058 }
1059 case ICmpInst::ICMP_SGE: {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001060 APInt SMin(CR.getSignedMin());
Zhou Sheng31787362007-04-26 16:42:07 +00001061 if (SMin.isMinSignedValue())
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001062 return ConstantRange(W);
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001063 return ConstantRange(SMin, APInt::getSignedMinValue(W));
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001064 }
1065 }
1066 }
1067
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001068#ifndef NDEBUG
Nick Lewyckye635cc42007-07-10 03:28:21 +00001069 bool isCanonical(Value *V, DomTreeDFS::Node *Subtree) {
1070 return V == VN.canonicalize(V, Subtree);
1071 }
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001072#endif
1073
1074 public:
1075
Nick Lewyckye635cc42007-07-10 03:28:21 +00001076 ValueRanges(ValueNumbering &VN, TargetData *TD) : VN(VN), TD(TD) {}
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001077
Nick Lewyckye635cc42007-07-10 03:28:21 +00001078#ifndef NDEBUG
1079 virtual ~ValueRanges() {}
1080
1081 virtual void dump() const {
1082 dump(*cerr.stream());
1083 }
1084
1085 void dump(std::ostream &os) const {
1086 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1087 os << (i+1) << " = ";
1088 Ranges[i].dump(os);
1089 os << "\n";
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001090 }
Nick Lewyckye635cc42007-07-10 03:28:21 +00001091 }
1092#endif
1093
1094 /// range - looks up the ConstantRange associated with a value number.
1095 ConstantRange range(unsigned n, DomTreeDFS::Node *Subtree) {
1096 assert(VN.value(n)); // performs range checks
1097
1098 if (n <= Ranges.size()) {
1099 ScopedRange::iterator I = Ranges[n-1].find(Subtree);
1100 if (I != Ranges[n-1].end()) return I->second;
1101 }
1102
1103 Value *V = VN.value(n);
1104 ConstantRange CR = range(V);
1105 return CR;
1106 }
1107
1108 /// range - determine a range from a Value without performing any lookups.
1109 ConstantRange range(Value *V) const {
1110 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
1111 return ConstantRange(C->getValue());
1112 else if (isa<ConstantPointerNull>(V))
1113 return ConstantRange(APInt::getNullValue(typeToWidth(V->getType())));
1114 else
1115 return typeToWidth(V->getType());
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001116 }
1117
Nick Lewycky12d44ab2007-04-07 03:16:12 +00001118 // typeToWidth - returns the number of bits necessary to store a value of
1119 // this type, or zero if unknown.
1120 uint32_t typeToWidth(const Type *Ty) const {
1121 if (TD)
1122 return TD->getTypeSizeInBits(Ty);
1123
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001124 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
1125 return ITy->getBitWidth();
1126
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001127 return 0;
1128 }
1129
Nick Lewyckye635cc42007-07-10 03:28:21 +00001130 static bool isRelatedBy(const ConstantRange &CR1, const ConstantRange &CR2,
1131 LatticeVal LV) {
Nick Lewycky4f73de22007-03-16 02:37:39 +00001132 switch (LV) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001133 default: assert(!"Impossible lattice value!");
1134 case NE:
Nick Lewycky39519f52007-07-14 04:28:04 +00001135 return CR1.maximalIntersectWith(CR2).isEmptySet();
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001136 case ULT:
1137 return CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
1138 case ULE:
1139 return CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
1140 case UGT:
1141 return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
1142 case UGE:
1143 return CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
1144 case SLT:
1145 return CR1.getSignedMax().slt(CR2.getSignedMin());
1146 case SLE:
1147 return CR1.getSignedMax().sle(CR2.getSignedMin());
1148 case SGT:
1149 return CR1.getSignedMin().sgt(CR2.getSignedMax());
1150 case SGE:
1151 return CR1.getSignedMin().sge(CR2.getSignedMax());
1152 case LT:
1153 return CR1.getUnsignedMax().ult(CR2.getUnsignedMin()) &&
1154 CR1.getSignedMax().slt(CR2.getUnsignedMin());
1155 case LE:
1156 return CR1.getUnsignedMax().ule(CR2.getUnsignedMin()) &&
1157 CR1.getSignedMax().sle(CR2.getUnsignedMin());
1158 case GT:
1159 return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax()) &&
1160 CR1.getSignedMin().sgt(CR2.getSignedMax());
1161 case GE:
1162 return CR1.getUnsignedMin().uge(CR2.getUnsignedMax()) &&
1163 CR1.getSignedMin().sge(CR2.getSignedMax());
1164 case SLTUGT:
1165 return CR1.getSignedMax().slt(CR2.getSignedMin()) &&
1166 CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
1167 case SLEUGE:
1168 return CR1.getSignedMax().sle(CR2.getSignedMin()) &&
1169 CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
1170 case SGTULT:
1171 return CR1.getSignedMin().sgt(CR2.getSignedMax()) &&
1172 CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
1173 case SGEULE:
1174 return CR1.getSignedMin().sge(CR2.getSignedMax()) &&
1175 CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
1176 }
1177 }
1178
Nick Lewyckye635cc42007-07-10 03:28:21 +00001179 bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
1180 LatticeVal LV) {
1181 ConstantRange CR1 = range(n1, Subtree);
1182 ConstantRange CR2 = range(n2, Subtree);
1183
1184 // True iff all values in CR1 are LV to all values in CR2.
1185 return isRelatedBy(CR1, CR2, LV);
1186 }
1187
Nick Lewycky3bb6de82007-04-07 03:36:51 +00001188 void addToWorklist(Value *V, Constant *C, ICmpInst::Predicate Pred,
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001189 VRPSolver *VRP);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001190 void markBlock(VRPSolver *VRP);
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001191
Nick Lewyckye635cc42007-07-10 03:28:21 +00001192 void mergeInto(Value **I, unsigned n, unsigned New,
Nick Lewycky26e25d32007-06-24 04:36:20 +00001193 DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
Nick Lewyckye635cc42007-07-10 03:28:21 +00001194 ConstantRange CR_New = range(New, Subtree);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001195 ConstantRange Merged = CR_New;
1196
1197 for (; n != 0; ++I, --n) {
Nick Lewyckye635cc42007-07-10 03:28:21 +00001198 unsigned i = VN.valueNumber(*I, Subtree);
1199 ConstantRange CR_Kill = i ? range(i, Subtree) : range(*I);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001200 if (CR_Kill.isFullSet()) continue;
Nick Lewycky39519f52007-07-14 04:28:04 +00001201 Merged = Merged.maximalIntersectWith(CR_Kill);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001202 }
1203
1204 if (Merged.isFullSet() || Merged == CR_New) return;
1205
Nick Lewycky3bb6de82007-04-07 03:36:51 +00001206 applyRange(New, Merged, Subtree, VRP);
1207 }
1208
Nick Lewyckye635cc42007-07-10 03:28:21 +00001209 void applyRange(unsigned n, const ConstantRange &CR,
Nick Lewycky26e25d32007-06-24 04:36:20 +00001210 DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
Nick Lewycky39519f52007-07-14 04:28:04 +00001211 ConstantRange Merged = CR.maximalIntersectWith(range(n, Subtree));
Nick Lewyckye635cc42007-07-10 03:28:21 +00001212 if (Merged.isEmptySet()) {
1213 markBlock(VRP);
1214 return;
1215 }
Nick Lewycky3bb6de82007-04-07 03:36:51 +00001216
Nick Lewyckye635cc42007-07-10 03:28:21 +00001217 if (const APInt *I = Merged.getSingleElement()) {
1218 Value *V = VN.value(n); // XXX: redesign worklist.
Nick Lewycky3bb6de82007-04-07 03:36:51 +00001219 const Type *Ty = V->getType();
1220 if (Ty->isInteger()) {
1221 addToWorklist(V, ConstantInt::get(*I), ICmpInst::ICMP_EQ, VRP);
1222 return;
1223 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1224 assert(*I == 0 && "Pointer is null but not zero?");
1225 addToWorklist(V, ConstantPointerNull::get(PTy),
Nick Lewyckye635cc42007-07-10 03:28:21 +00001226 ICmpInst::ICMP_EQ, VRP);
Nick Lewycky3bb6de82007-04-07 03:36:51 +00001227 return;
1228 }
1229 }
1230
Nick Lewyckye635cc42007-07-10 03:28:21 +00001231 update(n, Merged, Subtree);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001232 }
1233
Nick Lewyckye635cc42007-07-10 03:28:21 +00001234 void addNotEquals(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
Nick Lewycky26e25d32007-06-24 04:36:20 +00001235 VRPSolver *VRP) {
Nick Lewyckye635cc42007-07-10 03:28:21 +00001236 ConstantRange CR1 = range(n1, Subtree);
1237 ConstantRange CR2 = range(n2, Subtree);
Nick Lewycky93f54102007-04-07 04:49:12 +00001238
Nick Lewyckye635cc42007-07-10 03:28:21 +00001239 uint32_t W = CR1.getBitWidth();
Nick Lewycky93f54102007-04-07 04:49:12 +00001240
1241 if (const APInt *I = CR1.getSingleElement()) {
1242 if (CR2.isFullSet()) {
1243 ConstantRange NewCR2(CR1.getUpper(), CR1.getLower());
Nick Lewyckye635cc42007-07-10 03:28:21 +00001244 applyRange(n2, NewCR2, Subtree, VRP);
Nick Lewycky93f54102007-04-07 04:49:12 +00001245 } else if (*I == CR2.getLower()) {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001246 APInt NewLower(CR2.getLower() + 1),
1247 NewUpper(CR2.getUpper());
Nick Lewycky93f54102007-04-07 04:49:12 +00001248 if (NewLower == NewUpper)
1249 NewLower = NewUpper = APInt::getMinValue(W);
1250
1251 ConstantRange NewCR2(NewLower, NewUpper);
Nick Lewyckye635cc42007-07-10 03:28:21 +00001252 applyRange(n2, NewCR2, Subtree, VRP);
Nick Lewycky93f54102007-04-07 04:49:12 +00001253 } else if (*I == CR2.getUpper() - 1) {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001254 APInt NewLower(CR2.getLower()),
1255 NewUpper(CR2.getUpper() - 1);
Nick Lewycky93f54102007-04-07 04:49:12 +00001256 if (NewLower == NewUpper)
1257 NewLower = NewUpper = APInt::getMinValue(W);
1258
1259 ConstantRange NewCR2(NewLower, NewUpper);
Nick Lewyckye635cc42007-07-10 03:28:21 +00001260 applyRange(n2, NewCR2, Subtree, VRP);
Nick Lewycky93f54102007-04-07 04:49:12 +00001261 }
1262 }
1263
1264 if (const APInt *I = CR2.getSingleElement()) {
1265 if (CR1.isFullSet()) {
1266 ConstantRange NewCR1(CR2.getUpper(), CR2.getLower());
Nick Lewyckye635cc42007-07-10 03:28:21 +00001267 applyRange(n1, NewCR1, Subtree, VRP);
Nick Lewycky93f54102007-04-07 04:49:12 +00001268 } else if (*I == CR1.getLower()) {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001269 APInt NewLower(CR1.getLower() + 1),
1270 NewUpper(CR1.getUpper());
Nick Lewycky93f54102007-04-07 04:49:12 +00001271 if (NewLower == NewUpper)
1272 NewLower = NewUpper = APInt::getMinValue(W);
1273
1274 ConstantRange NewCR1(NewLower, NewUpper);
Nick Lewyckye635cc42007-07-10 03:28:21 +00001275 applyRange(n1, NewCR1, Subtree, VRP);
Nick Lewycky93f54102007-04-07 04:49:12 +00001276 } else if (*I == CR1.getUpper() - 1) {
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00001277 APInt NewLower(CR1.getLower()),
1278 NewUpper(CR1.getUpper() - 1);
Nick Lewycky93f54102007-04-07 04:49:12 +00001279 if (NewLower == NewUpper)
1280 NewLower = NewUpper = APInt::getMinValue(W);
1281
1282 ConstantRange NewCR1(NewLower, NewUpper);
Nick Lewyckye635cc42007-07-10 03:28:21 +00001283 applyRange(n1, NewCR1, Subtree, VRP);
Nick Lewycky93f54102007-04-07 04:49:12 +00001284 }
1285 }
1286 }
1287
Nick Lewyckye635cc42007-07-10 03:28:21 +00001288 void addInequality(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
Nick Lewycky26e25d32007-06-24 04:36:20 +00001289 LatticeVal LV, VRPSolver *VRP) {
Nick Lewyckye635cc42007-07-10 03:28:21 +00001290 assert(!isRelatedBy(n1, n2, Subtree, LV) && "Asked to do useless work.");
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001291
Nick Lewycky93f54102007-04-07 04:49:12 +00001292 if (LV == NE) {
Nick Lewyckye635cc42007-07-10 03:28:21 +00001293 addNotEquals(n1, n2, Subtree, VRP);
Nick Lewycky93f54102007-04-07 04:49:12 +00001294 return;
1295 }
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001296
Nick Lewyckye635cc42007-07-10 03:28:21 +00001297 ConstantRange CR1 = range(n1, Subtree);
1298 ConstantRange CR2 = range(n2, Subtree);
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001299
1300 if (!CR1.isSingleElement()) {
Nick Lewycky39519f52007-07-14 04:28:04 +00001301 ConstantRange NewCR1 = CR1.maximalIntersectWith(create(LV, CR2));
Nick Lewycky3bb6de82007-04-07 03:36:51 +00001302 if (NewCR1 != CR1)
Nick Lewyckye635cc42007-07-10 03:28:21 +00001303 applyRange(n1, NewCR1, Subtree, VRP);
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001304 }
1305
1306 if (!CR2.isSingleElement()) {
Nick Lewycky39519f52007-07-14 04:28:04 +00001307 ConstantRange NewCR2 = CR2.maximalIntersectWith(
1308 create(reversePredicate(LV), CR1));
Nick Lewycky3bb6de82007-04-07 03:36:51 +00001309 if (NewCR2 != CR2)
Nick Lewyckye635cc42007-07-10 03:28:21 +00001310 applyRange(n2, NewCR2, Subtree, VRP);
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001311 }
1312 }
1313 };
1314
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001315 /// UnreachableBlocks keeps tracks of blocks that are for one reason or
1316 /// another discovered to be unreachable. This is used to cull the graph when
1317 /// analyzing instructions, and to mark blocks with the "unreachable"
1318 /// terminator instruction after the function has executed.
1319 class VISIBILITY_HIDDEN UnreachableBlocks {
1320 private:
1321 std::vector<BasicBlock *> DeadBlocks;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001322
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001323 public:
1324 /// mark - mark a block as dead
1325 void mark(BasicBlock *BB) {
1326 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
1327 std::vector<BasicBlock *>::iterator I =
1328 std::lower_bound(DeadBlocks.begin(), E, BB);
1329
1330 if (I == E || *I != BB) DeadBlocks.insert(I, BB);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001331 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001332
1333 /// isDead - returns whether a block is known to be dead already
1334 bool isDead(BasicBlock *BB) {
1335 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
1336 std::vector<BasicBlock *>::iterator I =
1337 std::lower_bound(DeadBlocks.begin(), E, BB);
1338
1339 return I != E && *I == BB;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001340 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001341
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001342 /// kill - replace the dead blocks' terminator with an UnreachableInst.
1343 bool kill() {
1344 bool modified = false;
1345 for (std::vector<BasicBlock *>::iterator I = DeadBlocks.begin(),
1346 E = DeadBlocks.end(); I != E; ++I) {
1347 BasicBlock *BB = *I;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001348
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001349 DOUT << "unreachable block: " << BB->getName() << "\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001350
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001351 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
1352 SI != SE; ++SI) {
1353 BasicBlock *Succ = *SI;
1354 Succ->removePredecessor(BB);
Nick Lewycky9d17c822006-10-25 23:48:24 +00001355 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001356
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001357 TerminatorInst *TI = BB->getTerminator();
1358 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1359 TI->eraseFromParent();
1360 new UnreachableInst(BB);
1361 ++NumBlocks;
1362 modified = true;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001363 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001364 DeadBlocks.clear();
1365 return modified;
Nick Lewycky9d17c822006-10-25 23:48:24 +00001366 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001367 };
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001368
1369 /// VRPSolver keeps track of how changes to one variable affect other
1370 /// variables, and forwards changes along to the InequalityGraph. It
1371 /// also maintains the correct choice for "canonical" in the IG.
1372 /// @brief VRPSolver calculates inferences from a new relationship.
1373 class VISIBILITY_HIDDEN VRPSolver {
1374 private:
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001375 friend class ValueRanges;
1376
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001377 struct Operation {
1378 Value *LHS, *RHS;
1379 ICmpInst::Predicate Op;
1380
Nick Lewycky26e25d32007-06-24 04:36:20 +00001381 BasicBlock *ContextBB; // XXX use a DomTreeDFS::Node instead
Nick Lewycky42944462007-01-13 02:05:28 +00001382 Instruction *ContextInst;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001383 };
1384 std::deque<Operation> WorkList;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001385
Nick Lewycky73dd6922007-07-05 03:15:00 +00001386 ValueNumbering &VN;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001387 InequalityGraph &IG;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001388 UnreachableBlocks &UB;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001389 ValueRanges &VR;
Nick Lewycky26e25d32007-06-24 04:36:20 +00001390 DomTreeDFS *DTDFS;
1391 DomTreeDFS::Node *Top;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001392 BasicBlock *TopBB;
1393 Instruction *TopInst;
1394 bool &modified;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001395
1396 typedef InequalityGraph::Node Node;
1397
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001398 // below - true if the Instruction is dominated by the current context
1399 // block or instruction
1400 bool below(Instruction *I) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00001401 BasicBlock *BB = I->getParent();
1402 if (TopInst && TopInst->getParent() == BB) {
1403 if (isa<TerminatorInst>(TopInst)) return false;
1404 if (isa<TerminatorInst>(I)) return true;
1405 if ( isa<PHINode>(TopInst) && !isa<PHINode>(I)) return true;
1406 if (!isa<PHINode>(TopInst) && isa<PHINode>(I)) return false;
1407
1408 for (BasicBlock::const_iterator Iter = BB->begin(), E = BB->end();
1409 Iter != E; ++Iter) {
1410 if (&*Iter == TopInst) return true;
1411 else if (&*Iter == I) return false;
1412 }
1413 assert(!"Instructions not found in parent BasicBlock?");
1414 } else {
Nick Lewycky0f986fd2007-06-24 04:40:16 +00001415 DomTreeDFS::Node *Node = DTDFS->getNodeForBlock(BB);
Nick Lewycky26e25d32007-06-24 04:36:20 +00001416 if (!Node) return false;
1417 return Top->dominates(Node);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001418 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001419 }
1420
Nick Lewycky26e25d32007-06-24 04:36:20 +00001421 // aboveOrBelow - true if the Instruction either dominates or is dominated
1422 // by the current context block or instruction
1423 bool aboveOrBelow(Instruction *I) {
1424 BasicBlock *BB = I->getParent();
1425 DomTreeDFS::Node *Node = DTDFS->getNodeForBlock(BB);
1426 if (!Node) return false;
1427
1428 return Top == Node || Top->dominates(Node) || Node->dominates(Top);
1429 }
1430
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001431 bool makeEqual(Value *V1, Value *V2) {
1432 DOUT << "makeEqual(" << *V1 << ", " << *V2 << ")\n";
Nick Lewycky26e25d32007-06-24 04:36:20 +00001433 DOUT << "context is ";
1434 if (TopInst) DOUT << "I: " << *TopInst << "\n";
1435 else DOUT << "BB: " << TopBB->getName()
1436 << "(" << Top->getDFSNumIn() << ")\n";
Nick Lewycky9d17c822006-10-25 23:48:24 +00001437
Nick Lewycky12d44ab2007-04-07 03:16:12 +00001438 assert(V1->getType() == V2->getType() &&
1439 "Can't make two values with different types equal.");
1440
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001441 if (V1 == V2) return true;
Nick Lewycky9d17c822006-10-25 23:48:24 +00001442
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001443 if (isa<Constant>(V1) && isa<Constant>(V2))
1444 return false;
1445
Nick Lewycky73dd6922007-07-05 03:15:00 +00001446 unsigned n1 = VN.valueNumber(V1, Top), n2 = VN.valueNumber(V2, Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001447
1448 if (n1 && n2) {
1449 if (n1 == n2) return true;
1450 if (IG.isRelatedBy(n1, n2, Top, NE)) return false;
1451 }
1452
Nick Lewycky73dd6922007-07-05 03:15:00 +00001453 if (n1) assert(V1 == VN.value(n1) && "Value isn't canonical.");
1454 if (n2) assert(V2 == VN.value(n2) && "Value isn't canonical.");
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001455
Nick Lewycky73dd6922007-07-05 03:15:00 +00001456 assert(!VN.compare(V2, V1) && "Please order parameters to makeEqual.");
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001457
1458 assert(!isa<Constant>(V2) && "Tried to remove a constant.");
1459
1460 SetVector<unsigned> Remove;
1461 if (n2) Remove.insert(n2);
1462
1463 if (n1 && n2) {
1464 // Suppose we're being told that %x == %y, and %x <= %z and %y >= %z.
1465 // We can't just merge %x and %y because the relationship with %z would
1466 // be EQ and that's invalid. What we're doing is looking for any nodes
1467 // %z such that %x <= %z and %y >= %z, and vice versa.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001468
Nick Lewyckye635cc42007-07-10 03:28:21 +00001469 Node::iterator end = IG.node(n2)->end();
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001470
1471 // Find the intersection between N1 and N2 which is dominated by
1472 // Top. If we find %x where N1 <= %x <= N2 (or >=) then add %x to
1473 // Remove.
Nick Lewyckye635cc42007-07-10 03:28:21 +00001474 for (Node::iterator I = IG.node(n1)->begin(), E = IG.node(n1)->end();
1475 I != E; ++I) {
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001476 if (!(I->LV & EQ_BIT) || !Top->DominatedBy(I->Subtree)) continue;
1477
1478 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
1479 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
Nick Lewyckye635cc42007-07-10 03:28:21 +00001480 Node::iterator NI = IG.node(n2)->find(I->To, Top);
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00001481 if (NI != end) {
1482 LatticeVal NILV = reversePredicate(NI->LV);
1483 unsigned NILV_s = NILV & (SLT_BIT|SGT_BIT);
1484 unsigned NILV_u = NILV & (ULT_BIT|UGT_BIT);
1485
1486 if ((ILV_s != (SLT_BIT|SGT_BIT) && ILV_s == NILV_s) ||
1487 (ILV_u != (ULT_BIT|UGT_BIT) && ILV_u == NILV_u))
1488 Remove.insert(I->To);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001489 }
1490 }
1491
1492 // See if one of the nodes about to be removed is actually a better
1493 // canonical choice than n1.
1494 unsigned orig_n1 = n1;
Reid Spencera8a15472007-01-17 02:23:37 +00001495 SetVector<unsigned>::iterator DontRemove = Remove.end();
1496 for (SetVector<unsigned>::iterator I = Remove.begin()+1 /* skip n2 */,
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001497 E = Remove.end(); I != E; ++I) {
1498 unsigned n = *I;
Nick Lewycky73dd6922007-07-05 03:15:00 +00001499 Value *V = VN.value(n);
1500 if (VN.compare(V, V1)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001501 V1 = V;
1502 n1 = n;
1503 DontRemove = I;
1504 }
1505 }
1506 if (DontRemove != Remove.end()) {
1507 unsigned n = *DontRemove;
1508 Remove.remove(n);
1509 Remove.insert(orig_n1);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001510 }
1511 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001512
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001513 // We'd like to allow makeEqual on two values to perform a simple
1514 // substitution without every creating nodes in the IG whenever possible.
1515 //
1516 // The first iteration through this loop operates on V2 before going
1517 // through the Remove list and operating on those too. If all of the
1518 // iterations performed simple replacements then we exit early.
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001519 bool mergeIGNode = false;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001520 unsigned i = 0;
1521 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00001522 if (i) R = VN.value(Remove[i]); // skip n2.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001523
1524 // Try to replace the whole instruction. If we can, we're done.
1525 Instruction *I2 = dyn_cast<Instruction>(R);
1526 if (I2 && below(I2)) {
1527 std::vector<Instruction *> ToNotify;
1528 for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
1529 UI != UE;) {
1530 Use &TheUse = UI.getUse();
1531 ++UI;
1532 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser()))
1533 ToNotify.push_back(I);
1534 }
1535
1536 DOUT << "Simply removing " << *I2
1537 << ", replacing with " << *V1 << "\n";
1538 I2->replaceAllUsesWith(V1);
1539 // leave it dead; it'll get erased later.
1540 ++NumInstruction;
1541 modified = true;
1542
1543 for (std::vector<Instruction *>::iterator II = ToNotify.begin(),
1544 IE = ToNotify.end(); II != IE; ++II) {
1545 opsToDef(*II);
1546 }
1547
1548 continue;
1549 }
1550
1551 // Otherwise, replace all dominated uses.
1552 for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
1553 UI != UE;) {
1554 Use &TheUse = UI.getUse();
1555 ++UI;
1556 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
1557 if (below(I)) {
1558 TheUse.set(V1);
1559 modified = true;
1560 ++NumVarsReplaced;
1561 opsToDef(I);
1562 }
1563 }
1564 }
1565
1566 // If that killed the instruction, stop here.
1567 if (I2 && isInstructionTriviallyDead(I2)) {
1568 DOUT << "Killed all uses of " << *I2
1569 << ", replacing with " << *V1 << "\n";
1570 continue;
1571 }
1572
1573 // If we make it to here, then we will need to create a node for N1.
1574 // Otherwise, we can skip out early!
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001575 mergeIGNode = true;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001576 }
1577
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001578 if (!isa<Constant>(V1)) {
1579 if (Remove.empty()) {
Nick Lewyckye635cc42007-07-10 03:28:21 +00001580 VR.mergeInto(&V2, 1, VN.getOrInsertVN(V1, Top), Top, this);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001581 } else {
1582 std::vector<Value*> RemoveVals;
1583 RemoveVals.reserve(Remove.size());
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001584
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001585 for (SetVector<unsigned>::iterator I = Remove.begin(),
1586 E = Remove.end(); I != E; ++I) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00001587 Value *V = VN.value(*I);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001588 if (!V->use_empty())
1589 RemoveVals.push_back(V);
1590 }
Nick Lewyckye635cc42007-07-10 03:28:21 +00001591 VR.mergeInto(&RemoveVals[0], RemoveVals.size(),
1592 VN.getOrInsertVN(V1, Top), Top, this);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001593 }
1594 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001595
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001596 if (mergeIGNode) {
1597 // Create N1.
Nick Lewyckye635cc42007-07-10 03:28:21 +00001598 if (!n1) n1 = VN.getOrInsertVN(V1, Top);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001599
1600 // Migrate relationships from removed nodes to N1.
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001601 for (SetVector<unsigned>::iterator I = Remove.begin(), E = Remove.end();
1602 I != E; ++I) {
1603 unsigned n = *I;
Nick Lewyckye635cc42007-07-10 03:28:21 +00001604 for (Node::iterator NI = IG.node(n)->begin(), NE = IG.node(n)->end();
1605 NI != NE; ++NI) {
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001606 if (NI->Subtree->DominatedBy(Top)) {
1607 if (NI->To == n1) {
1608 assert((NI->LV & EQ_BIT) && "Node inequal to itself.");
1609 continue;
1610 }
1611 if (Remove.count(NI->To))
1612 continue;
1613
1614 IG.node(NI->To)->update(n1, reversePredicate(NI->LV), Top);
Nick Lewyckye635cc42007-07-10 03:28:21 +00001615 IG.node(n1)->update(NI->To, NI->LV, Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001616 }
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001617 }
1618 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001619
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001620 // Point V2 (and all items in Remove) to N1.
1621 if (!n2)
Nick Lewycky73dd6922007-07-05 03:15:00 +00001622 VN.addEquality(n1, V2, Top);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001623 else {
1624 for (SetVector<unsigned>::iterator I = Remove.begin(),
1625 E = Remove.end(); I != E; ++I) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00001626 VN.addEquality(n1, VN.value(*I), Top);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001627 }
1628 }
1629
1630 // If !Remove.empty() then V2 = Remove[0]->getValue().
1631 // Even when Remove is empty, we still want to process V2.
1632 i = 0;
1633 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00001634 if (i) R = VN.value(Remove[i]); // skip n2.
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001635
1636 if (Instruction *I2 = dyn_cast<Instruction>(R)) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00001637 if (aboveOrBelow(I2))
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001638 defToOps(I2);
1639 }
1640 for (Value::use_iterator UI = V2->use_begin(), UE = V2->use_end();
1641 UI != UE;) {
1642 Use &TheUse = UI.getUse();
1643 ++UI;
1644 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00001645 if (aboveOrBelow(I))
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001646 opsToDef(I);
1647 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001648 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001649 }
1650 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001651
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001652 // re-opsToDef all dominated users of V1.
1653 if (Instruction *I = dyn_cast<Instruction>(V1)) {
1654 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001655 UI != UE;) {
1656 Use &TheUse = UI.getUse();
1657 ++UI;
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001658 Value *V = TheUse.getUser();
1659 if (!V->use_empty()) {
1660 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00001661 if (aboveOrBelow(Inst))
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001662 opsToDef(Inst);
1663 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001664 }
1665 }
1666 }
1667
1668 return true;
1669 }
1670
1671 /// cmpInstToLattice - converts an CmpInst::Predicate to lattice value
1672 /// Requires that the lattice value be valid; does not accept ICMP_EQ.
1673 static LatticeVal cmpInstToLattice(ICmpInst::Predicate Pred) {
1674 switch (Pred) {
1675 case ICmpInst::ICMP_EQ:
1676 assert(!"No matching lattice value.");
1677 return static_cast<LatticeVal>(EQ_BIT);
1678 default:
1679 assert(!"Invalid 'icmp' predicate.");
1680 case ICmpInst::ICMP_NE:
1681 return NE;
1682 case ICmpInst::ICMP_UGT:
Nick Lewycky56639802007-01-29 02:56:54 +00001683 return UGT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001684 case ICmpInst::ICMP_UGE:
Nick Lewycky56639802007-01-29 02:56:54 +00001685 return UGE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001686 case ICmpInst::ICMP_ULT:
Nick Lewycky56639802007-01-29 02:56:54 +00001687 return ULT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001688 case ICmpInst::ICMP_ULE:
Nick Lewycky56639802007-01-29 02:56:54 +00001689 return ULE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001690 case ICmpInst::ICMP_SGT:
Nick Lewycky56639802007-01-29 02:56:54 +00001691 return SGT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001692 case ICmpInst::ICMP_SGE:
Nick Lewycky56639802007-01-29 02:56:54 +00001693 return SGE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001694 case ICmpInst::ICMP_SLT:
Nick Lewycky56639802007-01-29 02:56:54 +00001695 return SLT;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001696 case ICmpInst::ICMP_SLE:
Nick Lewycky56639802007-01-29 02:56:54 +00001697 return SLE;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001698 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001699 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001700
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001701 public:
Nick Lewycky73dd6922007-07-05 03:15:00 +00001702 VRPSolver(ValueNumbering &VN, InequalityGraph &IG, UnreachableBlocks &UB,
1703 ValueRanges &VR, DomTreeDFS *DTDFS, bool &modified,
1704 BasicBlock *TopBB)
1705 : VN(VN),
1706 IG(IG),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001707 UB(UB),
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001708 VR(VR),
Nick Lewycky26e25d32007-06-24 04:36:20 +00001709 DTDFS(DTDFS),
1710 Top(DTDFS->getNodeForBlock(TopBB)),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001711 TopBB(TopBB),
1712 TopInst(NULL),
Nick Lewycky26e25d32007-06-24 04:36:20 +00001713 modified(modified)
1714 {
1715 assert(Top && "VRPSolver created for unreachable basic block.");
1716 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00001717
Nick Lewycky73dd6922007-07-05 03:15:00 +00001718 VRPSolver(ValueNumbering &VN, InequalityGraph &IG, UnreachableBlocks &UB,
1719 ValueRanges &VR, DomTreeDFS *DTDFS, bool &modified,
1720 Instruction *TopInst)
1721 : VN(VN),
1722 IG(IG),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001723 UB(UB),
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001724 VR(VR),
Nick Lewycky26e25d32007-06-24 04:36:20 +00001725 DTDFS(DTDFS),
1726 Top(DTDFS->getNodeForBlock(TopInst->getParent())),
1727 TopBB(TopInst->getParent()),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001728 TopInst(TopInst),
1729 modified(modified)
1730 {
Nick Lewycky26e25d32007-06-24 04:36:20 +00001731 assert(Top && "VRPSolver created for unreachable basic block.");
1732 assert(Top->getBlock() == TopInst->getParent() && "Context mismatch.");
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001733 }
1734
1735 bool isRelatedBy(Value *V1, Value *V2, ICmpInst::Predicate Pred) const {
1736 if (Constant *C1 = dyn_cast<Constant>(V1))
1737 if (Constant *C2 = dyn_cast<Constant>(V2))
1738 return ConstantExpr::getCompare(Pred, C1, C2) ==
Zhou Sheng75b871f2007-01-11 12:24:14 +00001739 ConstantInt::getTrue();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001740
Nick Lewyckye635cc42007-07-10 03:28:21 +00001741 unsigned n1 = VN.valueNumber(V1, Top);
1742 unsigned n2 = VN.valueNumber(V2, Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001743
Nick Lewyckye635cc42007-07-10 03:28:21 +00001744 if (n1 && n2) {
1745 if (n1 == n2) return Pred == ICmpInst::ICMP_EQ ||
1746 Pred == ICmpInst::ICMP_ULE ||
1747 Pred == ICmpInst::ICMP_UGE ||
1748 Pred == ICmpInst::ICMP_SLE ||
1749 Pred == ICmpInst::ICMP_SGE;
1750 if (Pred == ICmpInst::ICMP_EQ) return false;
1751 if (IG.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
1752 if (VR.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
1753 }
1754
1755 if ((n1 && !n2 && isa<Constant>(V2)) ||
1756 (n2 && !n1 && isa<Constant>(V1))) {
1757 ConstantRange CR1 = n1 ? VR.range(n1, Top) : VR.range(V1);
1758 ConstantRange CR2 = n2 ? VR.range(n2, Top) : VR.range(V2);
1759
1760 if (Pred == ICmpInst::ICMP_EQ)
1761 return CR1.isSingleElement() &&
1762 CR1.getSingleElement() == CR2.getSingleElement();
1763
1764 return VR.isRelatedBy(CR1, CR2, cmpInstToLattice(Pred));
1765 }
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001766 if (Pred == ICmpInst::ICMP_EQ) return V1 == V2;
Nick Lewyckye635cc42007-07-10 03:28:21 +00001767 return false;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001768 }
1769
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001770 /// add - adds a new property to the work queue
1771 void add(Value *V1, Value *V2, ICmpInst::Predicate Pred,
1772 Instruction *I = NULL) {
1773 DOUT << "adding " << *V1 << " " << Pred << " " << *V2;
1774 if (I) DOUT << " context: " << *I;
Nick Lewycky26e25d32007-06-24 04:36:20 +00001775 else DOUT << " default context (" << Top->getDFSNumIn() << ")";
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001776 DOUT << "\n";
1777
Nick Lewycky12d44ab2007-04-07 03:16:12 +00001778 assert(V1->getType() == V2->getType() &&
1779 "Can't relate two values with different types.");
1780
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001781 WorkList.push_back(Operation());
1782 Operation &O = WorkList.back();
Nick Lewycky42944462007-01-13 02:05:28 +00001783 O.LHS = V1, O.RHS = V2, O.Op = Pred, O.ContextInst = I;
1784 O.ContextBB = I ? I->getParent() : TopBB;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001785 }
1786
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001787 /// defToOps - Given an instruction definition that we've learned something
1788 /// new about, find any new relationships between its operands.
1789 void defToOps(Instruction *I) {
1790 Instruction *NewContext = below(I) ? I : TopInst;
Nick Lewycky73dd6922007-07-05 03:15:00 +00001791 Value *Canonical = VN.canonicalize(I, Top);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001792
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001793 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1794 const Type *Ty = BO->getType();
1795 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001796
Nick Lewycky73dd6922007-07-05 03:15:00 +00001797 Value *Op0 = VN.canonicalize(BO->getOperand(0), Top);
1798 Value *Op1 = VN.canonicalize(BO->getOperand(1), Top);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001799
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001800 // TODO: "and i32 -1, %x" EQ %y then %x EQ %y.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001801
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001802 switch (BO->getOpcode()) {
1803 case Instruction::And: {
Nick Lewycky4f73de22007-03-16 02:37:39 +00001804 // "and i32 %a, %b" EQ -1 then %a EQ -1 and %b EQ -1
Zhou Sheng75b871f2007-01-11 12:24:14 +00001805 ConstantInt *CI = ConstantInt::getAllOnesValue(Ty);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001806 if (Canonical == CI) {
1807 add(CI, Op0, ICmpInst::ICMP_EQ, NewContext);
1808 add(CI, Op1, ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001809 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001810 } break;
1811 case Instruction::Or: {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001812 // "or i32 %a, %b" EQ 0 then %a EQ 0 and %b EQ 0
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001813 Constant *Zero = Constant::getNullValue(Ty);
1814 if (Canonical == Zero) {
1815 add(Zero, Op0, ICmpInst::ICMP_EQ, NewContext);
1816 add(Zero, Op1, ICmpInst::ICMP_EQ, NewContext);
1817 }
1818 } break;
1819 case Instruction::Xor: {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001820 // "xor i32 %c, %a" EQ %b then %a EQ %c ^ %b
1821 // "xor i32 %c, %a" EQ %c then %a EQ 0
1822 // "xor i32 %c, %a" NE %c then %a NE 0
1823 // Repeat the above, with order of operands reversed.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001824 Value *LHS = Op0;
1825 Value *RHS = Op1;
1826 if (!isa<Constant>(LHS)) std::swap(LHS, RHS);
1827
Nick Lewycky4a74a752007-01-12 00:02:12 +00001828 if (ConstantInt *CI = dyn_cast<ConstantInt>(Canonical)) {
1829 if (ConstantInt *Arg = dyn_cast<ConstantInt>(LHS)) {
Reid Spencerc34dedf2007-03-03 00:48:31 +00001830 add(RHS, ConstantInt::get(CI->getValue() ^ Arg->getValue()),
Nick Lewycky4a74a752007-01-12 00:02:12 +00001831 ICmpInst::ICMP_EQ, NewContext);
1832 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001833 }
1834 if (Canonical == LHS) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001835 if (isa<ConstantInt>(Canonical))
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001836 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_EQ,
1837 NewContext);
1838 } else if (isRelatedBy(LHS, Canonical, ICmpInst::ICMP_NE)) {
1839 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_NE,
1840 NewContext);
1841 }
1842 } break;
1843 default:
1844 break;
1845 }
1846 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001847 // "icmp ult i32 %a, %y" EQ true then %a u< y
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001848 // etc.
1849
Zhou Sheng75b871f2007-01-11 12:24:14 +00001850 if (Canonical == ConstantInt::getTrue()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001851 add(IC->getOperand(0), IC->getOperand(1), IC->getPredicate(),
1852 NewContext);
Zhou Sheng75b871f2007-01-11 12:24:14 +00001853 } else if (Canonical == ConstantInt::getFalse()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001854 add(IC->getOperand(0), IC->getOperand(1),
1855 ICmpInst::getInversePredicate(IC->getPredicate()), NewContext);
1856 }
1857 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
1858 if (I->getType()->isFPOrFPVector()) return;
1859
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001860 // Given: "%a = select i1 %x, i32 %b, i32 %c"
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001861 // %a EQ %b and %b NE %c then %x EQ true
1862 // %a EQ %c and %b NE %c then %x EQ false
1863
1864 Value *True = SI->getTrueValue();
1865 Value *False = SI->getFalseValue();
1866 if (isRelatedBy(True, False, ICmpInst::ICMP_NE)) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00001867 if (Canonical == VN.canonicalize(True, Top) ||
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001868 isRelatedBy(Canonical, False, ICmpInst::ICMP_NE))
Zhou Sheng75b871f2007-01-11 12:24:14 +00001869 add(SI->getCondition(), ConstantInt::getTrue(),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001870 ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky73dd6922007-07-05 03:15:00 +00001871 else if (Canonical == VN.canonicalize(False, Top) ||
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001872 isRelatedBy(Canonical, True, ICmpInst::ICMP_NE))
Zhou Sheng75b871f2007-01-11 12:24:14 +00001873 add(SI->getCondition(), ConstantInt::getFalse(),
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001874 ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001875 }
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001876 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1877 for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
1878 OE = GEPI->idx_end(); OI != OE; ++OI) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00001879 ConstantInt *Op = dyn_cast<ConstantInt>(VN.canonicalize(*OI, Top));
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001880 if (!Op || !Op->isZero()) return;
1881 }
1882 // TODO: The GEPI indices are all zero. Copy from definition to operand,
1883 // jumping the type plane as needed.
1884 if (isRelatedBy(GEPI, Constant::getNullValue(GEPI->getType()),
1885 ICmpInst::ICMP_NE)) {
1886 Value *Ptr = GEPI->getPointerOperand();
1887 add(Ptr, Constant::getNullValue(Ptr->getType()), ICmpInst::ICMP_NE,
1888 NewContext);
1889 }
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001890 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
1891 const Type *SrcTy = CI->getSrcTy();
1892
Nick Lewyckye635cc42007-07-10 03:28:21 +00001893 unsigned ci = VN.getOrInsertVN(CI, Top);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001894 uint32_t W = VR.typeToWidth(SrcTy);
1895 if (!W) return;
Nick Lewyckye635cc42007-07-10 03:28:21 +00001896 ConstantRange CR = VR.range(ci, Top);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001897
1898 if (CR.isFullSet()) return;
1899
1900 switch (CI->getOpcode()) {
1901 default: break;
1902 case Instruction::ZExt:
1903 case Instruction::SExt:
Nick Lewyckye635cc42007-07-10 03:28:21 +00001904 VR.applyRange(VN.getOrInsertVN(CI->getOperand(0), Top),
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001905 CR.truncate(W), Top, this);
1906 break;
1907 case Instruction::BitCast:
Nick Lewyckye635cc42007-07-10 03:28:21 +00001908 VR.applyRange(VN.getOrInsertVN(CI->getOperand(0), Top),
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001909 CR, Top, this);
1910 break;
1911 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001912 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001913 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001914
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001915 /// opsToDef - A new relationship was discovered involving one of this
1916 /// instruction's operands. Find any new relationship involving the
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001917 /// definition, or another operand.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001918 void opsToDef(Instruction *I) {
1919 Instruction *NewContext = below(I) ? I : TopInst;
1920
1921 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00001922 Value *Op0 = VN.canonicalize(BO->getOperand(0), Top);
1923 Value *Op1 = VN.canonicalize(BO->getOperand(1), Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001924
Zhou Sheng75b871f2007-01-11 12:24:14 +00001925 if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0))
1926 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001927 add(BO, ConstantExpr::get(BO->getOpcode(), CI0, CI1),
1928 ICmpInst::ICMP_EQ, NewContext);
1929 return;
1930 }
1931
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001932 // "%y = and i1 true, %x" then %x EQ %y
1933 // "%y = or i1 false, %x" then %x EQ %y
1934 // "%x = add i32 %y, 0" then %x EQ %y
1935 // "%x = mul i32 %y, 0" then %x EQ 0
1936
1937 Instruction::BinaryOps Opcode = BO->getOpcode();
Nick Lewyckydb204ec2007-03-18 22:58:46 +00001938 const Type *Ty = BO->getType();
1939 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
1940
1941 Constant *Zero = Constant::getNullValue(Ty);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00001942 ConstantInt *AllOnes = ConstantInt::getAllOnesValue(Ty);
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001943
1944 switch (Opcode) {
1945 default: break;
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001946 case Instruction::LShr:
1947 case Instruction::AShr:
1948 case Instruction::Shl:
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001949 case Instruction::Sub:
Nick Lewyckydb204ec2007-03-18 22:58:46 +00001950 if (Op1 == Zero) {
1951 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1952 return;
1953 }
1954 break;
1955 case Instruction::Or:
1956 if (Op0 == AllOnes || Op1 == AllOnes) {
1957 add(BO, AllOnes, ICmpInst::ICMP_EQ, NewContext);
1958 return;
1959 } // fall-through
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001960 case Instruction::Xor:
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001961 case Instruction::Add:
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001962 if (Op0 == Zero) {
1963 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1964 return;
1965 } else if (Op1 == Zero) {
1966 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1967 return;
1968 }
Nick Lewyckydb204ec2007-03-18 22:58:46 +00001969 break;
1970 case Instruction::And:
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001971 if (Op0 == AllOnes) {
1972 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1973 return;
1974 } else if (Op1 == AllOnes) {
1975 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1976 return;
1977 }
Nick Lewyckydb204ec2007-03-18 22:58:46 +00001978 // fall-through
1979 case Instruction::Mul:
1980 if (Op0 == Zero || Op1 == Zero) {
Nick Lewycky17d20fd2007-03-18 01:09:32 +00001981 add(BO, Zero, ICmpInst::ICMP_EQ, NewContext);
1982 return;
1983 }
Nick Lewyckydb204ec2007-03-18 22:58:46 +00001984 break;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001985 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001986
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001987 // "%x = add i32 %y, %z" and %x EQ %y then %z EQ 0
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001988 // "%x = add i32 %y, %z" and %x EQ %z then %y EQ 0
1989 // "%x = shl i32 %y, %z" and %x EQ %y and %y NE 0 then %z EQ 0
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00001990 // "%x = udiv i32 %y, %z" and %x EQ %y then %z EQ 1
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00001991
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001992 Value *Known = Op0, *Unknown = Op1,
Nick Lewycky73dd6922007-07-05 03:15:00 +00001993 *TheBO = VN.canonicalize(BO, Top);
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001994 if (Known != TheBO) std::swap(Known, Unknown);
1995 if (Known == TheBO) {
Nick Lewycky4f73de22007-03-16 02:37:39 +00001996 switch (Opcode) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00001997 default: break;
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00001998 case Instruction::LShr:
1999 case Instruction::AShr:
2000 case Instruction::Shl:
2001 if (!isRelatedBy(Known, Zero, ICmpInst::ICMP_NE)) break;
2002 // otherwise, fall-through.
2003 case Instruction::Sub:
Nick Lewyckyeae7e7d2007-09-20 00:48:36 +00002004 if (Unknown == Op0) break;
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00002005 // otherwise, fall-through.
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002006 case Instruction::Xor:
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002007 case Instruction::Add:
Nick Lewyckydb204ec2007-03-18 22:58:46 +00002008 add(Unknown, Zero, ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002009 break;
2010 case Instruction::UDiv:
2011 case Instruction::SDiv:
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00002012 if (Unknown == Op1) break;
2013 if (isRelatedBy(Known, Zero, ICmpInst::ICMP_NE)) {
Nick Lewycky4a74a752007-01-12 00:02:12 +00002014 Constant *One = ConstantInt::get(Ty, 1);
2015 add(Unknown, One, ICmpInst::ICMP_EQ, NewContext);
2016 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00002017 break;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002018 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002019 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002020
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002021 // TODO: "%a = add i32 %b, 1" and %b > %z then %a >= %z.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002022
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002023 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
Nick Lewycky4f73de22007-03-16 02:37:39 +00002024 // "%a = icmp ult i32 %b, %c" and %b u< %c then %a EQ true
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002025 // "%a = icmp ult i32 %b, %c" and %b u>= %c then %a EQ false
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002026 // etc.
2027
Nick Lewycky73dd6922007-07-05 03:15:00 +00002028 Value *Op0 = VN.canonicalize(IC->getOperand(0), Top);
2029 Value *Op1 = VN.canonicalize(IC->getOperand(1), Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002030
2031 ICmpInst::Predicate Pred = IC->getPredicate();
Nick Lewyckye635cc42007-07-10 03:28:21 +00002032 if (isRelatedBy(Op0, Op1, Pred))
Zhou Sheng75b871f2007-01-11 12:24:14 +00002033 add(IC, ConstantInt::getTrue(), ICmpInst::ICMP_EQ, NewContext);
Nick Lewyckye635cc42007-07-10 03:28:21 +00002034 else if (isRelatedBy(Op0, Op1, ICmpInst::getInversePredicate(Pred)))
Zhou Sheng75b871f2007-01-11 12:24:14 +00002035 add(IC, ConstantInt::getFalse(), ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002036
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002037 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00002038 if (I->getType()->isFPOrFPVector()) return;
2039
Nick Lewycky4f73de22007-03-16 02:37:39 +00002040 // Given: "%a = select i1 %x, i32 %b, i32 %c"
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002041 // %x EQ true then %a EQ %b
2042 // %x EQ false then %a EQ %c
2043 // %b EQ %c then %a EQ %b
2044
Nick Lewycky73dd6922007-07-05 03:15:00 +00002045 Value *Canonical = VN.canonicalize(SI->getCondition(), Top);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002046 if (Canonical == ConstantInt::getTrue()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002047 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002048 } else if (Canonical == ConstantInt::getFalse()) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002049 add(SI, SI->getFalseValue(), ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky73dd6922007-07-05 03:15:00 +00002050 } else if (VN.canonicalize(SI->getTrueValue(), Top) ==
2051 VN.canonicalize(SI->getFalseValue(), Top)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002052 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
2053 }
Nick Lewyckyee32ee02007-01-12 01:23:53 +00002054 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00002055 const Type *DestTy = CI->getDestTy();
2056 if (DestTy->isFPOrFPVector()) return;
Nick Lewyckyee32ee02007-01-12 01:23:53 +00002057
Nick Lewycky73dd6922007-07-05 03:15:00 +00002058 Value *Op = VN.canonicalize(CI->getOperand(0), Top);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00002059 Instruction::CastOps Opcode = CI->getOpcode();
2060
2061 if (Constant *C = dyn_cast<Constant>(Op)) {
2062 add(CI, ConstantExpr::getCast(Opcode, C, DestTy),
Nick Lewyckyee32ee02007-01-12 01:23:53 +00002063 ICmpInst::ICMP_EQ, NewContext);
2064 }
2065
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00002066 uint32_t W = VR.typeToWidth(DestTy);
Nick Lewyckye635cc42007-07-10 03:28:21 +00002067 unsigned ci = VN.getOrInsertVN(CI, Top);
2068 ConstantRange CR = VR.range(VN.getOrInsertVN(Op, Top), Top);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00002069
2070 if (!CR.isFullSet()) {
2071 switch (Opcode) {
2072 default: break;
2073 case Instruction::ZExt:
Nick Lewyckye635cc42007-07-10 03:28:21 +00002074 VR.applyRange(ci, CR.zeroExtend(W), Top, this);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00002075 break;
2076 case Instruction::SExt:
Nick Lewyckye635cc42007-07-10 03:28:21 +00002077 VR.applyRange(ci, CR.signExtend(W), Top, this);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00002078 break;
2079 case Instruction::Trunc: {
2080 ConstantRange Result = CR.truncate(W);
2081 if (!Result.isFullSet())
Nick Lewyckye635cc42007-07-10 03:28:21 +00002082 VR.applyRange(ci, Result, Top, this);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00002083 } break;
2084 case Instruction::BitCast:
Nick Lewyckye635cc42007-07-10 03:28:21 +00002085 VR.applyRange(ci, CR, Top, this);
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00002086 break;
2087 // TODO: other casts?
2088 }
2089 }
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00002090 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
2091 for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
2092 OE = GEPI->idx_end(); OI != OE; ++OI) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002093 ConstantInt *Op = dyn_cast<ConstantInt>(VN.canonicalize(*OI, Top));
Nick Lewyckyb0da7ed2007-03-22 02:02:51 +00002094 if (!Op || !Op->isZero()) return;
2095 }
2096 // TODO: The GEPI indices are all zero. Copy from operand to definition,
2097 // jumping the type plane as needed.
2098 Value *Ptr = GEPI->getPointerOperand();
2099 if (isRelatedBy(Ptr, Constant::getNullValue(Ptr->getType()),
2100 ICmpInst::ICMP_NE)) {
2101 add(GEPI, Constant::getNullValue(GEPI->getType()), ICmpInst::ICMP_NE,
2102 NewContext);
2103 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002104 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002105 }
2106
2107 /// solve - process the work queue
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002108 void solve() {
2109 //DOUT << "WorkList entry, size: " << WorkList.size() << "\n";
2110 while (!WorkList.empty()) {
2111 //DOUT << "WorkList size: " << WorkList.size() << "\n";
2112
2113 Operation &O = WorkList.front();
Nick Lewycky42944462007-01-13 02:05:28 +00002114 TopInst = O.ContextInst;
2115 TopBB = O.ContextBB;
Nick Lewycky26e25d32007-06-24 04:36:20 +00002116 Top = DTDFS->getNodeForBlock(TopBB); // XXX move this into Context
Nick Lewycky42944462007-01-13 02:05:28 +00002117
Nick Lewycky73dd6922007-07-05 03:15:00 +00002118 O.LHS = VN.canonicalize(O.LHS, Top);
2119 O.RHS = VN.canonicalize(O.RHS, Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002120
Nick Lewycky73dd6922007-07-05 03:15:00 +00002121 assert(O.LHS == VN.canonicalize(O.LHS, Top) && "Canonicalize isn't.");
2122 assert(O.RHS == VN.canonicalize(O.RHS, Top) && "Canonicalize isn't.");
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002123
2124 DOUT << "solving " << *O.LHS << " " << O.Op << " " << *O.RHS;
Nick Lewycky42944462007-01-13 02:05:28 +00002125 if (O.ContextInst) DOUT << " context inst: " << *O.ContextInst;
2126 else DOUT << " context block: " << O.ContextBB->getName();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002127 DOUT << "\n";
2128
Nick Lewyckye635cc42007-07-10 03:28:21 +00002129 DEBUG(VN.dump());
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002130 DEBUG(IG.dump());
Nick Lewyckye635cc42007-07-10 03:28:21 +00002131 DEBUG(VR.dump());
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002132
Nick Lewycky15245952007-02-04 23:43:05 +00002133 // If they're both Constant, skip it. Check for contradiction and mark
2134 // the BB as unreachable if so.
2135 if (Constant *CI_L = dyn_cast<Constant>(O.LHS)) {
2136 if (Constant *CI_R = dyn_cast<Constant>(O.RHS)) {
2137 if (ConstantExpr::getCompare(O.Op, CI_L, CI_R) ==
2138 ConstantInt::getFalse())
2139 UB.mark(TopBB);
2140
2141 WorkList.pop_front();
2142 continue;
2143 }
2144 }
2145
Nick Lewycky73dd6922007-07-05 03:15:00 +00002146 if (VN.compare(O.LHS, O.RHS)) {
Nick Lewycky15245952007-02-04 23:43:05 +00002147 std::swap(O.LHS, O.RHS);
2148 O.Op = ICmpInst::getSwappedPredicate(O.Op);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002149 }
2150
2151 if (O.Op == ICmpInst::ICMP_EQ) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002152 if (!makeEqual(O.RHS, O.LHS))
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002153 UB.mark(TopBB);
2154 } else {
2155 LatticeVal LV = cmpInstToLattice(O.Op);
2156
2157 if ((LV & EQ_BIT) &&
2158 isRelatedBy(O.LHS, O.RHS, ICmpInst::getSwappedPredicate(O.Op))) {
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002159 if (!makeEqual(O.RHS, O.LHS))
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002160 UB.mark(TopBB);
2161 } else {
2162 if (isRelatedBy(O.LHS, O.RHS, ICmpInst::getInversePredicate(O.Op))){
Nick Lewycky15245952007-02-04 23:43:05 +00002163 UB.mark(TopBB);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002164 WorkList.pop_front();
2165 continue;
2166 }
2167
Nick Lewyckye635cc42007-07-10 03:28:21 +00002168 unsigned n1 = VN.getOrInsertVN(O.LHS, Top);
2169 unsigned n2 = VN.getOrInsertVN(O.RHS, Top);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002170
Nick Lewyckye635cc42007-07-10 03:28:21 +00002171 if (n1 == n2) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002172 if (O.Op != ICmpInst::ICMP_UGE && O.Op != ICmpInst::ICMP_ULE &&
2173 O.Op != ICmpInst::ICMP_SGE && O.Op != ICmpInst::ICMP_SLE)
2174 UB.mark(TopBB);
2175
2176 WorkList.pop_front();
2177 continue;
2178 }
2179
Nick Lewyckye635cc42007-07-10 03:28:21 +00002180 if (VR.isRelatedBy(n1, n2, Top, LV) ||
2181 IG.isRelatedBy(n1, n2, Top, LV)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002182 WorkList.pop_front();
2183 continue;
2184 }
2185
Nick Lewyckye635cc42007-07-10 03:28:21 +00002186 VR.addInequality(n1, n2, Top, LV, this);
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002187 if ((!isa<ConstantInt>(O.RHS) && !isa<ConstantInt>(O.LHS)) ||
Nick Lewyckye635cc42007-07-10 03:28:21 +00002188 LV == NE)
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002189 IG.addInequality(n1, n2, Top, LV);
Nick Lewycky15245952007-02-04 23:43:05 +00002190
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002191 if (Instruction *I1 = dyn_cast<Instruction>(O.LHS)) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002192 if (aboveOrBelow(I1))
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002193 defToOps(I1);
2194 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002195 if (isa<Instruction>(O.LHS) || isa<Argument>(O.LHS)) {
2196 for (Value::use_iterator UI = O.LHS->use_begin(),
2197 UE = O.LHS->use_end(); UI != UE;) {
2198 Use &TheUse = UI.getUse();
2199 ++UI;
2200 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002201 if (aboveOrBelow(I))
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002202 opsToDef(I);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002203 }
2204 }
2205 }
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002206 if (Instruction *I2 = dyn_cast<Instruction>(O.RHS)) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002207 if (aboveOrBelow(I2))
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002208 defToOps(I2);
2209 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002210 if (isa<Instruction>(O.RHS) || isa<Argument>(O.RHS)) {
2211 for (Value::use_iterator UI = O.RHS->use_begin(),
2212 UE = O.RHS->use_end(); UI != UE;) {
2213 Use &TheUse = UI.getUse();
2214 ++UI;
2215 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002216 if (aboveOrBelow(I))
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002217 opsToDef(I);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002218 }
2219 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00002220 }
2221 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00002222 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002223 WorkList.pop_front();
Nick Lewycky9d17c822006-10-25 23:48:24 +00002224 }
Nick Lewycky9d17c822006-10-25 23:48:24 +00002225 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002226 };
2227
Nick Lewycky3bb6de82007-04-07 03:36:51 +00002228 void ValueRanges::addToWorklist(Value *V, Constant *C,
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002229 ICmpInst::Predicate Pred, VRPSolver *VRP) {
Nick Lewycky3bb6de82007-04-07 03:36:51 +00002230 VRP->add(V, C, Pred, VRP->TopInst);
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002231 }
2232
Nick Lewyckyd4f51a82007-04-07 15:48:32 +00002233 void ValueRanges::markBlock(VRPSolver *VRP) {
2234 VRP->UB.mark(VRP->TopBB);
2235 }
2236
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002237 /// PredicateSimplifier - This class is a simplifier that replaces
2238 /// one equivalent variable with another. It also tracks what
2239 /// can't be equal and will solve setcc instructions when possible.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002240 /// @brief Root of the predicate simplifier optimization.
2241 class VISIBILITY_HIDDEN PredicateSimplifier : public FunctionPass {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002242 DomTreeDFS *DTDFS;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002243 bool modified;
Nick Lewycky73dd6922007-07-05 03:15:00 +00002244 ValueNumbering *VN;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002245 InequalityGraph *IG;
2246 UnreachableBlocks UB;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002247 ValueRanges *VR;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002248
Nick Lewycky26e25d32007-06-24 04:36:20 +00002249 std::vector<DomTreeDFS::Node *> WorkList;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002250
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002251 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +00002252 static char ID; // Pass identification, replacement for typeid
Devang Patel09f162c2007-05-01 21:15:47 +00002253 PredicateSimplifier() : FunctionPass((intptr_t)&ID) {}
2254
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002255 bool runOnFunction(Function &F);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002256
2257 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
2258 AU.addRequiredID(BreakCriticalEdgesID);
Owen Anderson510fefc2007-04-25 04:18:54 +00002259 AU.addRequired<DominatorTree>();
Nick Lewycky12d44ab2007-04-07 03:16:12 +00002260 AU.addRequired<TargetData>();
2261 AU.addPreserved<TargetData>();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002262 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002263
2264 private:
Nick Lewyckyb7c0c8a2007-07-16 02:58:37 +00002265 /// Forwards - Adds new properties to VRPSolver and uses them to
Nick Lewycky77e030b2006-10-12 02:02:44 +00002266 /// simplify instructions. Because new properties sometimes apply to
2267 /// a transition from one BasicBlock to another, this will use the
2268 /// PredicateSimplifier::proceedToSuccessor(s) interface to enter the
Nick Lewyckyb7c0c8a2007-07-16 02:58:37 +00002269 /// basic block.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002270 /// @brief Performs abstract execution of the program.
2271 class VISIBILITY_HIDDEN Forwards : public InstVisitor<Forwards> {
Nick Lewycky77e030b2006-10-12 02:02:44 +00002272 friend class InstVisitor<Forwards>;
2273 PredicateSimplifier *PS;
Nick Lewycky26e25d32007-06-24 04:36:20 +00002274 DomTreeDFS::Node *DTNode;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002275
Nick Lewycky77e030b2006-10-12 02:02:44 +00002276 public:
Nick Lewycky73dd6922007-07-05 03:15:00 +00002277 ValueNumbering &VN;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002278 InequalityGraph &IG;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002279 UnreachableBlocks &UB;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002280 ValueRanges &VR;
Nick Lewycky77e030b2006-10-12 02:02:44 +00002281
Nick Lewycky26e25d32007-06-24 04:36:20 +00002282 Forwards(PredicateSimplifier *PS, DomTreeDFS::Node *DTNode)
Nick Lewycky73dd6922007-07-05 03:15:00 +00002283 : PS(PS), DTNode(DTNode), VN(*PS->VN), IG(*PS->IG), UB(PS->UB),
2284 VR(*PS->VR) {}
Nick Lewycky77e030b2006-10-12 02:02:44 +00002285
2286 void visitTerminatorInst(TerminatorInst &TI);
2287 void visitBranchInst(BranchInst &BI);
2288 void visitSwitchInst(SwitchInst &SI);
2289
Nick Lewyckyf3450082006-10-22 19:53:27 +00002290 void visitAllocaInst(AllocaInst &AI);
Nick Lewycky77e030b2006-10-12 02:02:44 +00002291 void visitLoadInst(LoadInst &LI);
2292 void visitStoreInst(StoreInst &SI);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002293
Nick Lewycky15245952007-02-04 23:43:05 +00002294 void visitSExtInst(SExtInst &SI);
2295 void visitZExtInst(ZExtInst &ZI);
2296
Nick Lewycky77e030b2006-10-12 02:02:44 +00002297 void visitBinaryOperator(BinaryOperator &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002298 void visitICmpInst(ICmpInst &IC);
Nick Lewycky77e030b2006-10-12 02:02:44 +00002299 };
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002300
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002301 // Used by terminator instructions to proceed from the current basic
2302 // block to the next. Verifies that "current" dominates "next",
2303 // then calls visitBasicBlock.
Nick Lewycky26e25d32007-06-24 04:36:20 +00002304 void proceedToSuccessors(DomTreeDFS::Node *Current) {
2305 for (DomTreeDFS::Node::iterator I = Current->begin(),
Owen Anderson510fefc2007-04-25 04:18:54 +00002306 E = Current->end(); I != E; ++I) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002307 WorkList.push_back(*I);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002308 }
2309 }
2310
Nick Lewycky26e25d32007-06-24 04:36:20 +00002311 void proceedToSuccessor(DomTreeDFS::Node *Next) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002312 WorkList.push_back(Next);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002313 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002314
2315 // Visits each instruction in the basic block.
Nick Lewycky26e25d32007-06-24 04:36:20 +00002316 void visitBasicBlock(DomTreeDFS::Node *Node) {
Owen Anderson510fefc2007-04-25 04:18:54 +00002317 BasicBlock *BB = Node->getBlock();
Nick Lewycky6ce36cf2007-01-15 14:30:07 +00002318 DOUT << "Entering Basic Block: " << BB->getName()
Nick Lewycky26e25d32007-06-24 04:36:20 +00002319 << " (" << Node->getDFSNumIn() << ")\n";
Bill Wendling22e978a2006-12-07 20:04:42 +00002320 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002321 visitInstruction(I++, Node);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002322 }
2323 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002324
Nick Lewyckyb7c0c8a2007-07-16 02:58:37 +00002325 // Tries to simplify each Instruction and add new properties.
Nick Lewycky26e25d32007-06-24 04:36:20 +00002326 void visitInstruction(Instruction *I, DomTreeDFS::Node *DT) {
Bill Wendling22e978a2006-12-07 20:04:42 +00002327 DOUT << "Considering instruction " << *I << "\n";
Nick Lewyckye635cc42007-07-10 03:28:21 +00002328 DEBUG(VN->dump());
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002329 DEBUG(IG->dump());
Nick Lewyckye635cc42007-07-10 03:28:21 +00002330 DEBUG(VR->dump());
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002331
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002332 // Sometimes instructions are killed in earlier analysis.
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002333 if (isInstructionTriviallyDead(I)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002334 ++NumSimple;
2335 modified = true;
Nick Lewycky73dd6922007-07-05 03:15:00 +00002336 if (unsigned n = VN->valueNumber(I, DTDFS->getRootNode()))
2337 if (VN->value(n) == I) IG->remove(n);
2338 VN->remove(I);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002339 I->eraseFromParent();
2340 return;
2341 }
2342
Nick Lewycky42944462007-01-13 02:05:28 +00002343#ifndef NDEBUG
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002344 // Try to replace the whole instruction.
Nick Lewycky73dd6922007-07-05 03:15:00 +00002345 Value *V = VN->canonicalize(I, DT);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002346 assert(V == I && "Late instruction canonicalization.");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002347 if (V != I) {
2348 modified = true;
2349 ++NumInstruction;
Bill Wendling22e978a2006-12-07 20:04:42 +00002350 DOUT << "Removing " << *I << ", replacing with " << *V << "\n";
Nick Lewycky73dd6922007-07-05 03:15:00 +00002351 if (unsigned n = VN->valueNumber(I, DTDFS->getRootNode()))
2352 if (VN->value(n) == I) IG->remove(n);
2353 VN->remove(I);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002354 I->replaceAllUsesWith(V);
2355 I->eraseFromParent();
2356 return;
2357 }
2358
2359 // Try to substitute operands.
2360 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2361 Value *Oper = I->getOperand(i);
Nick Lewycky73dd6922007-07-05 03:15:00 +00002362 Value *V = VN->canonicalize(Oper, DT);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002363 assert(V == Oper && "Late operand canonicalization.");
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002364 if (V != Oper) {
2365 modified = true;
2366 ++NumVarsReplaced;
Bill Wendling22e978a2006-12-07 20:04:42 +00002367 DOUT << "Resolving " << *I;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002368 I->setOperand(i, V);
Bill Wendling22e978a2006-12-07 20:04:42 +00002369 DOUT << " into " << *I;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002370 }
2371 }
Nick Lewycky42944462007-01-13 02:05:28 +00002372#endif
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002373
Nick Lewycky4f73de22007-03-16 02:37:39 +00002374 std::string name = I->getParent()->getName();
2375 DOUT << "push (%" << name << ")\n";
Owen Anderson510fefc2007-04-25 04:18:54 +00002376 Forwards visit(this, DT);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002377 visit.visit(*I);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002378 DOUT << "pop (%" << name << ")\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002379 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002380 };
2381
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002382 bool PredicateSimplifier::runOnFunction(Function &F) {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002383 DominatorTree *DT = &getAnalysis<DominatorTree>();
2384 DTDFS = new DomTreeDFS(DT);
Nick Lewycky12d44ab2007-04-07 03:16:12 +00002385 TargetData *TD = &getAnalysis<TargetData>();
2386
Bill Wendling22e978a2006-12-07 20:04:42 +00002387 DOUT << "Entering Function: " << F.getName() << "\n";
Nick Lewyckycfff1c32006-09-20 17:04:01 +00002388
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002389 modified = false;
Nick Lewycky26e25d32007-06-24 04:36:20 +00002390 DomTreeDFS::Node *Root = DTDFS->getRootNode();
Nick Lewycky73dd6922007-07-05 03:15:00 +00002391 VN = new ValueNumbering(DTDFS);
2392 IG = new InequalityGraph(*VN, Root);
Nick Lewyckye635cc42007-07-10 03:28:21 +00002393 VR = new ValueRanges(*VN, TD);
Nick Lewycky26e25d32007-06-24 04:36:20 +00002394 WorkList.push_back(Root);
Nick Lewyckycfff1c32006-09-20 17:04:01 +00002395
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002396 do {
Nick Lewycky26e25d32007-06-24 04:36:20 +00002397 DomTreeDFS::Node *DTNode = WorkList.back();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002398 WorkList.pop_back();
Owen Anderson510fefc2007-04-25 04:18:54 +00002399 if (!UB.isDead(DTNode->getBlock())) visitBasicBlock(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002400 } while (!WorkList.empty());
Nick Lewyckycfff1c32006-09-20 17:04:01 +00002401
Nick Lewycky26e25d32007-06-24 04:36:20 +00002402 delete DTDFS;
Nick Lewyckyd9bd0bc2007-03-10 18:12:48 +00002403 delete VR;
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002404 delete IG;
2405
2406 modified |= UB.kill();
Nick Lewyckycfff1c32006-09-20 17:04:01 +00002407
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002408 return modified;
Nick Lewycky8e559932006-09-02 19:40:38 +00002409 }
2410
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002411 void PredicateSimplifier::Forwards::visitTerminatorInst(TerminatorInst &TI) {
Owen Anderson510fefc2007-04-25 04:18:54 +00002412 PS->proceedToSuccessors(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002413 }
2414
2415 void PredicateSimplifier::Forwards::visitBranchInst(BranchInst &BI) {
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002416 if (BI.isUnconditional()) {
Owen Anderson510fefc2007-04-25 04:18:54 +00002417 PS->proceedToSuccessors(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002418 return;
2419 }
2420
2421 Value *Condition = BI.getCondition();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002422 BasicBlock *TrueDest = BI.getSuccessor(0);
2423 BasicBlock *FalseDest = BI.getSuccessor(1);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002424
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002425 if (isa<Constant>(Condition) || TrueDest == FalseDest) {
Owen Anderson510fefc2007-04-25 04:18:54 +00002426 PS->proceedToSuccessors(DTNode);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002427 return;
2428 }
2429
Nick Lewycky26e25d32007-06-24 04:36:20 +00002430 for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
Owen Anderson510fefc2007-04-25 04:18:54 +00002431 I != E; ++I) {
2432 BasicBlock *Dest = (*I)->getBlock();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002433 DOUT << "Branch thinking about %" << Dest->getName()
Nick Lewycky26e25d32007-06-24 04:36:20 +00002434 << "(" << PS->DTDFS->getNodeForBlock(Dest)->getDFSNumIn() << ")\n";
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002435
2436 if (Dest == TrueDest) {
Owen Anderson510fefc2007-04-25 04:18:54 +00002437 DOUT << "(" << DTNode->getBlock()->getName() << ") true set:\n";
Nick Lewycky73dd6922007-07-05 03:15:00 +00002438 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002439 VRP.add(ConstantInt::getTrue(), Condition, ICmpInst::ICMP_EQ);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002440 VRP.solve();
Nick Lewyckye635cc42007-07-10 03:28:21 +00002441 DEBUG(VN.dump());
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002442 DEBUG(IG.dump());
Nick Lewyckye635cc42007-07-10 03:28:21 +00002443 DEBUG(VR.dump());
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002444 } else if (Dest == FalseDest) {
Owen Anderson510fefc2007-04-25 04:18:54 +00002445 DOUT << "(" << DTNode->getBlock()->getName() << ") false set:\n";
Nick Lewycky73dd6922007-07-05 03:15:00 +00002446 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
Zhou Sheng75b871f2007-01-11 12:24:14 +00002447 VRP.add(ConstantInt::getFalse(), Condition, ICmpInst::ICMP_EQ);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002448 VRP.solve();
Nick Lewyckye635cc42007-07-10 03:28:21 +00002449 DEBUG(VN.dump());
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002450 DEBUG(IG.dump());
Nick Lewyckye635cc42007-07-10 03:28:21 +00002451 DEBUG(VR.dump());
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002452 }
2453
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002454 PS->proceedToSuccessor(*I);
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002455 }
2456 }
2457
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002458 void PredicateSimplifier::Forwards::visitSwitchInst(SwitchInst &SI) {
2459 Value *Condition = SI.getCondition();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002460
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002461 // Set the EQProperty in each of the cases BBs, and the NEProperties
2462 // in the default BB.
Owen Anderson510fefc2007-04-25 04:18:54 +00002463
Nick Lewycky26e25d32007-06-24 04:36:20 +00002464 for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
Owen Anderson510fefc2007-04-25 04:18:54 +00002465 I != E; ++I) {
2466 BasicBlock *BB = (*I)->getBlock();
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002467 DOUT << "Switch thinking about BB %" << BB->getName()
Nick Lewycky26e25d32007-06-24 04:36:20 +00002468 << "(" << PS->DTDFS->getNodeForBlock(BB)->getDFSNumIn() << ")\n";
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002469
Nick Lewycky73dd6922007-07-05 03:15:00 +00002470 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, BB);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002471 if (BB == SI.getDefaultDest()) {
2472 for (unsigned i = 1, e = SI.getNumCases(); i < e; ++i)
2473 if (SI.getSuccessor(i) != BB)
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002474 VRP.add(Condition, SI.getCaseValue(i), ICmpInst::ICMP_NE);
2475 VRP.solve();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002476 } else if (ConstantInt *CI = SI.findCaseDest(BB)) {
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002477 VRP.add(Condition, CI, ICmpInst::ICMP_EQ);
2478 VRP.solve();
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002479 }
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002480 PS->proceedToSuccessor(*I);
Nick Lewycky1d00f3e2006-10-03 15:19:11 +00002481 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002482 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002483
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002484 void PredicateSimplifier::Forwards::visitAllocaInst(AllocaInst &AI) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002485 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &AI);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002486 VRP.add(Constant::getNullValue(AI.getType()), &AI, ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002487 VRP.solve();
2488 }
Nick Lewyckyf3450082006-10-22 19:53:27 +00002489
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002490 void PredicateSimplifier::Forwards::visitLoadInst(LoadInst &LI) {
2491 Value *Ptr = LI.getPointerOperand();
2492 // avoid "load uint* null" -> null NE null.
2493 if (isa<Constant>(Ptr)) return;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002494
Nick Lewycky73dd6922007-07-05 03:15:00 +00002495 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &LI);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002496 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002497 VRP.solve();
2498 }
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002499
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002500 void PredicateSimplifier::Forwards::visitStoreInst(StoreInst &SI) {
2501 Value *Ptr = SI.getPointerOperand();
2502 if (isa<Constant>(Ptr)) return;
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002503
Nick Lewycky73dd6922007-07-05 03:15:00 +00002504 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
Nick Lewycky2fc338f2007-01-11 02:32:38 +00002505 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002506 VRP.solve();
2507 }
2508
Nick Lewycky15245952007-02-04 23:43:05 +00002509 void PredicateSimplifier::Forwards::visitSExtInst(SExtInst &SI) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002510 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
Reid Spencerc34dedf2007-03-03 00:48:31 +00002511 uint32_t SrcBitWidth = cast<IntegerType>(SI.getSrcTy())->getBitWidth();
2512 uint32_t DstBitWidth = cast<IntegerType>(SI.getDestTy())->getBitWidth();
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00002513 APInt Min(APInt::getHighBitsSet(DstBitWidth, DstBitWidth-SrcBitWidth+1));
2514 APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth-1));
Reid Spencerc34dedf2007-03-03 00:48:31 +00002515 VRP.add(ConstantInt::get(Min), &SI, ICmpInst::ICMP_SLE);
2516 VRP.add(ConstantInt::get(Max), &SI, ICmpInst::ICMP_SGE);
Nick Lewycky15245952007-02-04 23:43:05 +00002517 VRP.solve();
2518 }
2519
2520 void PredicateSimplifier::Forwards::visitZExtInst(ZExtInst &ZI) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002521 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &ZI);
Reid Spencerc34dedf2007-03-03 00:48:31 +00002522 uint32_t SrcBitWidth = cast<IntegerType>(ZI.getSrcTy())->getBitWidth();
2523 uint32_t DstBitWidth = cast<IntegerType>(ZI.getDestTy())->getBitWidth();
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00002524 APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth));
Reid Spencerc34dedf2007-03-03 00:48:31 +00002525 VRP.add(ConstantInt::get(Max), &ZI, ICmpInst::ICMP_UGE);
Nick Lewycky15245952007-02-04 23:43:05 +00002526 VRP.solve();
2527 }
2528
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002529 void PredicateSimplifier::Forwards::visitBinaryOperator(BinaryOperator &BO) {
2530 Instruction::BinaryOps ops = BO.getOpcode();
2531
2532 switch (ops) {
Nick Lewycky4f73de22007-03-16 02:37:39 +00002533 default: break;
Nick Lewycky15245952007-02-04 23:43:05 +00002534 case Instruction::URem:
2535 case Instruction::SRem:
2536 case Instruction::UDiv:
2537 case Instruction::SDiv: {
2538 Value *Divisor = BO.getOperand(1);
Nick Lewycky73dd6922007-07-05 03:15:00 +00002539 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky15245952007-02-04 23:43:05 +00002540 VRP.add(Constant::getNullValue(Divisor->getType()), Divisor,
2541 ICmpInst::ICMP_NE);
2542 VRP.solve();
2543 break;
2544 }
Nick Lewycky4f73de22007-03-16 02:37:39 +00002545 }
2546
2547 switch (ops) {
2548 default: break;
2549 case Instruction::Shl: {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002550 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002551 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
2552 VRP.solve();
2553 } break;
2554 case Instruction::AShr: {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002555 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002556 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_SLE);
2557 VRP.solve();
2558 } break;
2559 case Instruction::LShr:
2560 case Instruction::UDiv: {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002561 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002562 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
2563 VRP.solve();
2564 } break;
2565 case Instruction::URem: {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002566 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002567 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
2568 VRP.solve();
2569 } break;
2570 case Instruction::And: {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002571 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002572 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
2573 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
2574 VRP.solve();
2575 } break;
2576 case Instruction::Or: {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002577 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002578 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
2579 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_UGE);
2580 VRP.solve();
2581 } break;
2582 }
2583 }
2584
2585 void PredicateSimplifier::Forwards::visitICmpInst(ICmpInst &IC) {
2586 // If possible, squeeze the ICmp predicate into something simpler.
2587 // Eg., if x = [0, 4) and we're being asked icmp uge %x, 3 then change
2588 // the predicate to eq.
2589
Nick Lewyckyeeb01b42007-04-07 02:30:14 +00002590 // XXX: once we do full PHI handling, modifying the instruction in the
2591 // Forwards visitor will cause missed optimizations.
2592
Nick Lewycky4f73de22007-03-16 02:37:39 +00002593 ICmpInst::Predicate Pred = IC.getPredicate();
2594
Nick Lewyckyeeb01b42007-04-07 02:30:14 +00002595 switch (Pred) {
2596 default: break;
2597 case ICmpInst::ICMP_ULE: Pred = ICmpInst::ICMP_ULT; break;
2598 case ICmpInst::ICMP_UGE: Pred = ICmpInst::ICMP_UGT; break;
2599 case ICmpInst::ICMP_SLE: Pred = ICmpInst::ICMP_SLT; break;
2600 case ICmpInst::ICMP_SGE: Pred = ICmpInst::ICMP_SGT; break;
2601 }
2602 if (Pred != IC.getPredicate()) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002603 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &IC);
Nick Lewyckyeeb01b42007-04-07 02:30:14 +00002604 if (VRP.isRelatedBy(IC.getOperand(1), IC.getOperand(0),
2605 ICmpInst::ICMP_NE)) {
2606 ++NumSnuggle;
2607 PS->modified = true;
2608 IC.setPredicate(Pred);
2609 }
2610 }
2611
2612 Pred = IC.getPredicate();
2613
Nick Lewycky4f73de22007-03-16 02:37:39 +00002614 if (ConstantInt *Op1 = dyn_cast<ConstantInt>(IC.getOperand(1))) {
2615 ConstantInt *NextVal = 0;
Nick Lewyckyeeb01b42007-04-07 02:30:14 +00002616 switch (Pred) {
Nick Lewycky4f73de22007-03-16 02:37:39 +00002617 default: break;
2618 case ICmpInst::ICMP_SLT:
2619 case ICmpInst::ICMP_ULT:
2620 if (Op1->getValue() != 0)
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00002621 NextVal = ConstantInt::get(Op1->getValue()-1);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002622 break;
2623 case ICmpInst::ICMP_SGT:
2624 case ICmpInst::ICMP_UGT:
2625 if (!Op1->getValue().isAllOnesValue())
Zhou Sheng82fcf3c2007-04-19 05:35:00 +00002626 NextVal = ConstantInt::get(Op1->getValue()+1);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002627 break;
2628
2629 }
2630 if (NextVal) {
Nick Lewycky73dd6922007-07-05 03:15:00 +00002631 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &IC);
Nick Lewycky4f73de22007-03-16 02:37:39 +00002632 if (VRP.isRelatedBy(IC.getOperand(0), NextVal,
2633 ICmpInst::getInversePredicate(Pred))) {
2634 ICmpInst *NewIC = new ICmpInst(ICmpInst::ICMP_EQ, IC.getOperand(0),
2635 NextVal, "", &IC);
2636 NewIC->takeName(&IC);
2637 IC.replaceAllUsesWith(NewIC);
Nick Lewycky73dd6922007-07-05 03:15:00 +00002638
2639 // XXX: prove this isn't necessary
2640 if (unsigned n = VN.valueNumber(&IC, PS->DTDFS->getRootNode()))
2641 if (VN.value(n) == &IC) IG.remove(n);
2642 VN.remove(&IC);
2643
Nick Lewycky4f73de22007-03-16 02:37:39 +00002644 IC.eraseFromParent();
2645 ++NumSnuggle;
2646 PS->modified = true;
Nick Lewycky4f73de22007-03-16 02:37:39 +00002647 }
2648 }
2649 }
Nick Lewycky5f8f9af2006-08-30 02:46:48 +00002650 }
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002651
Devang Patel8c78a0b2007-05-03 01:11:54 +00002652 char PredicateSimplifier::ID = 0;
Nick Lewycky09b7e4d2006-11-22 23:49:16 +00002653 RegisterPass<PredicateSimplifier> X("predsimplify",
2654 "Predicate Simplifier");
2655}
2656
2657FunctionPass *llvm::createPredicateSimplifierPass() {
2658 return new PredicateSimplifier();
Nick Lewyckyb2e8ae12006-08-28 22:44:55 +00002659}