blob: 3c648a887e329c6f524165f40acc27bbd4bff85c [file] [log] [blame]
Nick Lewycky565706b2006-11-22 23:49:16 +00001//===-- PredicateSimplifier.cpp - Path Sensitive Simplifier ---------------===//
Nick Lewycky05450ae2006-08-28 22:44:55 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Nick Lewycky05450ae2006-08-28 22:44:55 +00007//
Nick Lewycky565706b2006-11-22 23:49:16 +00008//===----------------------------------------------------------------------===//
Nick Lewycky05450ae2006-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 Lewycky565706b2006-11-22 23:49:16 +000023//===----------------------------------------------------------------------===//
Nick Lewycky05450ae2006-08-28 22:44:55 +000024//
Nick Lewycky4c708752007-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 Lewycky565706b2006-11-22 23:49:16 +000028// are stored in a lattice; LE can become LT or EQ, NE can become LT or GT.
Nick Lewycky05450ae2006-08-28 22:44:55 +000029//
Nick Lewycky565706b2006-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 Lewyckye677a0b2007-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 Lewycky565706b2006-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 Lewycky419c6f52007-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 Lewycky565706b2006-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 Lewyckye677a0b2007-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 Lewycky565706b2006-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 Lewycky6a08f912007-01-29 02:56:54 +000062// branch it can't infer anything from the "and" instruction.
Nick Lewycky565706b2006-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 Lewycky4c708752007-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 Lewycky7956dae2007-08-04 18:45:32 +000073// %b = [0, 254].
Nick Lewycky4c708752007-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 Lewyckyb01c77e2007-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 Lewycky4c708752007-03-16 02:37:39 +000079//
80//===----------------------------------------------------------------------===//
Nick Lewycky05450ae2006-08-28 22:44:55 +000081
Nick Lewycky05450ae2006-08-28 22:44:55 +000082#define DEBUG_TYPE "predsimplify"
83#include "llvm/Transforms/Scalar.h"
84#include "llvm/Constants.h"
Nick Lewycky802fe272006-10-22 19:53:27 +000085#include "llvm/DerivedTypes.h"
Nick Lewycky05450ae2006-08-28 22:44:55 +000086#include "llvm/Instructions.h"
87#include "llvm/Pass.h"
Nick Lewycky419c6f52007-01-11 02:32:38 +000088#include "llvm/ADT/DepthFirstIterator.h"
Nick Lewycky565706b2006-11-22 23:49:16 +000089#include "llvm/ADT/SetOperations.h"
Reid Spencer6734b572007-02-04 00:40:42 +000090#include "llvm/ADT/SetVector.h"
Nick Lewycky05450ae2006-08-28 22:44:55 +000091#include "llvm/ADT/Statistic.h"
92#include "llvm/ADT/STLExtras.h"
93#include "llvm/Analysis/Dominators.h"
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +000094#include "llvm/Assembly/Writer.h"
Nick Lewycky05450ae2006-08-28 22:44:55 +000095#include "llvm/Support/CFG.h"
Chris Lattner02fc40e2006-12-06 18:14:47 +000096#include "llvm/Support/Compiler.h"
Nick Lewyckye677a0b2007-03-10 18:12:48 +000097#include "llvm/Support/ConstantRange.h"
Nick Lewycky05450ae2006-08-28 22:44:55 +000098#include "llvm/Support/Debug.h"
Nick Lewycky078ff412006-10-12 02:02:44 +000099#include "llvm/Support/InstVisitor.h"
Nick Lewyckyb01c77e2007-04-07 03:16:12 +0000100#include "llvm/Target/TargetData.h"
Nick Lewycky565706b2006-11-22 23:49:16 +0000101#include "llvm/Transforms/Utils/Local.h"
102#include <algorithm>
103#include <deque>
Nick Lewycky984504b2007-06-24 04:36:20 +0000104#include <stack>
Nick Lewycky05450ae2006-08-28 22:44:55 +0000105using namespace llvm;
106
Chris Lattner438e08e2006-12-19 21:49:03 +0000107STATISTIC(NumVarsReplaced, "Number of argument substitutions");
108STATISTIC(NumInstruction , "Number of instructions removed");
109STATISTIC(NumSimple , "Number of simple replacements");
Nick Lewycky419c6f52007-01-11 02:32:38 +0000110STATISTIC(NumBlocks , "Number of blocks marked unreachable");
Nick Lewycky4c708752007-03-16 02:37:39 +0000111STATISTIC(NumSnuggle , "Number of comparisons snuggled");
Nick Lewycky05450ae2006-08-28 22:44:55 +0000112
Owen Andersonafe0a082009-06-26 21:39:56 +0000113static const ConstantRange empty(1, false);
114
Chris Lattner438e08e2006-12-19 21:49:03 +0000115namespace {
Nick Lewycky984504b2007-06-24 04:36:20 +0000116 class DomTreeDFS {
117 public:
118 class Node {
119 friend class DomTreeDFS;
120 public:
121 typedef std::vector<Node *>::iterator iterator;
122 typedef std::vector<Node *>::const_iterator const_iterator;
123
124 unsigned getDFSNumIn() const { return DFSin; }
125 unsigned getDFSNumOut() const { return DFSout; }
126
127 BasicBlock *getBlock() const { return BB; }
128
129 iterator begin() { return Children.begin(); }
130 iterator end() { return Children.end(); }
131
132 const_iterator begin() const { return Children.begin(); }
133 const_iterator end() const { return Children.end(); }
134
135 bool dominates(const Node *N) const {
136 return DFSin <= N->DFSin && DFSout >= N->DFSout;
137 }
138
139 bool DominatedBy(const Node *N) const {
140 return N->dominates(this);
141 }
142
143 /// Sorts by the number of descendants. With this, you can iterate
144 /// through a sorted list and the first matching entry is the most
145 /// specific match for your basic block. The order provided is stable;
146 /// DomTreeDFS::Nodes with the same number of descendants are sorted by
147 /// DFS in number.
148 bool operator<(const Node &N) const {
149 unsigned spread = DFSout - DFSin;
150 unsigned N_spread = N.DFSout - N.DFSin;
151 if (spread == N_spread) return DFSin < N.DFSin;
Nick Lewycky29a05b62007-07-05 03:15:00 +0000152 return spread < N_spread;
Nick Lewycky984504b2007-06-24 04:36:20 +0000153 }
154 bool operator>(const Node &N) const { return N < *this; }
155
156 private:
157 unsigned DFSin, DFSout;
158 BasicBlock *BB;
159
160 std::vector<Node *> Children;
161 };
162
163 // XXX: this may be slow. Instead of using "new" for each node, consider
164 // putting them in a vector to keep them contiguous.
165 explicit DomTreeDFS(DominatorTree *DT) {
166 std::stack<std::pair<Node *, DomTreeNode *> > S;
167
168 Entry = new Node;
169 Entry->BB = DT->getRootNode()->getBlock();
170 S.push(std::make_pair(Entry, DT->getRootNode()));
171
172 NodeMap[Entry->BB] = Entry;
173
174 while (!S.empty()) {
175 std::pair<Node *, DomTreeNode *> &Pair = S.top();
176 Node *N = Pair.first;
177 DomTreeNode *DTNode = Pair.second;
178 S.pop();
179
180 for (DomTreeNode::iterator I = DTNode->begin(), E = DTNode->end();
181 I != E; ++I) {
182 Node *NewNode = new Node;
183 NewNode->BB = (*I)->getBlock();
184 N->Children.push_back(NewNode);
185 S.push(std::make_pair(NewNode, *I));
186
187 NodeMap[NewNode->BB] = NewNode;
188 }
189 }
190
191 renumber();
192
193#ifndef NDEBUG
194 DEBUG(dump());
195#endif
196 }
197
198#ifndef NDEBUG
199 virtual
200#endif
201 ~DomTreeDFS() {
202 std::stack<Node *> S;
203
204 S.push(Entry);
205 while (!S.empty()) {
206 Node *N = S.top(); S.pop();
207
208 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I)
209 S.push(*I);
210
211 delete N;
212 }
213 }
214
Nick Lewycky5380e942007-07-16 02:58:37 +0000215 /// getRootNode - This returns the entry node for the CFG of the function.
Nick Lewycky984504b2007-06-24 04:36:20 +0000216 Node *getRootNode() const { return Entry; }
217
Nick Lewycky5380e942007-07-16 02:58:37 +0000218 /// getNodeForBlock - return the node for the specified basic block.
Nick Lewycky984504b2007-06-24 04:36:20 +0000219 Node *getNodeForBlock(BasicBlock *BB) const {
220 if (!NodeMap.count(BB)) return 0;
Nick Lewycky29a05b62007-07-05 03:15:00 +0000221 return const_cast<DomTreeDFS*>(this)->NodeMap[BB];
Nick Lewycky984504b2007-06-24 04:36:20 +0000222 }
223
Nick Lewycky5380e942007-07-16 02:58:37 +0000224 /// dominates - returns true if the basic block for I1 dominates that of
225 /// the basic block for I2. If the instructions belong to the same basic
226 /// block, the instruction first instruction sequentially in the block is
227 /// considered dominating.
Nick Lewycky984504b2007-06-24 04:36:20 +0000228 bool dominates(Instruction *I1, Instruction *I2) {
229 BasicBlock *BB1 = I1->getParent(),
230 *BB2 = I2->getParent();
231 if (BB1 == BB2) {
232 if (isa<TerminatorInst>(I1)) return false;
233 if (isa<TerminatorInst>(I2)) return true;
234 if ( isa<PHINode>(I1) && !isa<PHINode>(I2)) return true;
235 if (!isa<PHINode>(I1) && isa<PHINode>(I2)) return false;
236
237 for (BasicBlock::const_iterator I = BB2->begin(), E = BB2->end();
238 I != E; ++I) {
239 if (&*I == I1) return true;
240 else if (&*I == I2) return false;
241 }
242 assert(!"Instructions not found in parent BasicBlock?");
243 } else {
Nick Lewyckydea25262007-06-24 04:40:16 +0000244 Node *Node1 = getNodeForBlock(BB1),
Nick Lewycky984504b2007-06-24 04:36:20 +0000245 *Node2 = getNodeForBlock(BB2);
Nick Lewycky29a05b62007-07-05 03:15:00 +0000246 return Node1 && Node2 && Node1->dominates(Node2);
Nick Lewycky984504b2007-06-24 04:36:20 +0000247 }
Chris Lattnerd27c9912008-03-30 18:22:13 +0000248 return false; // Not reached
Nick Lewycky984504b2007-06-24 04:36:20 +0000249 }
Nick Lewycky5380e942007-07-16 02:58:37 +0000250
Nick Lewycky984504b2007-06-24 04:36:20 +0000251 private:
Nick Lewycky5380e942007-07-16 02:58:37 +0000252 /// renumber - calculates the depth first search numberings and applies
253 /// them onto the nodes.
Nick Lewycky984504b2007-06-24 04:36:20 +0000254 void renumber() {
255 std::stack<std::pair<Node *, Node::iterator> > S;
256 unsigned n = 0;
257
258 Entry->DFSin = ++n;
259 S.push(std::make_pair(Entry, Entry->begin()));
260
261 while (!S.empty()) {
262 std::pair<Node *, Node::iterator> &Pair = S.top();
263 Node *N = Pair.first;
264 Node::iterator &I = Pair.second;
265
266 if (I == N->end()) {
267 N->DFSout = ++n;
268 S.pop();
269 } else {
270 Node *Next = *I++;
271 Next->DFSin = ++n;
272 S.push(std::make_pair(Next, Next->begin()));
273 }
274 }
275 }
276
277#ifndef NDEBUG
278 virtual void dump() const {
279 dump(*cerr.stream());
280 }
281
282 void dump(std::ostream &os) const {
283 os << "Predicate simplifier DomTreeDFS: \n";
284 dump(Entry, 0, os);
285 os << "\n\n";
286 }
287
288 void dump(Node *N, int depth, std::ostream &os) const {
289 ++depth;
290 for (int i = 0; i < depth; ++i) { os << " "; }
291 os << "[" << depth << "] ";
292
293 os << N->getBlock()->getName() << " (" << N->getDFSNumIn()
294 << ", " << N->getDFSNumOut() << ")\n";
295
296 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I)
297 dump(*I, depth, os);
298 }
299#endif
300
301 Node *Entry;
302 std::map<BasicBlock *, Node *> NodeMap;
303 };
304
Nick Lewycky419c6f52007-01-11 02:32:38 +0000305 // SLT SGT ULT UGT EQ
306 // 0 1 0 1 0 -- GT 10
307 // 0 1 0 1 1 -- GE 11
308 // 0 1 1 0 0 -- SGTULT 12
309 // 0 1 1 0 1 -- SGEULE 13
Nick Lewycky6a08f912007-01-29 02:56:54 +0000310 // 0 1 1 1 0 -- SGT 14
311 // 0 1 1 1 1 -- SGE 15
Nick Lewycky419c6f52007-01-11 02:32:38 +0000312 // 1 0 0 1 0 -- SLTUGT 18
313 // 1 0 0 1 1 -- SLEUGE 19
314 // 1 0 1 0 0 -- LT 20
315 // 1 0 1 0 1 -- LE 21
Nick Lewycky6a08f912007-01-29 02:56:54 +0000316 // 1 0 1 1 0 -- SLT 22
317 // 1 0 1 1 1 -- SLE 23
318 // 1 1 0 1 0 -- UGT 26
319 // 1 1 0 1 1 -- UGE 27
320 // 1 1 1 0 0 -- ULT 28
321 // 1 1 1 0 1 -- ULE 29
Nick Lewycky419c6f52007-01-11 02:32:38 +0000322 // 1 1 1 1 0 -- NE 30
323 enum LatticeBits {
324 EQ_BIT = 1, UGT_BIT = 2, ULT_BIT = 4, SGT_BIT = 8, SLT_BIT = 16
325 };
326 enum LatticeVal {
327 GT = SGT_BIT | UGT_BIT,
328 GE = GT | EQ_BIT,
329 LT = SLT_BIT | ULT_BIT,
330 LE = LT | EQ_BIT,
331 NE = SLT_BIT | SGT_BIT | ULT_BIT | UGT_BIT,
332 SGTULT = SGT_BIT | ULT_BIT,
333 SGEULE = SGTULT | EQ_BIT,
334 SLTUGT = SLT_BIT | UGT_BIT,
335 SLEUGE = SLTUGT | EQ_BIT,
Nick Lewycky6a08f912007-01-29 02:56:54 +0000336 ULT = SLT_BIT | SGT_BIT | ULT_BIT,
337 UGT = SLT_BIT | SGT_BIT | UGT_BIT,
338 SLT = SLT_BIT | ULT_BIT | UGT_BIT,
339 SGT = SGT_BIT | ULT_BIT | UGT_BIT,
340 SLE = SLT | EQ_BIT,
341 SGE = SGT | EQ_BIT,
342 ULE = ULT | EQ_BIT,
343 UGE = UGT | EQ_BIT
Nick Lewycky419c6f52007-01-11 02:32:38 +0000344 };
345
Devang Patel59500c82008-11-21 20:00:59 +0000346#ifndef NDEBUG
Nick Lewycky7956dae2007-08-04 18:45:32 +0000347 /// validPredicate - determines whether a given value is actually a lattice
348 /// value. Only used in assertions or debugging.
Nick Lewycky419c6f52007-01-11 02:32:38 +0000349 static bool validPredicate(LatticeVal LV) {
350 switch (LV) {
Nick Lewycky45351752007-02-04 23:43:05 +0000351 case GT: case GE: case LT: case LE: case NE:
352 case SGTULT: case SGT: case SGEULE:
353 case SLTUGT: case SLT: case SLEUGE:
354 case ULT: case UGT:
355 case SLE: case SGE: case ULE: case UGE:
356 return true;
357 default:
358 return false;
Nick Lewycky419c6f52007-01-11 02:32:38 +0000359 }
360 }
Devang Patel59500c82008-11-21 20:00:59 +0000361#endif
Nick Lewycky419c6f52007-01-11 02:32:38 +0000362
363 /// reversePredicate - reverse the direction of the inequality
364 static LatticeVal reversePredicate(LatticeVal LV) {
365 unsigned reverse = LV ^ (SLT_BIT|SGT_BIT|ULT_BIT|UGT_BIT); //preserve EQ_BIT
Nick Lewycky4c708752007-03-16 02:37:39 +0000366
Nick Lewycky419c6f52007-01-11 02:32:38 +0000367 if ((reverse & (SLT_BIT|SGT_BIT)) == 0)
368 reverse |= (SLT_BIT|SGT_BIT);
369
370 if ((reverse & (ULT_BIT|UGT_BIT)) == 0)
371 reverse |= (ULT_BIT|UGT_BIT);
372
373 LatticeVal Rev = static_cast<LatticeVal>(reverse);
374 assert(validPredicate(Rev) && "Failed reversing predicate.");
375 return Rev;
376 }
377
Nick Lewycky29a05b62007-07-05 03:15:00 +0000378 /// ValueNumbering stores the scope-specific value numbers for a given Value.
379 class VISIBILITY_HIDDEN ValueNumbering {
Nick Lewycky7956dae2007-08-04 18:45:32 +0000380
381 /// VNPair is a tuple of {Value, index number, DomTreeDFS::Node}. It
382 /// includes the comparison operators necessary to allow you to store it
383 /// in a sorted vector.
Nick Lewycky29a05b62007-07-05 03:15:00 +0000384 class VISIBILITY_HIDDEN VNPair {
385 public:
386 Value *V;
387 unsigned index;
388 DomTreeDFS::Node *Subtree;
389
390 VNPair(Value *V, unsigned index, DomTreeDFS::Node *Subtree)
391 : V(V), index(index), Subtree(Subtree) {}
392
393 bool operator==(const VNPair &RHS) const {
394 return V == RHS.V && Subtree == RHS.Subtree;
395 }
396
397 bool operator<(const VNPair &RHS) const {
398 if (V != RHS.V) return V < RHS.V;
399 return *Subtree < *RHS.Subtree;
400 }
401
402 bool operator<(Value *RHS) const {
403 return V < RHS;
404 }
Nick Lewycky7956dae2007-08-04 18:45:32 +0000405
406 bool operator>(Value *RHS) const {
407 return V > RHS;
408 }
409
410 friend bool operator<(Value *RHS, const VNPair &pair) {
411 return pair.operator>(RHS);
412 }
Nick Lewycky29a05b62007-07-05 03:15:00 +0000413 };
414
415 typedef std::vector<VNPair> VNMapType;
416 VNMapType VNMap;
417
Nick Lewycky7956dae2007-08-04 18:45:32 +0000418 /// The canonical choice for value number at index.
Nick Lewycky29a05b62007-07-05 03:15:00 +0000419 std::vector<Value *> Values;
420
421 DomTreeDFS *DTDFS;
422
423 public:
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000424#ifndef NDEBUG
425 virtual ~ValueNumbering() {}
426 virtual void dump() {
427 dump(*cerr.stream());
428 }
429
430 void dump(std::ostream &os) {
431 for (unsigned i = 1; i <= Values.size(); ++i) {
432 os << i << " = ";
433 WriteAsOperand(os, Values[i-1]);
434 os << " {";
435 for (unsigned j = 0; j < VNMap.size(); ++j) {
436 if (VNMap[j].index == i) {
437 WriteAsOperand(os, VNMap[j].V);
438 os << " (" << VNMap[j].Subtree->getDFSNumIn() << ") ";
439 }
440 }
441 os << "}\n";
442 }
443 }
444#endif
445
Nick Lewycky29a05b62007-07-05 03:15:00 +0000446 /// compare - returns true if V1 is a better canonical value than V2.
447 bool compare(Value *V1, Value *V2) const {
448 if (isa<Constant>(V1))
449 return !isa<Constant>(V2);
450 else if (isa<Constant>(V2))
451 return false;
452 else if (isa<Argument>(V1))
453 return !isa<Argument>(V2);
454 else if (isa<Argument>(V2))
455 return false;
456
457 Instruction *I1 = dyn_cast<Instruction>(V1);
458 Instruction *I2 = dyn_cast<Instruction>(V2);
459
460 if (!I1 || !I2)
461 return V1->getNumUses() < V2->getNumUses();
462
463 return DTDFS->dominates(I1, I2);
464 }
465
466 ValueNumbering(DomTreeDFS *DTDFS) : DTDFS(DTDFS) {}
467
468 /// valueNumber - finds the value number for V under the Subtree. If
469 /// there is no value number, returns zero.
470 unsigned valueNumber(Value *V, DomTreeDFS::Node *Subtree) {
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000471 if (!(isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V))
472 || V->getType() == Type::VoidTy) return 0;
473
Nick Lewycky29a05b62007-07-05 03:15:00 +0000474 VNMapType::iterator E = VNMap.end();
475 VNPair pair(V, 0, Subtree);
476 VNMapType::iterator I = std::lower_bound(VNMap.begin(), E, pair);
477 while (I != E && I->V == V) {
478 if (I->Subtree->dominates(Subtree))
479 return I->index;
480 ++I;
481 }
482 return 0;
483 }
484
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000485 /// getOrInsertVN - always returns a value number, creating it if necessary.
486 unsigned getOrInsertVN(Value *V, DomTreeDFS::Node *Subtree) {
487 if (unsigned n = valueNumber(V, Subtree))
488 return n;
489 else
490 return newVN(V);
491 }
492
Nick Lewycky29a05b62007-07-05 03:15:00 +0000493 /// newVN - creates a new value number. Value V must not already have a
494 /// value number assigned.
495 unsigned newVN(Value *V) {
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000496 assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
497 "Bad Value for value numbering.");
498 assert(V->getType() != Type::VoidTy && "Won't value number a void value");
499
Nick Lewycky29a05b62007-07-05 03:15:00 +0000500 Values.push_back(V);
501
502 VNPair pair = VNPair(V, Values.size(), DTDFS->getRootNode());
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000503 VNMapType::iterator I = std::lower_bound(VNMap.begin(), VNMap.end(), pair);
504 assert((I == VNMap.end() || value(I->index) != V) &&
Nick Lewycky29a05b62007-07-05 03:15:00 +0000505 "Attempt to create a duplicate value number.");
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000506 VNMap.insert(I, pair);
Nick Lewycky29a05b62007-07-05 03:15:00 +0000507
508 return Values.size();
509 }
510
511 /// value - returns the Value associated with a value number.
512 Value *value(unsigned index) const {
513 assert(index != 0 && "Zero index is reserved for not found.");
514 assert(index <= Values.size() && "Index out of range.");
515 return Values[index-1];
516 }
517
518 /// canonicalize - return a Value that is equal to V under Subtree.
519 Value *canonicalize(Value *V, DomTreeDFS::Node *Subtree) {
520 if (isa<Constant>(V)) return V;
521
522 if (unsigned n = valueNumber(V, Subtree))
523 return value(n);
524 else
525 return V;
526 }
527
528 /// addEquality - adds that value V belongs to the set of equivalent
529 /// values defined by value number n under Subtree.
530 void addEquality(unsigned n, Value *V, DomTreeDFS::Node *Subtree) {
531 assert(canonicalize(value(n), Subtree) == value(n) &&
532 "Node's 'canonical' choice isn't best within this subtree.");
533
534 // Suppose that we are given "%x -> node #1 (%y)". The problem is that
535 // we may already have "%z -> node #2 (%x)" somewhere above us in the
536 // graph. We need to find those edges and add "%z -> node #1 (%y)"
537 // to keep the lookups canonical.
538
539 std::vector<Value *> ToRepoint(1, V);
540
541 if (unsigned Conflict = valueNumber(V, Subtree)) {
542 for (VNMapType::iterator I = VNMap.begin(), E = VNMap.end();
543 I != E; ++I) {
544 if (I->index == Conflict && I->Subtree->dominates(Subtree))
545 ToRepoint.push_back(I->V);
546 }
547 }
548
549 for (std::vector<Value *>::iterator VI = ToRepoint.begin(),
550 VE = ToRepoint.end(); VI != VE; ++VI) {
551 Value *V = *VI;
552
553 VNPair pair(V, n, Subtree);
554 VNMapType::iterator B = VNMap.begin(), E = VNMap.end();
555 VNMapType::iterator I = std::lower_bound(B, E, pair);
556 if (I != E && I->V == V && I->Subtree == Subtree)
557 I->index = n; // Update best choice
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000558 else
Nick Lewycky29a05b62007-07-05 03:15:00 +0000559 VNMap.insert(I, pair); // New Value
560
561 // XXX: we currently don't have to worry about updating values with
562 // more specific Subtrees, but we will need to for PHI node support.
563
564#ifndef NDEBUG
565 Value *V_n = value(n);
566 if (isa<Constant>(V) && isa<Constant>(V_n)) {
567 assert(V == V_n && "Constant equals different constant?");
568 }
569#endif
570 }
571 }
572
573 /// remove - removes all references to value V.
574 void remove(Value *V) {
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000575 VNMapType::iterator B = VNMap.begin(), E = VNMap.end();
Nick Lewycky29a05b62007-07-05 03:15:00 +0000576 VNPair pair(V, 0, DTDFS->getRootNode());
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000577 VNMapType::iterator J = std::upper_bound(B, E, pair);
Nick Lewycky29a05b62007-07-05 03:15:00 +0000578 VNMapType::iterator I = J;
579
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000580 while (I != B && (I == E || I->V == V)) --I;
Nick Lewycky29a05b62007-07-05 03:15:00 +0000581
582 VNMap.erase(I, J);
583 }
584 };
585
Nick Lewycky565706b2006-11-22 23:49:16 +0000586 /// The InequalityGraph stores the relationships between values.
587 /// Each Value in the graph is assigned to a Node. Nodes are pointer
588 /// comparable for equality. The caller is expected to maintain the logical
589 /// consistency of the system.
590 ///
591 /// The InequalityGraph class may invalidate Node*s after any mutator call.
592 /// @brief The InequalityGraph stores the relationships between values.
593 class VISIBILITY_HIDDEN InequalityGraph {
Nick Lewycky29a05b62007-07-05 03:15:00 +0000594 ValueNumbering &VN;
Nick Lewycky984504b2007-06-24 04:36:20 +0000595 DomTreeDFS::Node *TreeRoot;
Nick Lewycky419c6f52007-01-11 02:32:38 +0000596
597 InequalityGraph(); // DO NOT IMPLEMENT
598 InequalityGraph(InequalityGraph &); // DO NOT IMPLEMENT
Nick Lewycky565706b2006-11-22 23:49:16 +0000599 public:
Nick Lewycky29a05b62007-07-05 03:15:00 +0000600 InequalityGraph(ValueNumbering &VN, DomTreeDFS::Node *TreeRoot)
601 : VN(VN), TreeRoot(TreeRoot) {}
Nick Lewycky419c6f52007-01-11 02:32:38 +0000602
Nick Lewycky565706b2006-11-22 23:49:16 +0000603 class Node;
Nick Lewycky05450ae2006-08-28 22:44:55 +0000604
Nick Lewycky419c6f52007-01-11 02:32:38 +0000605 /// An Edge is contained inside a Node making one end of the edge implicit
606 /// and contains a pointer to the other end. The edge contains a lattice
Nick Lewycky984504b2007-06-24 04:36:20 +0000607 /// value specifying the relationship and an DomTreeDFS::Node specifying
608 /// the root in the dominator tree to which this edge applies.
Nick Lewycky419c6f52007-01-11 02:32:38 +0000609 class VISIBILITY_HIDDEN Edge {
610 public:
Nick Lewycky984504b2007-06-24 04:36:20 +0000611 Edge(unsigned T, LatticeVal V, DomTreeDFS::Node *ST)
Nick Lewycky419c6f52007-01-11 02:32:38 +0000612 : To(T), LV(V), Subtree(ST) {}
Nick Lewycky565706b2006-11-22 23:49:16 +0000613
Nick Lewycky419c6f52007-01-11 02:32:38 +0000614 unsigned To;
615 LatticeVal LV;
Nick Lewycky984504b2007-06-24 04:36:20 +0000616 DomTreeDFS::Node *Subtree;
Nick Lewycky565706b2006-11-22 23:49:16 +0000617
Nick Lewycky419c6f52007-01-11 02:32:38 +0000618 bool operator<(const Edge &edge) const {
619 if (To != edge.To) return To < edge.To;
Nick Lewycky29a05b62007-07-05 03:15:00 +0000620 return *Subtree < *edge.Subtree;
Nick Lewycky419c6f52007-01-11 02:32:38 +0000621 }
Nick Lewycky984504b2007-06-24 04:36:20 +0000622
Nick Lewycky419c6f52007-01-11 02:32:38 +0000623 bool operator<(unsigned to) const {
624 return To < to;
625 }
Nick Lewycky984504b2007-06-24 04:36:20 +0000626
Bill Wendling851879c2007-06-04 23:52:59 +0000627 bool operator>(unsigned to) const {
628 return To > to;
629 }
630
631 friend bool operator<(unsigned to, const Edge &edge) {
632 return edge.operator>(to);
633 }
Nick Lewycky419c6f52007-01-11 02:32:38 +0000634 };
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000635
Nick Lewycky565706b2006-11-22 23:49:16 +0000636 /// A single node in the InequalityGraph. This stores the canonical Value
637 /// for the node, as well as the relationships with the neighbours.
638 ///
Nick Lewycky565706b2006-11-22 23:49:16 +0000639 /// @brief A single node in the InequalityGraph.
640 class VISIBILITY_HIDDEN Node {
641 friend class InequalityGraph;
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000642
Nick Lewycky419c6f52007-01-11 02:32:38 +0000643 typedef SmallVector<Edge, 4> RelationsType;
644 RelationsType Relations;
645
Nick Lewycky419c6f52007-01-11 02:32:38 +0000646 // TODO: can this idea improve performance?
647 //friend class std::vector<Node>;
648 //Node(Node &N) { RelationsType.swap(N.RelationsType); }
649
Nick Lewycky565706b2006-11-22 23:49:16 +0000650 public:
651 typedef RelationsType::iterator iterator;
652 typedef RelationsType::const_iterator const_iterator;
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000653
Nick Lewycky419c6f52007-01-11 02:32:38 +0000654#ifndef NDEBUG
Nick Lewyckybc00fec2007-01-11 02:38:21 +0000655 virtual ~Node() {}
Nick Lewycky419c6f52007-01-11 02:32:38 +0000656 virtual void dump() const {
657 dump(*cerr.stream());
658 }
659 private:
Nick Lewycky29a05b62007-07-05 03:15:00 +0000660 void dump(std::ostream &os) const {
661 static const std::string names[32] =
662 { "000000", "000001", "000002", "000003", "000004", "000005",
663 "000006", "000007", "000008", "000009", " >", " >=",
664 " s>u<", "s>=u<=", " s>", " s>=", "000016", "000017",
665 " s<u>", "s<=u>=", " <", " <=", " s<", " s<=",
666 "000024", "000025", " u>", " u>=", " u<", " u<=",
667 " !=", "000031" };
Nick Lewycky419c6f52007-01-11 02:32:38 +0000668 for (Node::const_iterator NI = begin(), NE = end(); NI != NE; ++NI) {
Nick Lewycky29a05b62007-07-05 03:15:00 +0000669 os << names[NI->LV] << " " << NI->To
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000670 << " (" << NI->Subtree->getDFSNumIn() << "), ";
Nick Lewycky419c6f52007-01-11 02:32:38 +0000671 }
672 }
Nick Lewycky29a05b62007-07-05 03:15:00 +0000673 public:
Nick Lewycky419c6f52007-01-11 02:32:38 +0000674#endif
675
Nick Lewycky419c6f52007-01-11 02:32:38 +0000676 iterator begin() { return Relations.begin(); }
677 iterator end() { return Relations.end(); }
678 const_iterator begin() const { return Relations.begin(); }
679 const_iterator end() const { return Relations.end(); }
680
Nick Lewycky984504b2007-06-24 04:36:20 +0000681 iterator find(unsigned n, DomTreeDFS::Node *Subtree) {
Nick Lewycky419c6f52007-01-11 02:32:38 +0000682 iterator E = end();
683 for (iterator I = std::lower_bound(begin(), E, n);
684 I != E && I->To == n; ++I) {
685 if (Subtree->DominatedBy(I->Subtree))
686 return I;
687 }
688 return E;
689 }
690
Nick Lewycky984504b2007-06-24 04:36:20 +0000691 const_iterator find(unsigned n, DomTreeDFS::Node *Subtree) const {
Nick Lewycky419c6f52007-01-11 02:32:38 +0000692 const_iterator E = end();
693 for (const_iterator I = std::lower_bound(begin(), E, n);
694 I != E && I->To == n; ++I) {
695 if (Subtree->DominatedBy(I->Subtree))
696 return I;
697 }
698 return E;
699 }
700
Nick Lewycky7956dae2007-08-04 18:45:32 +0000701 /// update - updates the lattice value for a given node, creating a new
702 /// entry if one doesn't exist. The new lattice value must not be
703 /// inconsistent with any previously existing value.
Nick Lewycky984504b2007-06-24 04:36:20 +0000704 void update(unsigned n, LatticeVal R, DomTreeDFS::Node *Subtree) {
Nick Lewycky419c6f52007-01-11 02:32:38 +0000705 assert(validPredicate(R) && "Invalid predicate.");
Nick Lewycky419c6f52007-01-11 02:32:38 +0000706
Nick Lewycky7956dae2007-08-04 18:45:32 +0000707 Edge edge(n, R, Subtree);
708 iterator B = begin(), E = end();
709 iterator I = std::lower_bound(B, E, edge);
Nick Lewyckydd402582007-01-15 14:30:07 +0000710
Nick Lewycky7956dae2007-08-04 18:45:32 +0000711 iterator J = I;
712 while (J != E && J->To == n) {
713 if (Subtree->DominatedBy(J->Subtree))
714 break;
715 ++J;
716 }
717
Nick Lewyckyc7212232007-08-18 23:18:03 +0000718 if (J != E && J->To == n) {
Nick Lewycky7956dae2007-08-04 18:45:32 +0000719 edge.LV = static_cast<LatticeVal>(J->LV & R);
720 assert(validPredicate(edge.LV) && "Invalid union of lattice values.");
Nick Lewycky7956dae2007-08-04 18:45:32 +0000721
Nick Lewyckyc7212232007-08-18 23:18:03 +0000722 if (edge.LV == J->LV)
723 return; // This update adds nothing new.
Bill Wendling587c01d2008-02-26 10:53:30 +0000724 }
Nick Lewyckyc7212232007-08-18 23:18:03 +0000725
726 if (I != B) {
727 // We also have to tighten any edge beneath our update.
728 for (iterator K = I - 1; K->To == n; --K) {
729 if (K->Subtree->DominatedBy(Subtree)) {
730 LatticeVal LV = static_cast<LatticeVal>(K->LV & edge.LV);
731 assert(validPredicate(LV) && "Invalid union of lattice values");
732 K->LV = LV;
Nick Lewycky419c6f52007-01-11 02:32:38 +0000733 }
Nick Lewyckyc7212232007-08-18 23:18:03 +0000734 if (K == B) break;
Nick Lewycky419c6f52007-01-11 02:32:38 +0000735 }
Bill Wendling587c01d2008-02-26 10:53:30 +0000736 }
Nick Lewycky7956dae2007-08-04 18:45:32 +0000737
738 // Insert new edge at Subtree if it isn't already there.
739 if (I == E || I->To != n || Subtree != I->Subtree)
740 Relations.insert(I, edge);
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000741 }
Nick Lewycky565706b2006-11-22 23:49:16 +0000742 };
743
Nick Lewycky565706b2006-11-22 23:49:16 +0000744 private:
Nick Lewycky419c6f52007-01-11 02:32:38 +0000745
746 std::vector<Node> Nodes;
747
Nick Lewycky565706b2006-11-22 23:49:16 +0000748 public:
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000749 /// node - returns the node object at a given value number. The pointer
750 /// returned may be invalidated on the next call to node().
Nick Lewycky419c6f52007-01-11 02:32:38 +0000751 Node *node(unsigned index) {
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000752 assert(VN.value(index)); // This triggers the necessary checks.
753 if (Nodes.size() < index) Nodes.resize(index);
Nick Lewycky419c6f52007-01-11 02:32:38 +0000754 return &Nodes[index-1];
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000755 }
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000756
Nick Lewycky419c6f52007-01-11 02:32:38 +0000757 /// isRelatedBy - true iff n1 op n2
Nick Lewycky984504b2007-06-24 04:36:20 +0000758 bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
759 LatticeVal LV) {
Nick Lewycky419c6f52007-01-11 02:32:38 +0000760 if (n1 == n2) return LV & EQ_BIT;
761
762 Node *N1 = node(n1);
763 Node::iterator I = N1->find(n2, Subtree), E = N1->end();
764 if (I != E) return (I->LV & LV) == I->LV;
765
Nick Lewycky406fc0c2006-09-20 17:04:01 +0000766 return false;
767 }
768
Nick Lewycky565706b2006-11-22 23:49:16 +0000769 // The add* methods assume that your input is logically valid and may
770 // assertion-fail or infinitely loop if you attempt a contradiction.
Nick Lewyckye63bf952006-10-25 23:48:24 +0000771
Nick Lewycky419c6f52007-01-11 02:32:38 +0000772 /// addInequality - Sets n1 op n2.
773 /// It is also an error to call this on an inequality that is already true.
Nick Lewycky984504b2007-06-24 04:36:20 +0000774 void addInequality(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
Nick Lewycky419c6f52007-01-11 02:32:38 +0000775 LatticeVal LV1) {
776 assert(n1 != n2 && "A node can't be inequal to itself.");
777
778 if (LV1 != NE)
779 assert(!isRelatedBy(n1, n2, Subtree, reversePredicate(LV1)) &&
780 "Contradictory inequality.");
781
Nick Lewycky419c6f52007-01-11 02:32:38 +0000782 // Suppose we're adding %n1 < %n2. Find all the %a < %n1 and
783 // add %a < %n2 too. This keeps the graph fully connected.
784 if (LV1 != NE) {
Nick Lewyckyf3a9e362007-04-07 03:36:51 +0000785 // Break up the relationship into signed and unsigned comparison parts.
786 // If the signed parts of %a op1 %n1 match that of %n1 op2 %n2, and
787 // op1 and op2 aren't NE, then add %a op3 %n2. The new relationship
788 // should have the EQ_BIT iff it's set for both op1 and op2.
Nick Lewycky419c6f52007-01-11 02:32:38 +0000789
790 unsigned LV1_s = LV1 & (SLT_BIT|SGT_BIT);
791 unsigned LV1_u = LV1 & (ULT_BIT|UGT_BIT);
Nick Lewyckyf3a9e362007-04-07 03:36:51 +0000792
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000793 for (Node::iterator I = node(n1)->begin(), E = node(n1)->end(); I != E; ++I) {
Nick Lewycky419c6f52007-01-11 02:32:38 +0000794 if (I->LV != NE && I->To != n2) {
Nick Lewyckyf3a9e362007-04-07 03:36:51 +0000795
Nick Lewycky984504b2007-06-24 04:36:20 +0000796 DomTreeDFS::Node *Local_Subtree = NULL;
Nick Lewycky419c6f52007-01-11 02:32:38 +0000797 if (Subtree->DominatedBy(I->Subtree))
798 Local_Subtree = Subtree;
799 else if (I->Subtree->DominatedBy(Subtree))
800 Local_Subtree = I->Subtree;
801
802 if (Local_Subtree) {
803 unsigned new_relationship = 0;
804 LatticeVal ILV = reversePredicate(I->LV);
805 unsigned ILV_s = ILV & (SLT_BIT|SGT_BIT);
806 unsigned ILV_u = ILV & (ULT_BIT|UGT_BIT);
807
808 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
809 new_relationship |= ILV_s;
Nick Lewycky419c6f52007-01-11 02:32:38 +0000810 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
811 new_relationship |= ILV_u;
812
813 if (new_relationship) {
814 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
815 new_relationship |= (SLT_BIT|SGT_BIT);
816 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
817 new_relationship |= (ULT_BIT|UGT_BIT);
818 if ((LV1 & EQ_BIT) && (ILV & EQ_BIT))
819 new_relationship |= EQ_BIT;
820
821 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
822
823 node(I->To)->update(n2, NewLV, Local_Subtree);
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000824 node(n2)->update(I->To, reversePredicate(NewLV), Local_Subtree);
Nick Lewycky419c6f52007-01-11 02:32:38 +0000825 }
826 }
827 }
828 }
829
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000830 for (Node::iterator I = node(n2)->begin(), E = node(n2)->end(); I != E; ++I) {
Nick Lewycky419c6f52007-01-11 02:32:38 +0000831 if (I->LV != NE && I->To != n1) {
Nick Lewycky984504b2007-06-24 04:36:20 +0000832 DomTreeDFS::Node *Local_Subtree = NULL;
Nick Lewycky419c6f52007-01-11 02:32:38 +0000833 if (Subtree->DominatedBy(I->Subtree))
834 Local_Subtree = Subtree;
835 else if (I->Subtree->DominatedBy(Subtree))
836 Local_Subtree = I->Subtree;
837
838 if (Local_Subtree) {
839 unsigned new_relationship = 0;
840 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
841 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
842
843 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
844 new_relationship |= ILV_s;
845
846 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
847 new_relationship |= ILV_u;
848
849 if (new_relationship) {
850 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
851 new_relationship |= (SLT_BIT|SGT_BIT);
852 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
853 new_relationship |= (ULT_BIT|UGT_BIT);
854 if ((LV1 & EQ_BIT) && (I->LV & EQ_BIT))
855 new_relationship |= EQ_BIT;
856
857 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
858
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000859 node(n1)->update(I->To, NewLV, Local_Subtree);
Nick Lewycky419c6f52007-01-11 02:32:38 +0000860 node(I->To)->update(n1, reversePredicate(NewLV), Local_Subtree);
861 }
862 }
863 }
864 }
865 }
866
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000867 node(n1)->update(n2, LV1, Subtree);
868 node(n2)->update(n1, reversePredicate(LV1), Subtree);
Nick Lewycky419c6f52007-01-11 02:32:38 +0000869 }
Nick Lewycky977be252006-09-13 19:24:01 +0000870
Nick Lewycky29a05b62007-07-05 03:15:00 +0000871 /// remove - removes a node from the graph by removing all references to
872 /// and from it.
873 void remove(unsigned n) {
874 Node *N = node(n);
875 for (Node::iterator NI = N->begin(), NE = N->end(); NI != NE; ++NI) {
876 Node::iterator Iter = node(NI->To)->find(n, TreeRoot);
877 do {
878 node(NI->To)->Relations.erase(Iter);
879 Iter = node(NI->To)->find(n, TreeRoot);
880 } while (Iter != node(NI->To)->end());
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000881 }
Nick Lewycky29a05b62007-07-05 03:15:00 +0000882 N->Relations.clear();
Nick Lewycky565706b2006-11-22 23:49:16 +0000883 }
Nick Lewycky05450ae2006-08-28 22:44:55 +0000884
Nick Lewycky565706b2006-11-22 23:49:16 +0000885#ifndef NDEBUG
Nick Lewyckybc00fec2007-01-11 02:38:21 +0000886 virtual ~InequalityGraph() {}
Nick Lewycky419c6f52007-01-11 02:32:38 +0000887 virtual void dump() {
888 dump(*cerr.stream());
889 }
890
891 void dump(std::ostream &os) {
Nick Lewycky29a05b62007-07-05 03:15:00 +0000892 for (unsigned i = 1; i <= Nodes.size(); ++i) {
893 os << i << " = {";
894 node(i)->dump(os);
895 os << "}\n";
Nick Lewycky565706b2006-11-22 23:49:16 +0000896 }
897 }
Nick Lewycky565706b2006-11-22 23:49:16 +0000898#endif
899 };
Nick Lewycky05450ae2006-08-28 22:44:55 +0000900
Nick Lewyckye677a0b2007-03-10 18:12:48 +0000901 class VRPSolver;
902
903 /// ValueRanges tracks the known integer ranges and anti-ranges of the nodes
904 /// in the InequalityGraph.
905 class VISIBILITY_HIDDEN ValueRanges {
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000906 ValueNumbering &VN;
907 TargetData *TD;
Owen Anderson001dbfe2009-07-16 18:04:31 +0000908 LLVMContext *Context;
Nick Lewyckye677a0b2007-03-10 18:12:48 +0000909
Nick Lewyckye677a0b2007-03-10 18:12:48 +0000910 class VISIBILITY_HIDDEN ScopedRange {
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000911 typedef std::vector<std::pair<DomTreeDFS::Node *, ConstantRange> >
912 RangeListType;
913 RangeListType RangeList;
914
915 static bool swo(const std::pair<DomTreeDFS::Node *, ConstantRange> &LHS,
916 const std::pair<DomTreeDFS::Node *, ConstantRange> &RHS) {
917 return *LHS.first < *RHS.first;
918 }
919
Nick Lewyckye677a0b2007-03-10 18:12:48 +0000920 public:
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000921#ifndef NDEBUG
922 virtual ~ScopedRange() {}
923 virtual void dump() const {
924 dump(*cerr.stream());
Nick Lewyckye677a0b2007-03-10 18:12:48 +0000925 }
926
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000927 void dump(std::ostream &os) const {
928 os << "{";
929 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Chris Lattner944fac72008-08-23 22:23:09 +0000930 os << &I->second << " (" << I->first->getDFSNumIn() << "), ";
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000931 }
932 os << "}";
933 }
934#endif
935
936 typedef RangeListType::iterator iterator;
937 typedef RangeListType::const_iterator const_iterator;
938
939 iterator begin() { return RangeList.begin(); }
940 iterator end() { return RangeList.end(); }
941 const_iterator begin() const { return RangeList.begin(); }
942 const_iterator end() const { return RangeList.end(); }
943
944 iterator find(DomTreeDFS::Node *Subtree) {
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000945 iterator E = end();
946 iterator I = std::lower_bound(begin(), E,
947 std::make_pair(Subtree, empty), swo);
948
949 while (I != E && !I->first->dominates(Subtree)) ++I;
950 return I;
Nick Lewyckye677a0b2007-03-10 18:12:48 +0000951 }
Bill Wendling851879c2007-06-04 23:52:59 +0000952
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000953 const_iterator find(DomTreeDFS::Node *Subtree) const {
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000954 const_iterator E = end();
955 const_iterator I = std::lower_bound(begin(), E,
956 std::make_pair(Subtree, empty), swo);
957
958 while (I != E && !I->first->dominates(Subtree)) ++I;
959 return I;
Bill Wendling851879c2007-06-04 23:52:59 +0000960 }
961
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000962 void update(const ConstantRange &CR, DomTreeDFS::Node *Subtree) {
963 assert(!CR.isEmptySet() && "Empty ConstantRange.");
Nick Lewycky7956dae2007-08-04 18:45:32 +0000964 assert(!CR.isSingleElement() && "Refusing to store single element.");
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000965
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000966 iterator E = end();
967 iterator I =
968 std::lower_bound(begin(), E, std::make_pair(Subtree, empty), swo);
969
970 if (I != end() && I->first == Subtree) {
Nick Lewycky3a4a8842009-07-18 06:34:42 +0000971 ConstantRange CR2 = I->second.intersectWith(CR);
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000972 assert(!CR2.isEmptySet() && !CR2.isSingleElement() &&
973 "Invalid union of ranges.");
974 I->second = CR2;
975 } else
976 RangeList.insert(I, std::make_pair(Subtree, CR));
Bill Wendling851879c2007-06-04 23:52:59 +0000977 }
Nick Lewyckye677a0b2007-03-10 18:12:48 +0000978 };
979
980 std::vector<ScopedRange> Ranges;
Nick Lewyckye677a0b2007-03-10 18:12:48 +0000981
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000982 void update(unsigned n, const ConstantRange &CR, DomTreeDFS::Node *Subtree){
Nick Lewyckye677a0b2007-03-10 18:12:48 +0000983 if (CR.isFullSet()) return;
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000984 if (Ranges.size() < n) Ranges.resize(n);
985 Ranges[n-1].update(CR, Subtree);
Nick Lewyckye677a0b2007-03-10 18:12:48 +0000986 }
987
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000988 /// create - Creates a ConstantRange that matches the given LatticeVal
989 /// relation with a given integer.
990 ConstantRange create(LatticeVal LV, const ConstantRange &CR) {
991 assert(!CR.isEmptySet() && "Can't deal with empty set.");
992
993 if (LV == NE)
Nick Lewyckybf8c7f02009-07-11 06:15:39 +0000994 return ConstantRange::makeICmpRegion(ICmpInst::ICMP_NE, CR);
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +0000995
996 unsigned LV_s = LV & (SGT_BIT|SLT_BIT);
997 unsigned LV_u = LV & (UGT_BIT|ULT_BIT);
998 bool hasEQ = LV & EQ_BIT;
999
1000 ConstantRange Range(CR.getBitWidth());
1001
1002 if (LV_s == SGT_BIT) {
Nick Lewycky3a4a8842009-07-18 06:34:42 +00001003 Range = Range.intersectWith(ConstantRange::makeICmpRegion(
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001004 hasEQ ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_SGT, CR));
1005 } else if (LV_s == SLT_BIT) {
Nick Lewycky3a4a8842009-07-18 06:34:42 +00001006 Range = Range.intersectWith(ConstantRange::makeICmpRegion(
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001007 hasEQ ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_SLT, CR));
1008 }
1009
1010 if (LV_u == UGT_BIT) {
Nick Lewycky3a4a8842009-07-18 06:34:42 +00001011 Range = Range.intersectWith(ConstantRange::makeICmpRegion(
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001012 hasEQ ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_UGT, CR));
1013 } else if (LV_u == ULT_BIT) {
Nick Lewycky3a4a8842009-07-18 06:34:42 +00001014 Range = Range.intersectWith(ConstantRange::makeICmpRegion(
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001015 hasEQ ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT, CR));
1016 }
1017
1018 return Range;
1019 }
1020
Nick Lewyckyac4d6642007-04-07 15:48:32 +00001021#ifndef NDEBUG
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001022 bool isCanonical(Value *V, DomTreeDFS::Node *Subtree) {
1023 return V == VN.canonicalize(V, Subtree);
1024 }
Nick Lewyckyac4d6642007-04-07 15:48:32 +00001025#endif
1026
1027 public:
1028
Owen Anderson001dbfe2009-07-16 18:04:31 +00001029 ValueRanges(ValueNumbering &VN, TargetData *TD, LLVMContext *C) :
1030 VN(VN), TD(TD), Context(C) {}
Nick Lewyckyac4d6642007-04-07 15:48:32 +00001031
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001032#ifndef NDEBUG
1033 virtual ~ValueRanges() {}
1034
1035 virtual void dump() const {
1036 dump(*cerr.stream());
1037 }
1038
1039 void dump(std::ostream &os) const {
1040 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1041 os << (i+1) << " = ";
1042 Ranges[i].dump(os);
1043 os << "\n";
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001044 }
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001045 }
1046#endif
1047
1048 /// range - looks up the ConstantRange associated with a value number.
1049 ConstantRange range(unsigned n, DomTreeDFS::Node *Subtree) {
1050 assert(VN.value(n)); // performs range checks
1051
1052 if (n <= Ranges.size()) {
1053 ScopedRange::iterator I = Ranges[n-1].find(Subtree);
1054 if (I != Ranges[n-1].end()) return I->second;
1055 }
1056
1057 Value *V = VN.value(n);
1058 ConstantRange CR = range(V);
1059 return CR;
1060 }
1061
1062 /// range - determine a range from a Value without performing any lookups.
1063 ConstantRange range(Value *V) const {
1064 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
1065 return ConstantRange(C->getValue());
1066 else if (isa<ConstantPointerNull>(V))
1067 return ConstantRange(APInt::getNullValue(typeToWidth(V->getType())));
1068 else
Dan Gohmanb5660dc2008-02-20 16:44:09 +00001069 return ConstantRange(typeToWidth(V->getType()));
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001070 }
1071
Nick Lewyckyb01c77e2007-04-07 03:16:12 +00001072 // typeToWidth - returns the number of bits necessary to store a value of
1073 // this type, or zero if unknown.
1074 uint32_t typeToWidth(const Type *Ty) const {
1075 if (TD)
1076 return TD->getTypeSizeInBits(Ty);
Duncan Sands514ab342007-11-01 20:53:16 +00001077 else
1078 return Ty->getPrimitiveSizeInBits();
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001079 }
1080
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001081 static bool isRelatedBy(const ConstantRange &CR1, const ConstantRange &CR2,
1082 LatticeVal LV) {
Nick Lewycky4c708752007-03-16 02:37:39 +00001083 switch (LV) {
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001084 default: assert(!"Impossible lattice value!");
1085 case NE:
Nick Lewycky3a4a8842009-07-18 06:34:42 +00001086 return CR1.intersectWith(CR2).isEmptySet();
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001087 case ULT:
1088 return CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
1089 case ULE:
1090 return CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
1091 case UGT:
1092 return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
1093 case UGE:
1094 return CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
1095 case SLT:
1096 return CR1.getSignedMax().slt(CR2.getSignedMin());
1097 case SLE:
1098 return CR1.getSignedMax().sle(CR2.getSignedMin());
1099 case SGT:
1100 return CR1.getSignedMin().sgt(CR2.getSignedMax());
1101 case SGE:
1102 return CR1.getSignedMin().sge(CR2.getSignedMax());
1103 case LT:
1104 return CR1.getUnsignedMax().ult(CR2.getUnsignedMin()) &&
1105 CR1.getSignedMax().slt(CR2.getUnsignedMin());
1106 case LE:
1107 return CR1.getUnsignedMax().ule(CR2.getUnsignedMin()) &&
1108 CR1.getSignedMax().sle(CR2.getUnsignedMin());
1109 case GT:
1110 return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax()) &&
1111 CR1.getSignedMin().sgt(CR2.getSignedMax());
1112 case GE:
1113 return CR1.getUnsignedMin().uge(CR2.getUnsignedMax()) &&
1114 CR1.getSignedMin().sge(CR2.getSignedMax());
1115 case SLTUGT:
1116 return CR1.getSignedMax().slt(CR2.getSignedMin()) &&
1117 CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
1118 case SLEUGE:
1119 return CR1.getSignedMax().sle(CR2.getSignedMin()) &&
1120 CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
1121 case SGTULT:
1122 return CR1.getSignedMin().sgt(CR2.getSignedMax()) &&
1123 CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
1124 case SGEULE:
1125 return CR1.getSignedMin().sge(CR2.getSignedMax()) &&
1126 CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
1127 }
1128 }
1129
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001130 bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
1131 LatticeVal LV) {
1132 ConstantRange CR1 = range(n1, Subtree);
1133 ConstantRange CR2 = range(n2, Subtree);
1134
1135 // True iff all values in CR1 are LV to all values in CR2.
1136 return isRelatedBy(CR1, CR2, LV);
1137 }
1138
Nick Lewyckyf3a9e362007-04-07 03:36:51 +00001139 void addToWorklist(Value *V, Constant *C, ICmpInst::Predicate Pred,
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001140 VRPSolver *VRP);
Nick Lewyckyac4d6642007-04-07 15:48:32 +00001141 void markBlock(VRPSolver *VRP);
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001142
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001143 void mergeInto(Value **I, unsigned n, unsigned New,
Nick Lewycky984504b2007-06-24 04:36:20 +00001144 DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001145 ConstantRange CR_New = range(New, Subtree);
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001146 ConstantRange Merged = CR_New;
1147
1148 for (; n != 0; ++I, --n) {
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001149 unsigned i = VN.valueNumber(*I, Subtree);
1150 ConstantRange CR_Kill = i ? range(i, Subtree) : range(*I);
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001151 if (CR_Kill.isFullSet()) continue;
Nick Lewycky3a4a8842009-07-18 06:34:42 +00001152 Merged = Merged.intersectWith(CR_Kill);
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001153 }
1154
1155 if (Merged.isFullSet() || Merged == CR_New) return;
1156
Nick Lewyckyf3a9e362007-04-07 03:36:51 +00001157 applyRange(New, Merged, Subtree, VRP);
1158 }
1159
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001160 void applyRange(unsigned n, const ConstantRange &CR,
Nick Lewycky984504b2007-06-24 04:36:20 +00001161 DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
Nick Lewycky3a4a8842009-07-18 06:34:42 +00001162 ConstantRange Merged = CR.intersectWith(range(n, Subtree));
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001163 if (Merged.isEmptySet()) {
1164 markBlock(VRP);
1165 return;
1166 }
Nick Lewyckyf3a9e362007-04-07 03:36:51 +00001167
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001168 if (const APInt *I = Merged.getSingleElement()) {
1169 Value *V = VN.value(n); // XXX: redesign worklist.
Nick Lewyckyf3a9e362007-04-07 03:36:51 +00001170 const Type *Ty = V->getType();
1171 if (Ty->isInteger()) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001172 addToWorklist(V, ConstantInt::get(*Context, *I),
1173 ICmpInst::ICMP_EQ, VRP);
Nick Lewyckyf3a9e362007-04-07 03:36:51 +00001174 return;
1175 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1176 assert(*I == 0 && "Pointer is null but not zero?");
1177 addToWorklist(V, ConstantPointerNull::get(PTy),
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001178 ICmpInst::ICMP_EQ, VRP);
Nick Lewyckyf3a9e362007-04-07 03:36:51 +00001179 return;
1180 }
1181 }
1182
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001183 update(n, Merged, Subtree);
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001184 }
1185
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001186 void addNotEquals(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
Nick Lewycky984504b2007-06-24 04:36:20 +00001187 VRPSolver *VRP) {
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001188 ConstantRange CR1 = range(n1, Subtree);
1189 ConstantRange CR2 = range(n2, Subtree);
Nick Lewyckya995d922007-04-07 04:49:12 +00001190
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001191 uint32_t W = CR1.getBitWidth();
Nick Lewyckya995d922007-04-07 04:49:12 +00001192
1193 if (const APInt *I = CR1.getSingleElement()) {
1194 if (CR2.isFullSet()) {
1195 ConstantRange NewCR2(CR1.getUpper(), CR1.getLower());
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001196 applyRange(n2, NewCR2, Subtree, VRP);
Nick Lewyckya995d922007-04-07 04:49:12 +00001197 } else if (*I == CR2.getLower()) {
Zhou Sheng223d65b2007-04-19 05:35:00 +00001198 APInt NewLower(CR2.getLower() + 1),
1199 NewUpper(CR2.getUpper());
Nick Lewyckya995d922007-04-07 04:49:12 +00001200 if (NewLower == NewUpper)
1201 NewLower = NewUpper = APInt::getMinValue(W);
1202
1203 ConstantRange NewCR2(NewLower, NewUpper);
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001204 applyRange(n2, NewCR2, Subtree, VRP);
Nick Lewyckya995d922007-04-07 04:49:12 +00001205 } else if (*I == CR2.getUpper() - 1) {
Zhou Sheng223d65b2007-04-19 05:35:00 +00001206 APInt NewLower(CR2.getLower()),
1207 NewUpper(CR2.getUpper() - 1);
Nick Lewyckya995d922007-04-07 04:49:12 +00001208 if (NewLower == NewUpper)
1209 NewLower = NewUpper = APInt::getMinValue(W);
1210
1211 ConstantRange NewCR2(NewLower, NewUpper);
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001212 applyRange(n2, NewCR2, Subtree, VRP);
Nick Lewyckya995d922007-04-07 04:49:12 +00001213 }
1214 }
1215
1216 if (const APInt *I = CR2.getSingleElement()) {
1217 if (CR1.isFullSet()) {
1218 ConstantRange NewCR1(CR2.getUpper(), CR2.getLower());
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001219 applyRange(n1, NewCR1, Subtree, VRP);
Nick Lewyckya995d922007-04-07 04:49:12 +00001220 } else if (*I == CR1.getLower()) {
Zhou Sheng223d65b2007-04-19 05:35:00 +00001221 APInt NewLower(CR1.getLower() + 1),
1222 NewUpper(CR1.getUpper());
Nick Lewyckya995d922007-04-07 04:49:12 +00001223 if (NewLower == NewUpper)
1224 NewLower = NewUpper = APInt::getMinValue(W);
1225
1226 ConstantRange NewCR1(NewLower, NewUpper);
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001227 applyRange(n1, NewCR1, Subtree, VRP);
Nick Lewyckya995d922007-04-07 04:49:12 +00001228 } else if (*I == CR1.getUpper() - 1) {
Zhou Sheng223d65b2007-04-19 05:35:00 +00001229 APInt NewLower(CR1.getLower()),
1230 NewUpper(CR1.getUpper() - 1);
Nick Lewyckya995d922007-04-07 04:49:12 +00001231 if (NewLower == NewUpper)
1232 NewLower = NewUpper = APInt::getMinValue(W);
1233
1234 ConstantRange NewCR1(NewLower, NewUpper);
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001235 applyRange(n1, NewCR1, Subtree, VRP);
Nick Lewyckya995d922007-04-07 04:49:12 +00001236 }
1237 }
1238 }
1239
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001240 void addInequality(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
Nick Lewycky984504b2007-06-24 04:36:20 +00001241 LatticeVal LV, VRPSolver *VRP) {
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001242 assert(!isRelatedBy(n1, n2, Subtree, LV) && "Asked to do useless work.");
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001243
Nick Lewyckya995d922007-04-07 04:49:12 +00001244 if (LV == NE) {
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001245 addNotEquals(n1, n2, Subtree, VRP);
Nick Lewyckya995d922007-04-07 04:49:12 +00001246 return;
1247 }
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001248
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001249 ConstantRange CR1 = range(n1, Subtree);
1250 ConstantRange CR2 = range(n2, Subtree);
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001251
1252 if (!CR1.isSingleElement()) {
Nick Lewycky3a4a8842009-07-18 06:34:42 +00001253 ConstantRange NewCR1 = CR1.intersectWith(create(LV, CR2));
Nick Lewyckyf3a9e362007-04-07 03:36:51 +00001254 if (NewCR1 != CR1)
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001255 applyRange(n1, NewCR1, Subtree, VRP);
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001256 }
1257
1258 if (!CR2.isSingleElement()) {
Nick Lewycky3a4a8842009-07-18 06:34:42 +00001259 ConstantRange NewCR2 = CR2.intersectWith(
Nick Lewyckya73d11e2007-07-14 04:28:04 +00001260 create(reversePredicate(LV), CR1));
Nick Lewyckyf3a9e362007-04-07 03:36:51 +00001261 if (NewCR2 != CR2)
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001262 applyRange(n2, NewCR2, Subtree, VRP);
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001263 }
1264 }
1265 };
1266
Nick Lewycky419c6f52007-01-11 02:32:38 +00001267 /// UnreachableBlocks keeps tracks of blocks that are for one reason or
1268 /// another discovered to be unreachable. This is used to cull the graph when
1269 /// analyzing instructions, and to mark blocks with the "unreachable"
1270 /// terminator instruction after the function has executed.
1271 class VISIBILITY_HIDDEN UnreachableBlocks {
1272 private:
1273 std::vector<BasicBlock *> DeadBlocks;
Nick Lewycky565706b2006-11-22 23:49:16 +00001274
Nick Lewycky419c6f52007-01-11 02:32:38 +00001275 public:
1276 /// mark - mark a block as dead
1277 void mark(BasicBlock *BB) {
1278 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
1279 std::vector<BasicBlock *>::iterator I =
1280 std::lower_bound(DeadBlocks.begin(), E, BB);
1281
1282 if (I == E || *I != BB) DeadBlocks.insert(I, BB);
Nick Lewycky565706b2006-11-22 23:49:16 +00001283 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00001284
1285 /// isDead - returns whether a block is known to be dead already
1286 bool isDead(BasicBlock *BB) {
1287 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
1288 std::vector<BasicBlock *>::iterator I =
1289 std::lower_bound(DeadBlocks.begin(), E, BB);
1290
1291 return I != E && *I == BB;
Nick Lewycky565706b2006-11-22 23:49:16 +00001292 }
Nick Lewycky565706b2006-11-22 23:49:16 +00001293
Nick Lewycky419c6f52007-01-11 02:32:38 +00001294 /// kill - replace the dead blocks' terminator with an UnreachableInst.
1295 bool kill() {
1296 bool modified = false;
1297 for (std::vector<BasicBlock *>::iterator I = DeadBlocks.begin(),
1298 E = DeadBlocks.end(); I != E; ++I) {
1299 BasicBlock *BB = *I;
Nick Lewycky565706b2006-11-22 23:49:16 +00001300
Nick Lewycky419c6f52007-01-11 02:32:38 +00001301 DOUT << "unreachable block: " << BB->getName() << "\n";
Nick Lewycky565706b2006-11-22 23:49:16 +00001302
Nick Lewycky419c6f52007-01-11 02:32:38 +00001303 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
1304 SI != SE; ++SI) {
1305 BasicBlock *Succ = *SI;
1306 Succ->removePredecessor(BB);
Nick Lewyckye63bf952006-10-25 23:48:24 +00001307 }
Nick Lewycky565706b2006-11-22 23:49:16 +00001308
Nick Lewycky419c6f52007-01-11 02:32:38 +00001309 TerminatorInst *TI = BB->getTerminator();
1310 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1311 TI->eraseFromParent();
1312 new UnreachableInst(BB);
1313 ++NumBlocks;
1314 modified = true;
Nick Lewycky565706b2006-11-22 23:49:16 +00001315 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00001316 DeadBlocks.clear();
1317 return modified;
Nick Lewyckye63bf952006-10-25 23:48:24 +00001318 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00001319 };
Nick Lewycky565706b2006-11-22 23:49:16 +00001320
1321 /// VRPSolver keeps track of how changes to one variable affect other
1322 /// variables, and forwards changes along to the InequalityGraph. It
1323 /// also maintains the correct choice for "canonical" in the IG.
1324 /// @brief VRPSolver calculates inferences from a new relationship.
1325 class VISIBILITY_HIDDEN VRPSolver {
1326 private:
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001327 friend class ValueRanges;
1328
Nick Lewycky419c6f52007-01-11 02:32:38 +00001329 struct Operation {
1330 Value *LHS, *RHS;
1331 ICmpInst::Predicate Op;
1332
Nick Lewycky984504b2007-06-24 04:36:20 +00001333 BasicBlock *ContextBB; // XXX use a DomTreeDFS::Node instead
Nick Lewycky0be7f472007-01-13 02:05:28 +00001334 Instruction *ContextInst;
Nick Lewycky419c6f52007-01-11 02:32:38 +00001335 };
1336 std::deque<Operation> WorkList;
Nick Lewycky565706b2006-11-22 23:49:16 +00001337
Nick Lewycky29a05b62007-07-05 03:15:00 +00001338 ValueNumbering &VN;
Nick Lewycky565706b2006-11-22 23:49:16 +00001339 InequalityGraph &IG;
Nick Lewycky419c6f52007-01-11 02:32:38 +00001340 UnreachableBlocks &UB;
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001341 ValueRanges &VR;
Nick Lewycky984504b2007-06-24 04:36:20 +00001342 DomTreeDFS *DTDFS;
1343 DomTreeDFS::Node *Top;
Nick Lewycky419c6f52007-01-11 02:32:38 +00001344 BasicBlock *TopBB;
1345 Instruction *TopInst;
1346 bool &modified;
Owen Anderson0a5372e2009-07-13 04:09:18 +00001347 LLVMContext *Context;
Nick Lewycky565706b2006-11-22 23:49:16 +00001348
1349 typedef InequalityGraph::Node Node;
1350
Nick Lewycky419c6f52007-01-11 02:32:38 +00001351 // below - true if the Instruction is dominated by the current context
1352 // block or instruction
1353 bool below(Instruction *I) {
Nick Lewycky984504b2007-06-24 04:36:20 +00001354 BasicBlock *BB = I->getParent();
1355 if (TopInst && TopInst->getParent() == BB) {
1356 if (isa<TerminatorInst>(TopInst)) return false;
1357 if (isa<TerminatorInst>(I)) return true;
1358 if ( isa<PHINode>(TopInst) && !isa<PHINode>(I)) return true;
1359 if (!isa<PHINode>(TopInst) && isa<PHINode>(I)) return false;
1360
1361 for (BasicBlock::const_iterator Iter = BB->begin(), E = BB->end();
1362 Iter != E; ++Iter) {
1363 if (&*Iter == TopInst) return true;
1364 else if (&*Iter == I) return false;
1365 }
1366 assert(!"Instructions not found in parent BasicBlock?");
1367 } else {
Nick Lewyckydea25262007-06-24 04:40:16 +00001368 DomTreeDFS::Node *Node = DTDFS->getNodeForBlock(BB);
Nick Lewycky984504b2007-06-24 04:36:20 +00001369 if (!Node) return false;
1370 return Top->dominates(Node);
Nick Lewycky419c6f52007-01-11 02:32:38 +00001371 }
Chris Lattnerd27c9912008-03-30 18:22:13 +00001372 return false; // Not reached
Nick Lewycky565706b2006-11-22 23:49:16 +00001373 }
1374
Nick Lewycky984504b2007-06-24 04:36:20 +00001375 // aboveOrBelow - true if the Instruction either dominates or is dominated
1376 // by the current context block or instruction
1377 bool aboveOrBelow(Instruction *I) {
1378 BasicBlock *BB = I->getParent();
1379 DomTreeDFS::Node *Node = DTDFS->getNodeForBlock(BB);
1380 if (!Node) return false;
1381
1382 return Top == Node || Top->dominates(Node) || Node->dominates(Top);
1383 }
1384
Nick Lewycky419c6f52007-01-11 02:32:38 +00001385 bool makeEqual(Value *V1, Value *V2) {
1386 DOUT << "makeEqual(" << *V1 << ", " << *V2 << ")\n";
Nick Lewycky984504b2007-06-24 04:36:20 +00001387 DOUT << "context is ";
1388 if (TopInst) DOUT << "I: " << *TopInst << "\n";
1389 else DOUT << "BB: " << TopBB->getName()
1390 << "(" << Top->getDFSNumIn() << ")\n";
Nick Lewyckye63bf952006-10-25 23:48:24 +00001391
Nick Lewyckyb01c77e2007-04-07 03:16:12 +00001392 assert(V1->getType() == V2->getType() &&
1393 "Can't make two values with different types equal.");
1394
Nick Lewycky419c6f52007-01-11 02:32:38 +00001395 if (V1 == V2) return true;
Nick Lewyckye63bf952006-10-25 23:48:24 +00001396
Nick Lewycky419c6f52007-01-11 02:32:38 +00001397 if (isa<Constant>(V1) && isa<Constant>(V2))
1398 return false;
1399
Nick Lewycky29a05b62007-07-05 03:15:00 +00001400 unsigned n1 = VN.valueNumber(V1, Top), n2 = VN.valueNumber(V2, Top);
Nick Lewycky419c6f52007-01-11 02:32:38 +00001401
1402 if (n1 && n2) {
1403 if (n1 == n2) return true;
1404 if (IG.isRelatedBy(n1, n2, Top, NE)) return false;
1405 }
1406
Nick Lewycky29a05b62007-07-05 03:15:00 +00001407 if (n1) assert(V1 == VN.value(n1) && "Value isn't canonical.");
1408 if (n2) assert(V2 == VN.value(n2) && "Value isn't canonical.");
Nick Lewycky419c6f52007-01-11 02:32:38 +00001409
Nick Lewycky29a05b62007-07-05 03:15:00 +00001410 assert(!VN.compare(V2, V1) && "Please order parameters to makeEqual.");
Nick Lewycky419c6f52007-01-11 02:32:38 +00001411
1412 assert(!isa<Constant>(V2) && "Tried to remove a constant.");
1413
1414 SetVector<unsigned> Remove;
1415 if (n2) Remove.insert(n2);
1416
1417 if (n1 && n2) {
1418 // Suppose we're being told that %x == %y, and %x <= %z and %y >= %z.
1419 // We can't just merge %x and %y because the relationship with %z would
1420 // be EQ and that's invalid. What we're doing is looking for any nodes
1421 // %z such that %x <= %z and %y >= %z, and vice versa.
Nick Lewycky419c6f52007-01-11 02:32:38 +00001422
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001423 Node::iterator end = IG.node(n2)->end();
Nick Lewyckydd402582007-01-15 14:30:07 +00001424
1425 // Find the intersection between N1 and N2 which is dominated by
1426 // Top. If we find %x where N1 <= %x <= N2 (or >=) then add %x to
1427 // Remove.
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001428 for (Node::iterator I = IG.node(n1)->begin(), E = IG.node(n1)->end();
1429 I != E; ++I) {
Nick Lewyckydd402582007-01-15 14:30:07 +00001430 if (!(I->LV & EQ_BIT) || !Top->DominatedBy(I->Subtree)) continue;
1431
1432 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
1433 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001434 Node::iterator NI = IG.node(n2)->find(I->To, Top);
Nick Lewyckydd402582007-01-15 14:30:07 +00001435 if (NI != end) {
1436 LatticeVal NILV = reversePredicate(NI->LV);
1437 unsigned NILV_s = NILV & (SLT_BIT|SGT_BIT);
1438 unsigned NILV_u = NILV & (ULT_BIT|UGT_BIT);
1439
1440 if ((ILV_s != (SLT_BIT|SGT_BIT) && ILV_s == NILV_s) ||
1441 (ILV_u != (ULT_BIT|UGT_BIT) && ILV_u == NILV_u))
1442 Remove.insert(I->To);
Nick Lewycky419c6f52007-01-11 02:32:38 +00001443 }
1444 }
1445
1446 // See if one of the nodes about to be removed is actually a better
1447 // canonical choice than n1.
1448 unsigned orig_n1 = n1;
Reid Spencer7af9a132007-01-17 02:23:37 +00001449 SetVector<unsigned>::iterator DontRemove = Remove.end();
1450 for (SetVector<unsigned>::iterator I = Remove.begin()+1 /* skip n2 */,
Nick Lewycky419c6f52007-01-11 02:32:38 +00001451 E = Remove.end(); I != E; ++I) {
1452 unsigned n = *I;
Nick Lewycky29a05b62007-07-05 03:15:00 +00001453 Value *V = VN.value(n);
1454 if (VN.compare(V, V1)) {
Nick Lewycky419c6f52007-01-11 02:32:38 +00001455 V1 = V;
1456 n1 = n;
1457 DontRemove = I;
1458 }
1459 }
1460 if (DontRemove != Remove.end()) {
1461 unsigned n = *DontRemove;
1462 Remove.remove(n);
1463 Remove.insert(orig_n1);
Nick Lewycky565706b2006-11-22 23:49:16 +00001464 }
1465 }
Nick Lewyckye63bf952006-10-25 23:48:24 +00001466
Nick Lewycky419c6f52007-01-11 02:32:38 +00001467 // We'd like to allow makeEqual on two values to perform a simple
Nick Lewycky70ef6292008-05-26 22:49:36 +00001468 // substitution without creating nodes in the IG whenever possible.
Nick Lewycky419c6f52007-01-11 02:32:38 +00001469 //
1470 // The first iteration through this loop operates on V2 before going
1471 // through the Remove list and operating on those too. If all of the
1472 // iterations performed simple replacements then we exit early.
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001473 bool mergeIGNode = false;
Nick Lewycky419c6f52007-01-11 02:32:38 +00001474 unsigned i = 0;
1475 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
Nick Lewycky29a05b62007-07-05 03:15:00 +00001476 if (i) R = VN.value(Remove[i]); // skip n2.
Nick Lewycky419c6f52007-01-11 02:32:38 +00001477
1478 // Try to replace the whole instruction. If we can, we're done.
1479 Instruction *I2 = dyn_cast<Instruction>(R);
1480 if (I2 && below(I2)) {
1481 std::vector<Instruction *> ToNotify;
Jay Foad0906b1b2009-06-06 17:49:35 +00001482 for (Value::use_iterator UI = I2->use_begin(), UE = I2->use_end();
Nick Lewycky419c6f52007-01-11 02:32:38 +00001483 UI != UE;) {
1484 Use &TheUse = UI.getUse();
1485 ++UI;
Jay Foad0906b1b2009-06-06 17:49:35 +00001486 Instruction *I = cast<Instruction>(TheUse.getUser());
1487 ToNotify.push_back(I);
Nick Lewycky419c6f52007-01-11 02:32:38 +00001488 }
1489
1490 DOUT << "Simply removing " << *I2
1491 << ", replacing with " << *V1 << "\n";
1492 I2->replaceAllUsesWith(V1);
1493 // leave it dead; it'll get erased later.
1494 ++NumInstruction;
1495 modified = true;
1496
1497 for (std::vector<Instruction *>::iterator II = ToNotify.begin(),
1498 IE = ToNotify.end(); II != IE; ++II) {
1499 opsToDef(*II);
1500 }
1501
1502 continue;
1503 }
1504
1505 // Otherwise, replace all dominated uses.
1506 for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
1507 UI != UE;) {
1508 Use &TheUse = UI.getUse();
1509 ++UI;
1510 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
1511 if (below(I)) {
1512 TheUse.set(V1);
1513 modified = true;
1514 ++NumVarsReplaced;
1515 opsToDef(I);
1516 }
1517 }
1518 }
1519
1520 // If that killed the instruction, stop here.
1521 if (I2 && isInstructionTriviallyDead(I2)) {
1522 DOUT << "Killed all uses of " << *I2
1523 << ", replacing with " << *V1 << "\n";
1524 continue;
1525 }
1526
1527 // If we make it to here, then we will need to create a node for N1.
1528 // Otherwise, we can skip out early!
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001529 mergeIGNode = true;
Nick Lewycky419c6f52007-01-11 02:32:38 +00001530 }
1531
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001532 if (!isa<Constant>(V1)) {
1533 if (Remove.empty()) {
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001534 VR.mergeInto(&V2, 1, VN.getOrInsertVN(V1, Top), Top, this);
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001535 } else {
1536 std::vector<Value*> RemoveVals;
1537 RemoveVals.reserve(Remove.size());
Nick Lewycky419c6f52007-01-11 02:32:38 +00001538
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001539 for (SetVector<unsigned>::iterator I = Remove.begin(),
1540 E = Remove.end(); I != E; ++I) {
Nick Lewycky29a05b62007-07-05 03:15:00 +00001541 Value *V = VN.value(*I);
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001542 if (!V->use_empty())
1543 RemoveVals.push_back(V);
1544 }
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001545 VR.mergeInto(&RemoveVals[0], RemoveVals.size(),
1546 VN.getOrInsertVN(V1, Top), Top, this);
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001547 }
1548 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00001549
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001550 if (mergeIGNode) {
1551 // Create N1.
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001552 if (!n1) n1 = VN.getOrInsertVN(V1, Top);
Nick Lewycky6918a912008-05-27 00:59:05 +00001553 IG.node(n1); // Ensure that IG.Nodes won't get resized
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001554
1555 // Migrate relationships from removed nodes to N1.
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001556 for (SetVector<unsigned>::iterator I = Remove.begin(), E = Remove.end();
1557 I != E; ++I) {
1558 unsigned n = *I;
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001559 for (Node::iterator NI = IG.node(n)->begin(), NE = IG.node(n)->end();
1560 NI != NE; ++NI) {
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001561 if (NI->Subtree->DominatedBy(Top)) {
1562 if (NI->To == n1) {
1563 assert((NI->LV & EQ_BIT) && "Node inequal to itself.");
1564 continue;
1565 }
1566 if (Remove.count(NI->To))
1567 continue;
1568
1569 IG.node(NI->To)->update(n1, reversePredicate(NI->LV), Top);
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001570 IG.node(n1)->update(NI->To, NI->LV, Top);
Nick Lewycky419c6f52007-01-11 02:32:38 +00001571 }
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001572 }
1573 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00001574
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001575 // Point V2 (and all items in Remove) to N1.
1576 if (!n2)
Nick Lewycky29a05b62007-07-05 03:15:00 +00001577 VN.addEquality(n1, V2, Top);
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001578 else {
1579 for (SetVector<unsigned>::iterator I = Remove.begin(),
1580 E = Remove.end(); I != E; ++I) {
Nick Lewycky29a05b62007-07-05 03:15:00 +00001581 VN.addEquality(n1, VN.value(*I), Top);
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001582 }
1583 }
1584
1585 // If !Remove.empty() then V2 = Remove[0]->getValue().
1586 // Even when Remove is empty, we still want to process V2.
1587 i = 0;
1588 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
Nick Lewycky29a05b62007-07-05 03:15:00 +00001589 if (i) R = VN.value(Remove[i]); // skip n2.
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001590
1591 if (Instruction *I2 = dyn_cast<Instruction>(R)) {
Nick Lewycky984504b2007-06-24 04:36:20 +00001592 if (aboveOrBelow(I2))
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001593 defToOps(I2);
1594 }
1595 for (Value::use_iterator UI = V2->use_begin(), UE = V2->use_end();
1596 UI != UE;) {
1597 Use &TheUse = UI.getUse();
1598 ++UI;
1599 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
Nick Lewycky984504b2007-06-24 04:36:20 +00001600 if (aboveOrBelow(I))
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001601 opsToDef(I);
1602 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00001603 }
Nick Lewycky565706b2006-11-22 23:49:16 +00001604 }
1605 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00001606
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001607 // re-opsToDef all dominated users of V1.
1608 if (Instruction *I = dyn_cast<Instruction>(V1)) {
1609 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
Nick Lewycky419c6f52007-01-11 02:32:38 +00001610 UI != UE;) {
1611 Use &TheUse = UI.getUse();
1612 ++UI;
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001613 Value *V = TheUse.getUser();
1614 if (!V->use_empty()) {
Jay Foad0906b1b2009-06-06 17:49:35 +00001615 Instruction *Inst = cast<Instruction>(V);
1616 if (aboveOrBelow(Inst))
1617 opsToDef(Inst);
Nick Lewycky419c6f52007-01-11 02:32:38 +00001618 }
1619 }
1620 }
1621
1622 return true;
1623 }
1624
1625 /// cmpInstToLattice - converts an CmpInst::Predicate to lattice value
1626 /// Requires that the lattice value be valid; does not accept ICMP_EQ.
1627 static LatticeVal cmpInstToLattice(ICmpInst::Predicate Pred) {
1628 switch (Pred) {
1629 case ICmpInst::ICMP_EQ:
1630 assert(!"No matching lattice value.");
1631 return static_cast<LatticeVal>(EQ_BIT);
1632 default:
1633 assert(!"Invalid 'icmp' predicate.");
1634 case ICmpInst::ICMP_NE:
1635 return NE;
1636 case ICmpInst::ICMP_UGT:
Nick Lewycky6a08f912007-01-29 02:56:54 +00001637 return UGT;
Nick Lewycky419c6f52007-01-11 02:32:38 +00001638 case ICmpInst::ICMP_UGE:
Nick Lewycky6a08f912007-01-29 02:56:54 +00001639 return UGE;
Nick Lewycky419c6f52007-01-11 02:32:38 +00001640 case ICmpInst::ICMP_ULT:
Nick Lewycky6a08f912007-01-29 02:56:54 +00001641 return ULT;
Nick Lewycky419c6f52007-01-11 02:32:38 +00001642 case ICmpInst::ICMP_ULE:
Nick Lewycky6a08f912007-01-29 02:56:54 +00001643 return ULE;
Nick Lewycky419c6f52007-01-11 02:32:38 +00001644 case ICmpInst::ICMP_SGT:
Nick Lewycky6a08f912007-01-29 02:56:54 +00001645 return SGT;
Nick Lewycky419c6f52007-01-11 02:32:38 +00001646 case ICmpInst::ICMP_SGE:
Nick Lewycky6a08f912007-01-29 02:56:54 +00001647 return SGE;
Nick Lewycky419c6f52007-01-11 02:32:38 +00001648 case ICmpInst::ICMP_SLT:
Nick Lewycky6a08f912007-01-29 02:56:54 +00001649 return SLT;
Nick Lewycky419c6f52007-01-11 02:32:38 +00001650 case ICmpInst::ICMP_SLE:
Nick Lewycky6a08f912007-01-29 02:56:54 +00001651 return SLE;
Nick Lewycky419c6f52007-01-11 02:32:38 +00001652 }
Nick Lewycky565706b2006-11-22 23:49:16 +00001653 }
Nick Lewyckye63bf952006-10-25 23:48:24 +00001654
Nick Lewycky565706b2006-11-22 23:49:16 +00001655 public:
Nick Lewycky29a05b62007-07-05 03:15:00 +00001656 VRPSolver(ValueNumbering &VN, InequalityGraph &IG, UnreachableBlocks &UB,
1657 ValueRanges &VR, DomTreeDFS *DTDFS, bool &modified,
1658 BasicBlock *TopBB)
1659 : VN(VN),
1660 IG(IG),
Nick Lewycky419c6f52007-01-11 02:32:38 +00001661 UB(UB),
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001662 VR(VR),
Nick Lewycky984504b2007-06-24 04:36:20 +00001663 DTDFS(DTDFS),
1664 Top(DTDFS->getNodeForBlock(TopBB)),
Nick Lewycky419c6f52007-01-11 02:32:38 +00001665 TopBB(TopBB),
1666 TopInst(NULL),
Owen Anderson0a5372e2009-07-13 04:09:18 +00001667 modified(modified),
Owen Andersone922c022009-07-22 00:24:57 +00001668 Context(&TopBB->getContext())
Nick Lewycky984504b2007-06-24 04:36:20 +00001669 {
1670 assert(Top && "VRPSolver created for unreachable basic block.");
1671 }
Nick Lewyckye63bf952006-10-25 23:48:24 +00001672
Nick Lewycky29a05b62007-07-05 03:15:00 +00001673 VRPSolver(ValueNumbering &VN, InequalityGraph &IG, UnreachableBlocks &UB,
1674 ValueRanges &VR, DomTreeDFS *DTDFS, bool &modified,
1675 Instruction *TopInst)
1676 : VN(VN),
1677 IG(IG),
Nick Lewycky419c6f52007-01-11 02:32:38 +00001678 UB(UB),
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001679 VR(VR),
Nick Lewycky984504b2007-06-24 04:36:20 +00001680 DTDFS(DTDFS),
1681 Top(DTDFS->getNodeForBlock(TopInst->getParent())),
1682 TopBB(TopInst->getParent()),
Nick Lewycky419c6f52007-01-11 02:32:38 +00001683 TopInst(TopInst),
Owen Anderson001dbfe2009-07-16 18:04:31 +00001684 modified(modified),
Owen Andersone922c022009-07-22 00:24:57 +00001685 Context(&TopInst->getContext())
Nick Lewycky419c6f52007-01-11 02:32:38 +00001686 {
Nick Lewycky984504b2007-06-24 04:36:20 +00001687 assert(Top && "VRPSolver created for unreachable basic block.");
1688 assert(Top->getBlock() == TopInst->getParent() && "Context mismatch.");
Nick Lewycky419c6f52007-01-11 02:32:38 +00001689 }
1690
1691 bool isRelatedBy(Value *V1, Value *V2, ICmpInst::Predicate Pred) const {
1692 if (Constant *C1 = dyn_cast<Constant>(V1))
1693 if (Constant *C2 = dyn_cast<Constant>(V2))
Owen Andersonf53c3712009-07-21 02:47:59 +00001694 return Context->getConstantExprCompare(Pred, C1, C2) ==
Owen Andersonb3056fa2009-07-21 18:03:38 +00001695 Context->getTrue();
Nick Lewycky419c6f52007-01-11 02:32:38 +00001696
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001697 unsigned n1 = VN.valueNumber(V1, Top);
1698 unsigned n2 = VN.valueNumber(V2, Top);
Nick Lewycky419c6f52007-01-11 02:32:38 +00001699
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001700 if (n1 && n2) {
1701 if (n1 == n2) return Pred == ICmpInst::ICMP_EQ ||
1702 Pred == ICmpInst::ICMP_ULE ||
1703 Pred == ICmpInst::ICMP_UGE ||
1704 Pred == ICmpInst::ICMP_SLE ||
1705 Pred == ICmpInst::ICMP_SGE;
1706 if (Pred == ICmpInst::ICMP_EQ) return false;
1707 if (IG.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
1708 if (VR.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
1709 }
1710
1711 if ((n1 && !n2 && isa<Constant>(V2)) ||
1712 (n2 && !n1 && isa<Constant>(V1))) {
1713 ConstantRange CR1 = n1 ? VR.range(n1, Top) : VR.range(V1);
1714 ConstantRange CR2 = n2 ? VR.range(n2, Top) : VR.range(V2);
1715
1716 if (Pred == ICmpInst::ICMP_EQ)
1717 return CR1.isSingleElement() &&
1718 CR1.getSingleElement() == CR2.getSingleElement();
1719
1720 return VR.isRelatedBy(CR1, CR2, cmpInstToLattice(Pred));
1721 }
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001722 if (Pred == ICmpInst::ICMP_EQ) return V1 == V2;
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001723 return false;
Nick Lewycky565706b2006-11-22 23:49:16 +00001724 }
1725
Nick Lewycky419c6f52007-01-11 02:32:38 +00001726 /// add - adds a new property to the work queue
1727 void add(Value *V1, Value *V2, ICmpInst::Predicate Pred,
1728 Instruction *I = NULL) {
1729 DOUT << "adding " << *V1 << " " << Pred << " " << *V2;
1730 if (I) DOUT << " context: " << *I;
Nick Lewycky984504b2007-06-24 04:36:20 +00001731 else DOUT << " default context (" << Top->getDFSNumIn() << ")";
Nick Lewycky419c6f52007-01-11 02:32:38 +00001732 DOUT << "\n";
1733
Nick Lewyckyb01c77e2007-04-07 03:16:12 +00001734 assert(V1->getType() == V2->getType() &&
1735 "Can't relate two values with different types.");
1736
Nick Lewycky419c6f52007-01-11 02:32:38 +00001737 WorkList.push_back(Operation());
1738 Operation &O = WorkList.back();
Nick Lewycky0be7f472007-01-13 02:05:28 +00001739 O.LHS = V1, O.RHS = V2, O.Op = Pred, O.ContextInst = I;
1740 O.ContextBB = I ? I->getParent() : TopBB;
Nick Lewycky565706b2006-11-22 23:49:16 +00001741 }
1742
Nick Lewycky419c6f52007-01-11 02:32:38 +00001743 /// defToOps - Given an instruction definition that we've learned something
1744 /// new about, find any new relationships between its operands.
1745 void defToOps(Instruction *I) {
1746 Instruction *NewContext = below(I) ? I : TopInst;
Nick Lewycky29a05b62007-07-05 03:15:00 +00001747 Value *Canonical = VN.canonicalize(I, Top);
Nick Lewycky565706b2006-11-22 23:49:16 +00001748
Nick Lewycky419c6f52007-01-11 02:32:38 +00001749 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1750 const Type *Ty = BO->getType();
1751 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
Nick Lewycky565706b2006-11-22 23:49:16 +00001752
Nick Lewycky29a05b62007-07-05 03:15:00 +00001753 Value *Op0 = VN.canonicalize(BO->getOperand(0), Top);
1754 Value *Op1 = VN.canonicalize(BO->getOperand(1), Top);
Nick Lewycky565706b2006-11-22 23:49:16 +00001755
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001756 // TODO: "and i32 -1, %x" EQ %y then %x EQ %y.
Nick Lewycky565706b2006-11-22 23:49:16 +00001757
Nick Lewycky419c6f52007-01-11 02:32:38 +00001758 switch (BO->getOpcode()) {
1759 case Instruction::And: {
Nick Lewycky4c708752007-03-16 02:37:39 +00001760 // "and i32 %a, %b" EQ -1 then %a EQ -1 and %b EQ -1
Owen Anderson73c6b712009-07-13 20:58:05 +00001761 ConstantInt *CI = cast<ConstantInt>(Context->getAllOnesValue(Ty));
Nick Lewycky419c6f52007-01-11 02:32:38 +00001762 if (Canonical == CI) {
1763 add(CI, Op0, ICmpInst::ICMP_EQ, NewContext);
1764 add(CI, Op1, ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky565706b2006-11-22 23:49:16 +00001765 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00001766 } break;
1767 case Instruction::Or: {
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001768 // "or i32 %a, %b" EQ 0 then %a EQ 0 and %b EQ 0
Owen Anderson0a5372e2009-07-13 04:09:18 +00001769 Constant *Zero = Context->getNullValue(Ty);
Nick Lewycky419c6f52007-01-11 02:32:38 +00001770 if (Canonical == Zero) {
1771 add(Zero, Op0, ICmpInst::ICMP_EQ, NewContext);
1772 add(Zero, Op1, ICmpInst::ICMP_EQ, NewContext);
1773 }
1774 } break;
1775 case Instruction::Xor: {
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001776 // "xor i32 %c, %a" EQ %b then %a EQ %c ^ %b
1777 // "xor i32 %c, %a" EQ %c then %a EQ 0
1778 // "xor i32 %c, %a" NE %c then %a NE 0
1779 // Repeat the above, with order of operands reversed.
Nick Lewycky419c6f52007-01-11 02:32:38 +00001780 Value *LHS = Op0;
1781 Value *RHS = Op1;
1782 if (!isa<Constant>(LHS)) std::swap(LHS, RHS);
1783
Nick Lewyckyc2a7d092007-01-12 00:02:12 +00001784 if (ConstantInt *CI = dyn_cast<ConstantInt>(Canonical)) {
1785 if (ConstantInt *Arg = dyn_cast<ConstantInt>(LHS)) {
Owen Anderson001dbfe2009-07-16 18:04:31 +00001786 add(RHS,
Owen Andersoneed707b2009-07-24 23:12:02 +00001787 ConstantInt::get(*Context, CI->getValue() ^ Arg->getValue()),
Nick Lewyckyc2a7d092007-01-12 00:02:12 +00001788 ICmpInst::ICMP_EQ, NewContext);
1789 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00001790 }
1791 if (Canonical == LHS) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001792 if (isa<ConstantInt>(Canonical))
Owen Anderson0a5372e2009-07-13 04:09:18 +00001793 add(RHS, Context->getNullValue(Ty), ICmpInst::ICMP_EQ,
Nick Lewycky419c6f52007-01-11 02:32:38 +00001794 NewContext);
1795 } else if (isRelatedBy(LHS, Canonical, ICmpInst::ICMP_NE)) {
Owen Anderson0a5372e2009-07-13 04:09:18 +00001796 add(RHS, Context->getNullValue(Ty), ICmpInst::ICMP_NE,
Nick Lewycky419c6f52007-01-11 02:32:38 +00001797 NewContext);
1798 }
1799 } break;
1800 default:
1801 break;
1802 }
1803 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001804 // "icmp ult i32 %a, %y" EQ true then %a u< y
Nick Lewycky419c6f52007-01-11 02:32:38 +00001805 // etc.
1806
Owen Andersonb3056fa2009-07-21 18:03:38 +00001807 if (Canonical == Context->getTrue()) {
Nick Lewycky419c6f52007-01-11 02:32:38 +00001808 add(IC->getOperand(0), IC->getOperand(1), IC->getPredicate(),
1809 NewContext);
Owen Andersonb3056fa2009-07-21 18:03:38 +00001810 } else if (Canonical == Context->getFalse()) {
Nick Lewycky419c6f52007-01-11 02:32:38 +00001811 add(IC->getOperand(0), IC->getOperand(1),
1812 ICmpInst::getInversePredicate(IC->getPredicate()), NewContext);
1813 }
1814 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
1815 if (I->getType()->isFPOrFPVector()) return;
1816
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001817 // Given: "%a = select i1 %x, i32 %b, i32 %c"
Nick Lewycky419c6f52007-01-11 02:32:38 +00001818 // %a EQ %b and %b NE %c then %x EQ true
1819 // %a EQ %c and %b NE %c then %x EQ false
1820
1821 Value *True = SI->getTrueValue();
1822 Value *False = SI->getFalseValue();
1823 if (isRelatedBy(True, False, ICmpInst::ICMP_NE)) {
Nick Lewycky29a05b62007-07-05 03:15:00 +00001824 if (Canonical == VN.canonicalize(True, Top) ||
Nick Lewycky419c6f52007-01-11 02:32:38 +00001825 isRelatedBy(Canonical, False, ICmpInst::ICMP_NE))
Owen Andersonb3056fa2009-07-21 18:03:38 +00001826 add(SI->getCondition(), Context->getTrue(),
Nick Lewycky419c6f52007-01-11 02:32:38 +00001827 ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky29a05b62007-07-05 03:15:00 +00001828 else if (Canonical == VN.canonicalize(False, Top) ||
Nick Lewyckye677a0b2007-03-10 18:12:48 +00001829 isRelatedBy(Canonical, True, ICmpInst::ICMP_NE))
Owen Andersonb3056fa2009-07-21 18:03:38 +00001830 add(SI->getCondition(), Context->getFalse(),
Nick Lewycky419c6f52007-01-11 02:32:38 +00001831 ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky565706b2006-11-22 23:49:16 +00001832 }
Nick Lewycky27e4da92007-03-22 02:02:51 +00001833 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1834 for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
1835 OE = GEPI->idx_end(); OI != OE; ++OI) {
Nick Lewycky29a05b62007-07-05 03:15:00 +00001836 ConstantInt *Op = dyn_cast<ConstantInt>(VN.canonicalize(*OI, Top));
Nick Lewycky27e4da92007-03-22 02:02:51 +00001837 if (!Op || !Op->isZero()) return;
1838 }
1839 // TODO: The GEPI indices are all zero. Copy from definition to operand,
1840 // jumping the type plane as needed.
Owen Anderson0a5372e2009-07-13 04:09:18 +00001841 if (isRelatedBy(GEPI, Context->getNullValue(GEPI->getType()),
Nick Lewycky27e4da92007-03-22 02:02:51 +00001842 ICmpInst::ICMP_NE)) {
1843 Value *Ptr = GEPI->getPointerOperand();
Owen Anderson0a5372e2009-07-13 04:09:18 +00001844 add(Ptr, Context->getNullValue(Ptr->getType()), ICmpInst::ICMP_NE,
Nick Lewycky27e4da92007-03-22 02:02:51 +00001845 NewContext);
1846 }
Nick Lewyckyac4d6642007-04-07 15:48:32 +00001847 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
1848 const Type *SrcTy = CI->getSrcTy();
1849
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001850 unsigned ci = VN.getOrInsertVN(CI, Top);
Nick Lewyckyac4d6642007-04-07 15:48:32 +00001851 uint32_t W = VR.typeToWidth(SrcTy);
1852 if (!W) return;
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001853 ConstantRange CR = VR.range(ci, Top);
Nick Lewyckyac4d6642007-04-07 15:48:32 +00001854
1855 if (CR.isFullSet()) return;
1856
1857 switch (CI->getOpcode()) {
1858 default: break;
1859 case Instruction::ZExt:
1860 case Instruction::SExt:
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001861 VR.applyRange(VN.getOrInsertVN(CI->getOperand(0), Top),
Nick Lewyckyac4d6642007-04-07 15:48:32 +00001862 CR.truncate(W), Top, this);
1863 break;
1864 case Instruction::BitCast:
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00001865 VR.applyRange(VN.getOrInsertVN(CI->getOperand(0), Top),
Nick Lewyckyac4d6642007-04-07 15:48:32 +00001866 CR, Top, this);
1867 break;
1868 }
Nick Lewycky565706b2006-11-22 23:49:16 +00001869 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00001870 }
Nick Lewycky565706b2006-11-22 23:49:16 +00001871
Nick Lewycky419c6f52007-01-11 02:32:38 +00001872 /// opsToDef - A new relationship was discovered involving one of this
1873 /// instruction's operands. Find any new relationship involving the
Nick Lewycky27e4da92007-03-22 02:02:51 +00001874 /// definition, or another operand.
Nick Lewycky419c6f52007-01-11 02:32:38 +00001875 void opsToDef(Instruction *I) {
1876 Instruction *NewContext = below(I) ? I : TopInst;
1877
1878 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Nick Lewycky29a05b62007-07-05 03:15:00 +00001879 Value *Op0 = VN.canonicalize(BO->getOperand(0), Top);
1880 Value *Op1 = VN.canonicalize(BO->getOperand(1), Top);
Nick Lewycky419c6f52007-01-11 02:32:38 +00001881
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001882 if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0))
1883 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky419c6f52007-01-11 02:32:38 +00001884 add(BO, ConstantExpr::get(BO->getOpcode(), CI0, CI1),
1885 ICmpInst::ICMP_EQ, NewContext);
1886 return;
1887 }
1888
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001889 // "%y = and i1 true, %x" then %x EQ %y
1890 // "%y = or i1 false, %x" then %x EQ %y
1891 // "%x = add i32 %y, 0" then %x EQ %y
1892 // "%x = mul i32 %y, 0" then %x EQ 0
1893
1894 Instruction::BinaryOps Opcode = BO->getOpcode();
Nick Lewycky3f64b1a2007-03-18 22:58:46 +00001895 const Type *Ty = BO->getType();
1896 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
1897
Owen Anderson0a5372e2009-07-13 04:09:18 +00001898 Constant *Zero = Context->getNullValue(Ty);
Owen Andersoneed707b2009-07-24 23:12:02 +00001899 Constant *One = ConstantInt::get(Ty, 1);
Owen Anderson73c6b712009-07-13 20:58:05 +00001900 ConstantInt *AllOnes = cast<ConstantInt>(Context->getAllOnesValue(Ty));
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001901
1902 switch (Opcode) {
1903 default: break;
Nick Lewycky27e4da92007-03-22 02:02:51 +00001904 case Instruction::LShr:
1905 case Instruction::AShr:
1906 case Instruction::Shl:
Nick Lewycky79cce5c2008-10-24 04:00:26 +00001907 if (Op1 == Zero) {
1908 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1909 return;
1910 }
1911 break;
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001912 case Instruction::Sub:
Nick Lewycky3f64b1a2007-03-18 22:58:46 +00001913 if (Op1 == Zero) {
1914 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1915 return;
1916 }
Nick Lewycky79cce5c2008-10-24 04:00:26 +00001917 if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0)) {
1918 unsigned n_ci0 = VN.getOrInsertVN(Op1, Top);
1919 ConstantRange CR = VR.range(n_ci0, Top);
1920 if (!CR.isFullSet()) {
1921 CR.subtract(CI0->getValue());
1922 unsigned n_bo = VN.getOrInsertVN(BO, Top);
1923 VR.applyRange(n_bo, CR, Top, this);
1924 return;
1925 }
1926 }
1927 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
1928 unsigned n_ci1 = VN.getOrInsertVN(Op0, Top);
1929 ConstantRange CR = VR.range(n_ci1, Top);
1930 if (!CR.isFullSet()) {
1931 CR.subtract(CI1->getValue());
1932 unsigned n_bo = VN.getOrInsertVN(BO, Top);
1933 VR.applyRange(n_bo, CR, Top, this);
1934 return;
1935 }
1936 }
Nick Lewycky3f64b1a2007-03-18 22:58:46 +00001937 break;
1938 case Instruction::Or:
1939 if (Op0 == AllOnes || Op1 == AllOnes) {
1940 add(BO, AllOnes, ICmpInst::ICMP_EQ, NewContext);
1941 return;
Nick Lewycky79cce5c2008-10-24 04:00:26 +00001942 }
1943 if (Op0 == Zero) {
1944 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1945 return;
1946 } else if (Op1 == Zero) {
1947 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1948 return;
1949 }
1950 break;
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001951 case Instruction::Add:
Nick Lewycky79cce5c2008-10-24 04:00:26 +00001952 if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0)) {
1953 unsigned n_ci0 = VN.getOrInsertVN(Op1, Top);
1954 ConstantRange CR = VR.range(n_ci0, Top);
1955 if (!CR.isFullSet()) {
1956 CR.subtract(-CI0->getValue());
1957 unsigned n_bo = VN.getOrInsertVN(BO, Top);
1958 VR.applyRange(n_bo, CR, Top, this);
1959 return;
1960 }
1961 }
1962 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
1963 unsigned n_ci1 = VN.getOrInsertVN(Op0, Top);
1964 ConstantRange CR = VR.range(n_ci1, Top);
1965 if (!CR.isFullSet()) {
1966 CR.subtract(-CI1->getValue());
1967 unsigned n_bo = VN.getOrInsertVN(BO, Top);
1968 VR.applyRange(n_bo, CR, Top, this);
1969 return;
1970 }
1971 }
1972 // fall-through
1973 case Instruction::Xor:
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001974 if (Op0 == Zero) {
1975 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1976 return;
1977 } else if (Op1 == Zero) {
1978 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1979 return;
1980 }
Nick Lewycky3f64b1a2007-03-18 22:58:46 +00001981 break;
1982 case Instruction::And:
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001983 if (Op0 == AllOnes) {
1984 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1985 return;
1986 } else if (Op1 == AllOnes) {
1987 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1988 return;
1989 }
Nick Lewycky79cce5c2008-10-24 04:00:26 +00001990 if (Op0 == Zero || Op1 == Zero) {
1991 add(BO, Zero, ICmpInst::ICMP_EQ, NewContext);
1992 return;
1993 }
1994 break;
Nick Lewycky3f64b1a2007-03-18 22:58:46 +00001995 case Instruction::Mul:
1996 if (Op0 == Zero || Op1 == Zero) {
Nick Lewycky1eda0f62007-03-18 01:09:32 +00001997 add(BO, Zero, ICmpInst::ICMP_EQ, NewContext);
1998 return;
1999 }
Nick Lewycky79cce5c2008-10-24 04:00:26 +00002000 if (Op0 == One) {
2001 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
2002 return;
2003 } else if (Op1 == One) {
2004 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
2005 return;
2006 }
Nick Lewycky3f64b1a2007-03-18 22:58:46 +00002007 break;
Nick Lewycky565706b2006-11-22 23:49:16 +00002008 }
Nick Lewycky565706b2006-11-22 23:49:16 +00002009
Nick Lewyckye677a0b2007-03-10 18:12:48 +00002010 // "%x = add i32 %y, %z" and %x EQ %y then %z EQ 0
Nick Lewycky27e4da92007-03-22 02:02:51 +00002011 // "%x = add i32 %y, %z" and %x EQ %z then %y EQ 0
2012 // "%x = shl i32 %y, %z" and %x EQ %y and %y NE 0 then %z EQ 0
Nick Lewycky79cce5c2008-10-24 04:00:26 +00002013 // "%x = udiv i32 %y, %z" and %x EQ %y and %y NE 0 then %z EQ 1
Nick Lewycky565706b2006-11-22 23:49:16 +00002014
Nick Lewycky27e4da92007-03-22 02:02:51 +00002015 Value *Known = Op0, *Unknown = Op1,
Nick Lewycky29a05b62007-07-05 03:15:00 +00002016 *TheBO = VN.canonicalize(BO, Top);
Nick Lewycky27e4da92007-03-22 02:02:51 +00002017 if (Known != TheBO) std::swap(Known, Unknown);
2018 if (Known == TheBO) {
Nick Lewycky4c708752007-03-16 02:37:39 +00002019 switch (Opcode) {
Nick Lewycky419c6f52007-01-11 02:32:38 +00002020 default: break;
Nick Lewycky27e4da92007-03-22 02:02:51 +00002021 case Instruction::LShr:
2022 case Instruction::AShr:
2023 case Instruction::Shl:
2024 if (!isRelatedBy(Known, Zero, ICmpInst::ICMP_NE)) break;
2025 // otherwise, fall-through.
2026 case Instruction::Sub:
Nick Lewyckye29578a2007-09-20 00:48:36 +00002027 if (Unknown == Op0) break;
Nick Lewycky27e4da92007-03-22 02:02:51 +00002028 // otherwise, fall-through.
Nick Lewycky419c6f52007-01-11 02:32:38 +00002029 case Instruction::Xor:
Nick Lewycky419c6f52007-01-11 02:32:38 +00002030 case Instruction::Add:
Nick Lewycky3f64b1a2007-03-18 22:58:46 +00002031 add(Unknown, Zero, ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky419c6f52007-01-11 02:32:38 +00002032 break;
2033 case Instruction::UDiv:
2034 case Instruction::SDiv:
Nick Lewycky27e4da92007-03-22 02:02:51 +00002035 if (Unknown == Op1) break;
Nick Lewycky79cce5c2008-10-24 04:00:26 +00002036 if (isRelatedBy(Known, Zero, ICmpInst::ICMP_NE))
Nick Lewyckyc2a7d092007-01-12 00:02:12 +00002037 add(Unknown, One, ICmpInst::ICMP_EQ, NewContext);
Nick Lewyckye63bf952006-10-25 23:48:24 +00002038 break;
Nick Lewycky565706b2006-11-22 23:49:16 +00002039 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00002040 }
Nick Lewycky565706b2006-11-22 23:49:16 +00002041
Nick Lewyckye677a0b2007-03-10 18:12:48 +00002042 // TODO: "%a = add i32 %b, 1" and %b > %z then %a >= %z.
Nick Lewycky565706b2006-11-22 23:49:16 +00002043
Nick Lewycky419c6f52007-01-11 02:32:38 +00002044 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
Nick Lewycky4c708752007-03-16 02:37:39 +00002045 // "%a = icmp ult i32 %b, %c" and %b u< %c then %a EQ true
Nick Lewyckye677a0b2007-03-10 18:12:48 +00002046 // "%a = icmp ult i32 %b, %c" and %b u>= %c then %a EQ false
Nick Lewycky419c6f52007-01-11 02:32:38 +00002047 // etc.
2048
Nick Lewycky29a05b62007-07-05 03:15:00 +00002049 Value *Op0 = VN.canonicalize(IC->getOperand(0), Top);
2050 Value *Op1 = VN.canonicalize(IC->getOperand(1), Top);
Nick Lewycky419c6f52007-01-11 02:32:38 +00002051
2052 ICmpInst::Predicate Pred = IC->getPredicate();
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002053 if (isRelatedBy(Op0, Op1, Pred))
Owen Andersonb3056fa2009-07-21 18:03:38 +00002054 add(IC, Context->getTrue(), ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002055 else if (isRelatedBy(Op0, Op1, ICmpInst::getInversePredicate(Pred)))
Owen Andersonb3056fa2009-07-21 18:03:38 +00002056 add(IC, Context->getFalse(),
Owen Andersonf53c3712009-07-21 02:47:59 +00002057 ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky419c6f52007-01-11 02:32:38 +00002058
Nick Lewycky419c6f52007-01-11 02:32:38 +00002059 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
Nick Lewycky27e4da92007-03-22 02:02:51 +00002060 if (I->getType()->isFPOrFPVector()) return;
2061
Nick Lewycky4c708752007-03-16 02:37:39 +00002062 // Given: "%a = select i1 %x, i32 %b, i32 %c"
Nick Lewycky419c6f52007-01-11 02:32:38 +00002063 // %x EQ true then %a EQ %b
2064 // %x EQ false then %a EQ %c
2065 // %b EQ %c then %a EQ %b
2066
Nick Lewycky29a05b62007-07-05 03:15:00 +00002067 Value *Canonical = VN.canonicalize(SI->getCondition(), Top);
Owen Andersonb3056fa2009-07-21 18:03:38 +00002068 if (Canonical == Context->getTrue()) {
Nick Lewycky419c6f52007-01-11 02:32:38 +00002069 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
Owen Andersonb3056fa2009-07-21 18:03:38 +00002070 } else if (Canonical == Context->getFalse()) {
Nick Lewycky419c6f52007-01-11 02:32:38 +00002071 add(SI, SI->getFalseValue(), ICmpInst::ICMP_EQ, NewContext);
Nick Lewycky29a05b62007-07-05 03:15:00 +00002072 } else if (VN.canonicalize(SI->getTrueValue(), Top) ==
2073 VN.canonicalize(SI->getFalseValue(), Top)) {
Nick Lewycky419c6f52007-01-11 02:32:38 +00002074 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
2075 }
Nick Lewycky28c5b152007-01-12 01:23:53 +00002076 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Nick Lewyckyac4d6642007-04-07 15:48:32 +00002077 const Type *DestTy = CI->getDestTy();
2078 if (DestTy->isFPOrFPVector()) return;
Nick Lewycky28c5b152007-01-12 01:23:53 +00002079
Nick Lewycky29a05b62007-07-05 03:15:00 +00002080 Value *Op = VN.canonicalize(CI->getOperand(0), Top);
Nick Lewyckyac4d6642007-04-07 15:48:32 +00002081 Instruction::CastOps Opcode = CI->getOpcode();
2082
2083 if (Constant *C = dyn_cast<Constant>(Op)) {
2084 add(CI, ConstantExpr::getCast(Opcode, C, DestTy),
Nick Lewycky28c5b152007-01-12 01:23:53 +00002085 ICmpInst::ICMP_EQ, NewContext);
2086 }
2087
Nick Lewyckyac4d6642007-04-07 15:48:32 +00002088 uint32_t W = VR.typeToWidth(DestTy);
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002089 unsigned ci = VN.getOrInsertVN(CI, Top);
2090 ConstantRange CR = VR.range(VN.getOrInsertVN(Op, Top), Top);
Nick Lewyckyac4d6642007-04-07 15:48:32 +00002091
2092 if (!CR.isFullSet()) {
2093 switch (Opcode) {
2094 default: break;
2095 case Instruction::ZExt:
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002096 VR.applyRange(ci, CR.zeroExtend(W), Top, this);
Nick Lewyckyac4d6642007-04-07 15:48:32 +00002097 break;
2098 case Instruction::SExt:
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002099 VR.applyRange(ci, CR.signExtend(W), Top, this);
Nick Lewyckyac4d6642007-04-07 15:48:32 +00002100 break;
2101 case Instruction::Trunc: {
2102 ConstantRange Result = CR.truncate(W);
2103 if (!Result.isFullSet())
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002104 VR.applyRange(ci, Result, Top, this);
Nick Lewyckyac4d6642007-04-07 15:48:32 +00002105 } break;
2106 case Instruction::BitCast:
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002107 VR.applyRange(ci, CR, Top, this);
Nick Lewyckyac4d6642007-04-07 15:48:32 +00002108 break;
2109 // TODO: other casts?
2110 }
2111 }
Nick Lewycky27e4da92007-03-22 02:02:51 +00002112 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
2113 for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
2114 OE = GEPI->idx_end(); OI != OE; ++OI) {
Nick Lewycky29a05b62007-07-05 03:15:00 +00002115 ConstantInt *Op = dyn_cast<ConstantInt>(VN.canonicalize(*OI, Top));
Nick Lewycky27e4da92007-03-22 02:02:51 +00002116 if (!Op || !Op->isZero()) return;
2117 }
2118 // TODO: The GEPI indices are all zero. Copy from operand to definition,
2119 // jumping the type plane as needed.
2120 Value *Ptr = GEPI->getPointerOperand();
Owen Anderson0a5372e2009-07-13 04:09:18 +00002121 if (isRelatedBy(Ptr, Context->getNullValue(Ptr->getType()),
Nick Lewycky27e4da92007-03-22 02:02:51 +00002122 ICmpInst::ICMP_NE)) {
Owen Anderson0a5372e2009-07-13 04:09:18 +00002123 add(GEPI, Context->getNullValue(GEPI->getType()), ICmpInst::ICMP_NE,
Nick Lewycky27e4da92007-03-22 02:02:51 +00002124 NewContext);
2125 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00002126 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00002127 }
2128
2129 /// solve - process the work queue
Nick Lewycky419c6f52007-01-11 02:32:38 +00002130 void solve() {
2131 //DOUT << "WorkList entry, size: " << WorkList.size() << "\n";
2132 while (!WorkList.empty()) {
2133 //DOUT << "WorkList size: " << WorkList.size() << "\n";
2134
2135 Operation &O = WorkList.front();
Nick Lewycky0be7f472007-01-13 02:05:28 +00002136 TopInst = O.ContextInst;
2137 TopBB = O.ContextBB;
Nick Lewycky984504b2007-06-24 04:36:20 +00002138 Top = DTDFS->getNodeForBlock(TopBB); // XXX move this into Context
Nick Lewycky0be7f472007-01-13 02:05:28 +00002139
Nick Lewycky29a05b62007-07-05 03:15:00 +00002140 O.LHS = VN.canonicalize(O.LHS, Top);
2141 O.RHS = VN.canonicalize(O.RHS, Top);
Nick Lewycky419c6f52007-01-11 02:32:38 +00002142
Nick Lewycky29a05b62007-07-05 03:15:00 +00002143 assert(O.LHS == VN.canonicalize(O.LHS, Top) && "Canonicalize isn't.");
2144 assert(O.RHS == VN.canonicalize(O.RHS, Top) && "Canonicalize isn't.");
Nick Lewycky419c6f52007-01-11 02:32:38 +00002145
2146 DOUT << "solving " << *O.LHS << " " << O.Op << " " << *O.RHS;
Nick Lewycky0be7f472007-01-13 02:05:28 +00002147 if (O.ContextInst) DOUT << " context inst: " << *O.ContextInst;
2148 else DOUT << " context block: " << O.ContextBB->getName();
Nick Lewycky419c6f52007-01-11 02:32:38 +00002149 DOUT << "\n";
2150
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002151 DEBUG(VN.dump());
Nick Lewycky419c6f52007-01-11 02:32:38 +00002152 DEBUG(IG.dump());
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002153 DEBUG(VR.dump());
Nick Lewycky419c6f52007-01-11 02:32:38 +00002154
Nick Lewycky45351752007-02-04 23:43:05 +00002155 // If they're both Constant, skip it. Check for contradiction and mark
2156 // the BB as unreachable if so.
2157 if (Constant *CI_L = dyn_cast<Constant>(O.LHS)) {
2158 if (Constant *CI_R = dyn_cast<Constant>(O.RHS)) {
Owen Andersonf53c3712009-07-21 02:47:59 +00002159 if (Context->getConstantExprCompare(O.Op, CI_L, CI_R) ==
Owen Andersonb3056fa2009-07-21 18:03:38 +00002160 Context->getFalse())
Nick Lewycky45351752007-02-04 23:43:05 +00002161 UB.mark(TopBB);
2162
2163 WorkList.pop_front();
2164 continue;
2165 }
2166 }
2167
Nick Lewycky29a05b62007-07-05 03:15:00 +00002168 if (VN.compare(O.LHS, O.RHS)) {
Nick Lewycky45351752007-02-04 23:43:05 +00002169 std::swap(O.LHS, O.RHS);
2170 O.Op = ICmpInst::getSwappedPredicate(O.Op);
Nick Lewycky419c6f52007-01-11 02:32:38 +00002171 }
2172
2173 if (O.Op == ICmpInst::ICMP_EQ) {
Nick Lewyckye677a0b2007-03-10 18:12:48 +00002174 if (!makeEqual(O.RHS, O.LHS))
Nick Lewycky419c6f52007-01-11 02:32:38 +00002175 UB.mark(TopBB);
2176 } else {
2177 LatticeVal LV = cmpInstToLattice(O.Op);
2178
2179 if ((LV & EQ_BIT) &&
2180 isRelatedBy(O.LHS, O.RHS, ICmpInst::getSwappedPredicate(O.Op))) {
Nick Lewyckye677a0b2007-03-10 18:12:48 +00002181 if (!makeEqual(O.RHS, O.LHS))
Nick Lewycky419c6f52007-01-11 02:32:38 +00002182 UB.mark(TopBB);
2183 } else {
2184 if (isRelatedBy(O.LHS, O.RHS, ICmpInst::getInversePredicate(O.Op))){
Nick Lewycky45351752007-02-04 23:43:05 +00002185 UB.mark(TopBB);
Nick Lewycky419c6f52007-01-11 02:32:38 +00002186 WorkList.pop_front();
2187 continue;
2188 }
2189
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002190 unsigned n1 = VN.getOrInsertVN(O.LHS, Top);
2191 unsigned n2 = VN.getOrInsertVN(O.RHS, Top);
Nick Lewycky419c6f52007-01-11 02:32:38 +00002192
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002193 if (n1 == n2) {
Nick Lewycky419c6f52007-01-11 02:32:38 +00002194 if (O.Op != ICmpInst::ICMP_UGE && O.Op != ICmpInst::ICMP_ULE &&
2195 O.Op != ICmpInst::ICMP_SGE && O.Op != ICmpInst::ICMP_SLE)
2196 UB.mark(TopBB);
2197
2198 WorkList.pop_front();
2199 continue;
2200 }
2201
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002202 if (VR.isRelatedBy(n1, n2, Top, LV) ||
2203 IG.isRelatedBy(n1, n2, Top, LV)) {
Nick Lewycky419c6f52007-01-11 02:32:38 +00002204 WorkList.pop_front();
2205 continue;
2206 }
2207
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002208 VR.addInequality(n1, n2, Top, LV, this);
Nick Lewyckye677a0b2007-03-10 18:12:48 +00002209 if ((!isa<ConstantInt>(O.RHS) && !isa<ConstantInt>(O.LHS)) ||
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002210 LV == NE)
Nick Lewyckye677a0b2007-03-10 18:12:48 +00002211 IG.addInequality(n1, n2, Top, LV);
Nick Lewycky45351752007-02-04 23:43:05 +00002212
Nick Lewyckydd402582007-01-15 14:30:07 +00002213 if (Instruction *I1 = dyn_cast<Instruction>(O.LHS)) {
Nick Lewycky984504b2007-06-24 04:36:20 +00002214 if (aboveOrBelow(I1))
Nick Lewyckydd402582007-01-15 14:30:07 +00002215 defToOps(I1);
2216 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00002217 if (isa<Instruction>(O.LHS) || isa<Argument>(O.LHS)) {
2218 for (Value::use_iterator UI = O.LHS->use_begin(),
2219 UE = O.LHS->use_end(); UI != UE;) {
2220 Use &TheUse = UI.getUse();
2221 ++UI;
Jay Foad0906b1b2009-06-06 17:49:35 +00002222 Instruction *I = cast<Instruction>(TheUse.getUser());
2223 if (aboveOrBelow(I))
2224 opsToDef(I);
Nick Lewycky419c6f52007-01-11 02:32:38 +00002225 }
2226 }
Nick Lewyckydd402582007-01-15 14:30:07 +00002227 if (Instruction *I2 = dyn_cast<Instruction>(O.RHS)) {
Nick Lewycky984504b2007-06-24 04:36:20 +00002228 if (aboveOrBelow(I2))
Nick Lewyckydd402582007-01-15 14:30:07 +00002229 defToOps(I2);
2230 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00002231 if (isa<Instruction>(O.RHS) || isa<Argument>(O.RHS)) {
2232 for (Value::use_iterator UI = O.RHS->use_begin(),
2233 UE = O.RHS->use_end(); UI != UE;) {
2234 Use &TheUse = UI.getUse();
2235 ++UI;
Jay Foad0906b1b2009-06-06 17:49:35 +00002236 Instruction *I = cast<Instruction>(TheUse.getUser());
2237 if (aboveOrBelow(I))
2238 opsToDef(I);
Nick Lewycky419c6f52007-01-11 02:32:38 +00002239 }
Nick Lewyckye63bf952006-10-25 23:48:24 +00002240 }
2241 }
Nick Lewyckye63bf952006-10-25 23:48:24 +00002242 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00002243 WorkList.pop_front();
Nick Lewyckye63bf952006-10-25 23:48:24 +00002244 }
Nick Lewyckye63bf952006-10-25 23:48:24 +00002245 }
Nick Lewycky05450ae2006-08-28 22:44:55 +00002246 };
2247
Nick Lewyckyf3a9e362007-04-07 03:36:51 +00002248 void ValueRanges::addToWorklist(Value *V, Constant *C,
Nick Lewyckye677a0b2007-03-10 18:12:48 +00002249 ICmpInst::Predicate Pred, VRPSolver *VRP) {
Nick Lewyckyf3a9e362007-04-07 03:36:51 +00002250 VRP->add(V, C, Pred, VRP->TopInst);
Nick Lewyckye677a0b2007-03-10 18:12:48 +00002251 }
2252
Nick Lewyckyac4d6642007-04-07 15:48:32 +00002253 void ValueRanges::markBlock(VRPSolver *VRP) {
2254 VRP->UB.mark(VRP->TopBB);
2255 }
2256
Nick Lewycky05450ae2006-08-28 22:44:55 +00002257 /// PredicateSimplifier - This class is a simplifier that replaces
2258 /// one equivalent variable with another. It also tracks what
2259 /// can't be equal and will solve setcc instructions when possible.
Nick Lewycky565706b2006-11-22 23:49:16 +00002260 /// @brief Root of the predicate simplifier optimization.
2261 class VISIBILITY_HIDDEN PredicateSimplifier : public FunctionPass {
Nick Lewycky984504b2007-06-24 04:36:20 +00002262 DomTreeDFS *DTDFS;
Nick Lewycky565706b2006-11-22 23:49:16 +00002263 bool modified;
Nick Lewycky29a05b62007-07-05 03:15:00 +00002264 ValueNumbering *VN;
Nick Lewycky419c6f52007-01-11 02:32:38 +00002265 InequalityGraph *IG;
2266 UnreachableBlocks UB;
Nick Lewyckye677a0b2007-03-10 18:12:48 +00002267 ValueRanges *VR;
Nick Lewycky565706b2006-11-22 23:49:16 +00002268
Nick Lewycky984504b2007-06-24 04:36:20 +00002269 std::vector<DomTreeDFS::Node *> WorkList;
Nick Lewycky565706b2006-11-22 23:49:16 +00002270
Owen Andersone922c022009-07-22 00:24:57 +00002271 LLVMContext *Context;
Nick Lewycky05450ae2006-08-28 22:44:55 +00002272 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +00002273 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +00002274 PredicateSimplifier() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +00002275
Nick Lewycky05450ae2006-08-28 22:44:55 +00002276 bool runOnFunction(Function &F);
Nick Lewycky565706b2006-11-22 23:49:16 +00002277
2278 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
2279 AU.addRequiredID(BreakCriticalEdgesID);
Owen Andersonab0e4d32007-04-25 04:18:54 +00002280 AU.addRequired<DominatorTree>();
Nick Lewyckyb01c77e2007-04-07 03:16:12 +00002281 AU.addRequired<TargetData>();
2282 AU.addPreserved<TargetData>();
Nick Lewycky565706b2006-11-22 23:49:16 +00002283 }
Nick Lewycky05450ae2006-08-28 22:44:55 +00002284
2285 private:
Nick Lewycky5380e942007-07-16 02:58:37 +00002286 /// Forwards - Adds new properties to VRPSolver and uses them to
Nick Lewycky078ff412006-10-12 02:02:44 +00002287 /// simplify instructions. Because new properties sometimes apply to
2288 /// a transition from one BasicBlock to another, this will use the
2289 /// PredicateSimplifier::proceedToSuccessor(s) interface to enter the
Nick Lewycky5380e942007-07-16 02:58:37 +00002290 /// basic block.
Nick Lewycky565706b2006-11-22 23:49:16 +00002291 /// @brief Performs abstract execution of the program.
2292 class VISIBILITY_HIDDEN Forwards : public InstVisitor<Forwards> {
Nick Lewycky078ff412006-10-12 02:02:44 +00002293 friend class InstVisitor<Forwards>;
2294 PredicateSimplifier *PS;
Nick Lewycky984504b2007-06-24 04:36:20 +00002295 DomTreeDFS::Node *DTNode;
Nick Lewycky565706b2006-11-22 23:49:16 +00002296
Nick Lewycky078ff412006-10-12 02:02:44 +00002297 public:
Nick Lewycky29a05b62007-07-05 03:15:00 +00002298 ValueNumbering &VN;
Nick Lewycky565706b2006-11-22 23:49:16 +00002299 InequalityGraph &IG;
Nick Lewycky419c6f52007-01-11 02:32:38 +00002300 UnreachableBlocks &UB;
Nick Lewyckye677a0b2007-03-10 18:12:48 +00002301 ValueRanges &VR;
Nick Lewycky078ff412006-10-12 02:02:44 +00002302
Nick Lewycky984504b2007-06-24 04:36:20 +00002303 Forwards(PredicateSimplifier *PS, DomTreeDFS::Node *DTNode)
Nick Lewycky29a05b62007-07-05 03:15:00 +00002304 : PS(PS), DTNode(DTNode), VN(*PS->VN), IG(*PS->IG), UB(PS->UB),
2305 VR(*PS->VR) {}
Nick Lewycky078ff412006-10-12 02:02:44 +00002306
2307 void visitTerminatorInst(TerminatorInst &TI);
2308 void visitBranchInst(BranchInst &BI);
2309 void visitSwitchInst(SwitchInst &SI);
2310
Nick Lewycky802fe272006-10-22 19:53:27 +00002311 void visitAllocaInst(AllocaInst &AI);
Nick Lewycky078ff412006-10-12 02:02:44 +00002312 void visitLoadInst(LoadInst &LI);
2313 void visitStoreInst(StoreInst &SI);
Nick Lewycky565706b2006-11-22 23:49:16 +00002314
Nick Lewycky45351752007-02-04 23:43:05 +00002315 void visitSExtInst(SExtInst &SI);
2316 void visitZExtInst(ZExtInst &ZI);
2317
Nick Lewycky078ff412006-10-12 02:02:44 +00002318 void visitBinaryOperator(BinaryOperator &BO);
Nick Lewycky4c708752007-03-16 02:37:39 +00002319 void visitICmpInst(ICmpInst &IC);
Nick Lewycky078ff412006-10-12 02:02:44 +00002320 };
Nick Lewyckye677a0b2007-03-10 18:12:48 +00002321
Nick Lewycky05450ae2006-08-28 22:44:55 +00002322 // Used by terminator instructions to proceed from the current basic
2323 // block to the next. Verifies that "current" dominates "next",
2324 // then calls visitBasicBlock.
Nick Lewycky984504b2007-06-24 04:36:20 +00002325 void proceedToSuccessors(DomTreeDFS::Node *Current) {
2326 for (DomTreeDFS::Node::iterator I = Current->begin(),
Owen Andersonab0e4d32007-04-25 04:18:54 +00002327 E = Current->end(); I != E; ++I) {
Nick Lewycky419c6f52007-01-11 02:32:38 +00002328 WorkList.push_back(*I);
Nick Lewycky565706b2006-11-22 23:49:16 +00002329 }
2330 }
2331
Nick Lewycky984504b2007-06-24 04:36:20 +00002332 void proceedToSuccessor(DomTreeDFS::Node *Next) {
Nick Lewycky419c6f52007-01-11 02:32:38 +00002333 WorkList.push_back(Next);
Nick Lewycky565706b2006-11-22 23:49:16 +00002334 }
Nick Lewycky05450ae2006-08-28 22:44:55 +00002335
2336 // Visits each instruction in the basic block.
Nick Lewycky984504b2007-06-24 04:36:20 +00002337 void visitBasicBlock(DomTreeDFS::Node *Node) {
Owen Andersonab0e4d32007-04-25 04:18:54 +00002338 BasicBlock *BB = Node->getBlock();
Nick Lewyckydd402582007-01-15 14:30:07 +00002339 DOUT << "Entering Basic Block: " << BB->getName()
Nick Lewycky984504b2007-06-24 04:36:20 +00002340 << " (" << Node->getDFSNumIn() << ")\n";
Bill Wendling832171c2006-12-07 20:04:42 +00002341 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Nick Lewycky984504b2007-06-24 04:36:20 +00002342 visitInstruction(I++, Node);
Nick Lewycky565706b2006-11-22 23:49:16 +00002343 }
2344 }
Nick Lewycky05450ae2006-08-28 22:44:55 +00002345
Nick Lewycky5380e942007-07-16 02:58:37 +00002346 // Tries to simplify each Instruction and add new properties.
Nick Lewycky984504b2007-06-24 04:36:20 +00002347 void visitInstruction(Instruction *I, DomTreeDFS::Node *DT) {
Bill Wendling832171c2006-12-07 20:04:42 +00002348 DOUT << "Considering instruction " << *I << "\n";
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002349 DEBUG(VN->dump());
Nick Lewycky419c6f52007-01-11 02:32:38 +00002350 DEBUG(IG->dump());
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002351 DEBUG(VR->dump());
Nick Lewycky05450ae2006-08-28 22:44:55 +00002352
Nick Lewycky419c6f52007-01-11 02:32:38 +00002353 // Sometimes instructions are killed in earlier analysis.
Nick Lewycky565706b2006-11-22 23:49:16 +00002354 if (isInstructionTriviallyDead(I)) {
Nick Lewycky419c6f52007-01-11 02:32:38 +00002355 ++NumSimple;
2356 modified = true;
Nick Lewycky29a05b62007-07-05 03:15:00 +00002357 if (unsigned n = VN->valueNumber(I, DTDFS->getRootNode()))
2358 if (VN->value(n) == I) IG->remove(n);
2359 VN->remove(I);
Nick Lewycky565706b2006-11-22 23:49:16 +00002360 I->eraseFromParent();
2361 return;
2362 }
2363
Nick Lewycky0be7f472007-01-13 02:05:28 +00002364#ifndef NDEBUG
Nick Lewycky565706b2006-11-22 23:49:16 +00002365 // Try to replace the whole instruction.
Nick Lewycky29a05b62007-07-05 03:15:00 +00002366 Value *V = VN->canonicalize(I, DT);
Nick Lewycky419c6f52007-01-11 02:32:38 +00002367 assert(V == I && "Late instruction canonicalization.");
Nick Lewycky565706b2006-11-22 23:49:16 +00002368 if (V != I) {
2369 modified = true;
2370 ++NumInstruction;
Bill Wendling832171c2006-12-07 20:04:42 +00002371 DOUT << "Removing " << *I << ", replacing with " << *V << "\n";
Nick Lewycky29a05b62007-07-05 03:15:00 +00002372 if (unsigned n = VN->valueNumber(I, DTDFS->getRootNode()))
2373 if (VN->value(n) == I) IG->remove(n);
2374 VN->remove(I);
Nick Lewycky565706b2006-11-22 23:49:16 +00002375 I->replaceAllUsesWith(V);
2376 I->eraseFromParent();
2377 return;
2378 }
2379
2380 // Try to substitute operands.
2381 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2382 Value *Oper = I->getOperand(i);
Nick Lewycky29a05b62007-07-05 03:15:00 +00002383 Value *V = VN->canonicalize(Oper, DT);
Nick Lewycky419c6f52007-01-11 02:32:38 +00002384 assert(V == Oper && "Late operand canonicalization.");
Nick Lewycky565706b2006-11-22 23:49:16 +00002385 if (V != Oper) {
2386 modified = true;
2387 ++NumVarsReplaced;
Bill Wendling832171c2006-12-07 20:04:42 +00002388 DOUT << "Resolving " << *I;
Nick Lewycky565706b2006-11-22 23:49:16 +00002389 I->setOperand(i, V);
Bill Wendling832171c2006-12-07 20:04:42 +00002390 DOUT << " into " << *I;
Nick Lewycky565706b2006-11-22 23:49:16 +00002391 }
2392 }
Nick Lewycky0be7f472007-01-13 02:05:28 +00002393#endif
Nick Lewycky565706b2006-11-22 23:49:16 +00002394
Nick Lewycky4c708752007-03-16 02:37:39 +00002395 std::string name = I->getParent()->getName();
2396 DOUT << "push (%" << name << ")\n";
Owen Andersonab0e4d32007-04-25 04:18:54 +00002397 Forwards visit(this, DT);
Nick Lewycky565706b2006-11-22 23:49:16 +00002398 visit.visit(*I);
Nick Lewycky4c708752007-03-16 02:37:39 +00002399 DOUT << "pop (%" << name << ")\n";
Nick Lewycky565706b2006-11-22 23:49:16 +00002400 }
Nick Lewycky05450ae2006-08-28 22:44:55 +00002401 };
2402
Nick Lewycky565706b2006-11-22 23:49:16 +00002403 bool PredicateSimplifier::runOnFunction(Function &F) {
Nick Lewycky984504b2007-06-24 04:36:20 +00002404 DominatorTree *DT = &getAnalysis<DominatorTree>();
2405 DTDFS = new DomTreeDFS(DT);
Nick Lewyckyb01c77e2007-04-07 03:16:12 +00002406 TargetData *TD = &getAnalysis<TargetData>();
Owen Andersone922c022009-07-22 00:24:57 +00002407 Context = &F.getContext();
Nick Lewyckyb01c77e2007-04-07 03:16:12 +00002408
Bill Wendling832171c2006-12-07 20:04:42 +00002409 DOUT << "Entering Function: " << F.getName() << "\n";
Nick Lewycky406fc0c2006-09-20 17:04:01 +00002410
Nick Lewycky565706b2006-11-22 23:49:16 +00002411 modified = false;
Nick Lewycky984504b2007-06-24 04:36:20 +00002412 DomTreeDFS::Node *Root = DTDFS->getRootNode();
Nick Lewycky29a05b62007-07-05 03:15:00 +00002413 VN = new ValueNumbering(DTDFS);
2414 IG = new InequalityGraph(*VN, Root);
Owen Anderson001dbfe2009-07-16 18:04:31 +00002415 VR = new ValueRanges(*VN, TD, Context);
Nick Lewycky984504b2007-06-24 04:36:20 +00002416 WorkList.push_back(Root);
Nick Lewycky406fc0c2006-09-20 17:04:01 +00002417
Nick Lewycky565706b2006-11-22 23:49:16 +00002418 do {
Nick Lewycky984504b2007-06-24 04:36:20 +00002419 DomTreeDFS::Node *DTNode = WorkList.back();
Nick Lewycky565706b2006-11-22 23:49:16 +00002420 WorkList.pop_back();
Owen Andersonab0e4d32007-04-25 04:18:54 +00002421 if (!UB.isDead(DTNode->getBlock())) visitBasicBlock(DTNode);
Nick Lewycky565706b2006-11-22 23:49:16 +00002422 } while (!WorkList.empty());
Nick Lewycky406fc0c2006-09-20 17:04:01 +00002423
Nick Lewycky984504b2007-06-24 04:36:20 +00002424 delete DTDFS;
Nick Lewyckye677a0b2007-03-10 18:12:48 +00002425 delete VR;
Nick Lewycky419c6f52007-01-11 02:32:38 +00002426 delete IG;
Nuno Lopesea736ce2008-11-09 12:45:23 +00002427 delete VN;
Nick Lewycky419c6f52007-01-11 02:32:38 +00002428
2429 modified |= UB.kill();
Nick Lewycky406fc0c2006-09-20 17:04:01 +00002430
Nick Lewycky565706b2006-11-22 23:49:16 +00002431 return modified;
Nick Lewyckya3a68bd2006-09-02 19:40:38 +00002432 }
2433
Nick Lewycky565706b2006-11-22 23:49:16 +00002434 void PredicateSimplifier::Forwards::visitTerminatorInst(TerminatorInst &TI) {
Owen Andersonab0e4d32007-04-25 04:18:54 +00002435 PS->proceedToSuccessors(DTNode);
Nick Lewycky565706b2006-11-22 23:49:16 +00002436 }
2437
2438 void PredicateSimplifier::Forwards::visitBranchInst(BranchInst &BI) {
Nick Lewycky565706b2006-11-22 23:49:16 +00002439 if (BI.isUnconditional()) {
Owen Andersonab0e4d32007-04-25 04:18:54 +00002440 PS->proceedToSuccessors(DTNode);
Nick Lewycky565706b2006-11-22 23:49:16 +00002441 return;
2442 }
2443
2444 Value *Condition = BI.getCondition();
Nick Lewycky419c6f52007-01-11 02:32:38 +00002445 BasicBlock *TrueDest = BI.getSuccessor(0);
2446 BasicBlock *FalseDest = BI.getSuccessor(1);
Nick Lewycky565706b2006-11-22 23:49:16 +00002447
Nick Lewycky419c6f52007-01-11 02:32:38 +00002448 if (isa<Constant>(Condition) || TrueDest == FalseDest) {
Owen Andersonab0e4d32007-04-25 04:18:54 +00002449 PS->proceedToSuccessors(DTNode);
Nick Lewycky565706b2006-11-22 23:49:16 +00002450 return;
2451 }
2452
Owen Andersone922c022009-07-22 00:24:57 +00002453 LLVMContext *Context = &BI.getContext();
Owen Andersonf53c3712009-07-21 02:47:59 +00002454
Nick Lewycky984504b2007-06-24 04:36:20 +00002455 for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
Owen Andersonab0e4d32007-04-25 04:18:54 +00002456 I != E; ++I) {
2457 BasicBlock *Dest = (*I)->getBlock();
Nick Lewycky419c6f52007-01-11 02:32:38 +00002458 DOUT << "Branch thinking about %" << Dest->getName()
Nick Lewycky984504b2007-06-24 04:36:20 +00002459 << "(" << PS->DTDFS->getNodeForBlock(Dest)->getDFSNumIn() << ")\n";
Nick Lewycky565706b2006-11-22 23:49:16 +00002460
2461 if (Dest == TrueDest) {
Owen Andersonab0e4d32007-04-25 04:18:54 +00002462 DOUT << "(" << DTNode->getBlock()->getName() << ") true set:\n";
Nick Lewycky29a05b62007-07-05 03:15:00 +00002463 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
Owen Andersonb3056fa2009-07-21 18:03:38 +00002464 VRP.add(Context->getTrue(), Condition, ICmpInst::ICMP_EQ);
Nick Lewycky419c6f52007-01-11 02:32:38 +00002465 VRP.solve();
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002466 DEBUG(VN.dump());
Nick Lewycky419c6f52007-01-11 02:32:38 +00002467 DEBUG(IG.dump());
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002468 DEBUG(VR.dump());
Nick Lewycky565706b2006-11-22 23:49:16 +00002469 } else if (Dest == FalseDest) {
Owen Andersonab0e4d32007-04-25 04:18:54 +00002470 DOUT << "(" << DTNode->getBlock()->getName() << ") false set:\n";
Nick Lewycky29a05b62007-07-05 03:15:00 +00002471 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
Owen Andersonb3056fa2009-07-21 18:03:38 +00002472 VRP.add(Context->getFalse(), Condition, ICmpInst::ICMP_EQ);
Nick Lewycky419c6f52007-01-11 02:32:38 +00002473 VRP.solve();
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002474 DEBUG(VN.dump());
Nick Lewycky419c6f52007-01-11 02:32:38 +00002475 DEBUG(IG.dump());
Nick Lewycky6e8eb7f2007-07-10 03:28:21 +00002476 DEBUG(VR.dump());
Nick Lewycky565706b2006-11-22 23:49:16 +00002477 }
2478
Nick Lewycky419c6f52007-01-11 02:32:38 +00002479 PS->proceedToSuccessor(*I);
Nick Lewycky05450ae2006-08-28 22:44:55 +00002480 }
2481 }
2482
Nick Lewycky565706b2006-11-22 23:49:16 +00002483 void PredicateSimplifier::Forwards::visitSwitchInst(SwitchInst &SI) {
2484 Value *Condition = SI.getCondition();
Nick Lewycky05450ae2006-08-28 22:44:55 +00002485
Nick Lewycky565706b2006-11-22 23:49:16 +00002486 // Set the EQProperty in each of the cases BBs, and the NEProperties
2487 // in the default BB.
Owen Andersonab0e4d32007-04-25 04:18:54 +00002488
Nick Lewycky984504b2007-06-24 04:36:20 +00002489 for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
Owen Andersonab0e4d32007-04-25 04:18:54 +00002490 I != E; ++I) {
2491 BasicBlock *BB = (*I)->getBlock();
Nick Lewycky419c6f52007-01-11 02:32:38 +00002492 DOUT << "Switch thinking about BB %" << BB->getName()
Nick Lewycky984504b2007-06-24 04:36:20 +00002493 << "(" << PS->DTDFS->getNodeForBlock(BB)->getDFSNumIn() << ")\n";
Nick Lewycky05450ae2006-08-28 22:44:55 +00002494
Nick Lewycky29a05b62007-07-05 03:15:00 +00002495 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, BB);
Nick Lewycky565706b2006-11-22 23:49:16 +00002496 if (BB == SI.getDefaultDest()) {
2497 for (unsigned i = 1, e = SI.getNumCases(); i < e; ++i)
2498 if (SI.getSuccessor(i) != BB)
Nick Lewycky419c6f52007-01-11 02:32:38 +00002499 VRP.add(Condition, SI.getCaseValue(i), ICmpInst::ICMP_NE);
2500 VRP.solve();
Nick Lewycky565706b2006-11-22 23:49:16 +00002501 } else if (ConstantInt *CI = SI.findCaseDest(BB)) {
Nick Lewycky419c6f52007-01-11 02:32:38 +00002502 VRP.add(Condition, CI, ICmpInst::ICMP_EQ);
2503 VRP.solve();
Nick Lewycky565706b2006-11-22 23:49:16 +00002504 }
Nick Lewycky419c6f52007-01-11 02:32:38 +00002505 PS->proceedToSuccessor(*I);
Nick Lewyckya73a6542006-10-03 15:19:11 +00002506 }
Nick Lewycky05450ae2006-08-28 22:44:55 +00002507 }
Nick Lewycky05450ae2006-08-28 22:44:55 +00002508
Nick Lewycky565706b2006-11-22 23:49:16 +00002509 void PredicateSimplifier::Forwards::visitAllocaInst(AllocaInst &AI) {
Nick Lewycky29a05b62007-07-05 03:15:00 +00002510 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &AI);
Owen Andersone922c022009-07-22 00:24:57 +00002511 VRP.add(AI.getContext().getNullValue(AI.getType()),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002512 &AI, ICmpInst::ICMP_NE);
Nick Lewycky565706b2006-11-22 23:49:16 +00002513 VRP.solve();
2514 }
Nick Lewycky802fe272006-10-22 19:53:27 +00002515
Nick Lewycky565706b2006-11-22 23:49:16 +00002516 void PredicateSimplifier::Forwards::visitLoadInst(LoadInst &LI) {
2517 Value *Ptr = LI.getPointerOperand();
Nick Lewycky79cce5c2008-10-24 04:00:26 +00002518 // avoid "load i8* null" -> null NE null.
Nick Lewycky565706b2006-11-22 23:49:16 +00002519 if (isa<Constant>(Ptr)) return;
Nick Lewycky05450ae2006-08-28 22:44:55 +00002520
Nick Lewycky29a05b62007-07-05 03:15:00 +00002521 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &LI);
Owen Andersone922c022009-07-22 00:24:57 +00002522 VRP.add(LI.getContext().getNullValue(Ptr->getType()),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002523 Ptr, ICmpInst::ICMP_NE);
Nick Lewycky565706b2006-11-22 23:49:16 +00002524 VRP.solve();
2525 }
Nick Lewycky05450ae2006-08-28 22:44:55 +00002526
Nick Lewycky565706b2006-11-22 23:49:16 +00002527 void PredicateSimplifier::Forwards::visitStoreInst(StoreInst &SI) {
2528 Value *Ptr = SI.getPointerOperand();
2529 if (isa<Constant>(Ptr)) return;
Nick Lewycky05450ae2006-08-28 22:44:55 +00002530
Nick Lewycky29a05b62007-07-05 03:15:00 +00002531 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
Owen Andersone922c022009-07-22 00:24:57 +00002532 VRP.add(SI.getContext().getNullValue(Ptr->getType()),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002533 Ptr, ICmpInst::ICMP_NE);
Nick Lewycky565706b2006-11-22 23:49:16 +00002534 VRP.solve();
2535 }
2536
Nick Lewycky45351752007-02-04 23:43:05 +00002537 void PredicateSimplifier::Forwards::visitSExtInst(SExtInst &SI) {
Nick Lewycky29a05b62007-07-05 03:15:00 +00002538 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
Owen Andersoneed707b2009-07-24 23:12:02 +00002539 LLVMContext &Context = SI.getContext();
Reid Spenceraf3e9462007-03-03 00:48:31 +00002540 uint32_t SrcBitWidth = cast<IntegerType>(SI.getSrcTy())->getBitWidth();
2541 uint32_t DstBitWidth = cast<IntegerType>(SI.getDestTy())->getBitWidth();
Zhou Sheng223d65b2007-04-19 05:35:00 +00002542 APInt Min(APInt::getHighBitsSet(DstBitWidth, DstBitWidth-SrcBitWidth+1));
2543 APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth-1));
Owen Andersoneed707b2009-07-24 23:12:02 +00002544 VRP.add(ConstantInt::get(Context, Min), &SI, ICmpInst::ICMP_SLE);
2545 VRP.add(ConstantInt::get(Context, Max), &SI, ICmpInst::ICMP_SGE);
Nick Lewycky45351752007-02-04 23:43:05 +00002546 VRP.solve();
2547 }
2548
2549 void PredicateSimplifier::Forwards::visitZExtInst(ZExtInst &ZI) {
Nick Lewycky29a05b62007-07-05 03:15:00 +00002550 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &ZI);
Owen Andersoneed707b2009-07-24 23:12:02 +00002551 LLVMContext &Context = ZI.getContext();
Reid Spenceraf3e9462007-03-03 00:48:31 +00002552 uint32_t SrcBitWidth = cast<IntegerType>(ZI.getSrcTy())->getBitWidth();
2553 uint32_t DstBitWidth = cast<IntegerType>(ZI.getDestTy())->getBitWidth();
Zhou Sheng223d65b2007-04-19 05:35:00 +00002554 APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth));
Owen Andersoneed707b2009-07-24 23:12:02 +00002555 VRP.add(ConstantInt::get(Context, Max), &ZI, ICmpInst::ICMP_UGE);
Nick Lewycky45351752007-02-04 23:43:05 +00002556 VRP.solve();
2557 }
2558
Nick Lewycky565706b2006-11-22 23:49:16 +00002559 void PredicateSimplifier::Forwards::visitBinaryOperator(BinaryOperator &BO) {
2560 Instruction::BinaryOps ops = BO.getOpcode();
2561
2562 switch (ops) {
Nick Lewycky4c708752007-03-16 02:37:39 +00002563 default: break;
Nick Lewycky45351752007-02-04 23:43:05 +00002564 case Instruction::URem:
2565 case Instruction::SRem:
2566 case Instruction::UDiv:
2567 case Instruction::SDiv: {
2568 Value *Divisor = BO.getOperand(1);
Nick Lewycky29a05b62007-07-05 03:15:00 +00002569 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Owen Andersone922c022009-07-22 00:24:57 +00002570 VRP.add(BO.getContext().getNullValue(Divisor->getType()),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002571 Divisor, ICmpInst::ICMP_NE);
Nick Lewycky45351752007-02-04 23:43:05 +00002572 VRP.solve();
2573 break;
2574 }
Nick Lewycky4c708752007-03-16 02:37:39 +00002575 }
2576
2577 switch (ops) {
2578 default: break;
2579 case Instruction::Shl: {
Nick Lewycky29a05b62007-07-05 03:15:00 +00002580 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4c708752007-03-16 02:37:39 +00002581 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
2582 VRP.solve();
2583 } break;
2584 case Instruction::AShr: {
Nick Lewycky29a05b62007-07-05 03:15:00 +00002585 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4c708752007-03-16 02:37:39 +00002586 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_SLE);
2587 VRP.solve();
2588 } break;
2589 case Instruction::LShr:
2590 case Instruction::UDiv: {
Nick Lewycky29a05b62007-07-05 03:15:00 +00002591 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4c708752007-03-16 02:37:39 +00002592 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
2593 VRP.solve();
2594 } break;
2595 case Instruction::URem: {
Nick Lewycky29a05b62007-07-05 03:15:00 +00002596 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4c708752007-03-16 02:37:39 +00002597 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
2598 VRP.solve();
2599 } break;
2600 case Instruction::And: {
Nick Lewycky29a05b62007-07-05 03:15:00 +00002601 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4c708752007-03-16 02:37:39 +00002602 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
2603 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
2604 VRP.solve();
2605 } break;
2606 case Instruction::Or: {
Nick Lewycky29a05b62007-07-05 03:15:00 +00002607 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
Nick Lewycky4c708752007-03-16 02:37:39 +00002608 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
2609 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_UGE);
2610 VRP.solve();
2611 } break;
2612 }
2613 }
2614
2615 void PredicateSimplifier::Forwards::visitICmpInst(ICmpInst &IC) {
2616 // If possible, squeeze the ICmp predicate into something simpler.
2617 // Eg., if x = [0, 4) and we're being asked icmp uge %x, 3 then change
2618 // the predicate to eq.
2619
Nick Lewycky8ac40dd2007-04-07 02:30:14 +00002620 // XXX: once we do full PHI handling, modifying the instruction in the
2621 // Forwards visitor will cause missed optimizations.
2622
Nick Lewycky4c708752007-03-16 02:37:39 +00002623 ICmpInst::Predicate Pred = IC.getPredicate();
2624
Nick Lewycky8ac40dd2007-04-07 02:30:14 +00002625 switch (Pred) {
2626 default: break;
2627 case ICmpInst::ICMP_ULE: Pred = ICmpInst::ICMP_ULT; break;
2628 case ICmpInst::ICMP_UGE: Pred = ICmpInst::ICMP_UGT; break;
2629 case ICmpInst::ICMP_SLE: Pred = ICmpInst::ICMP_SLT; break;
2630 case ICmpInst::ICMP_SGE: Pred = ICmpInst::ICMP_SGT; break;
2631 }
2632 if (Pred != IC.getPredicate()) {
Nick Lewycky29a05b62007-07-05 03:15:00 +00002633 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &IC);
Nick Lewycky8ac40dd2007-04-07 02:30:14 +00002634 if (VRP.isRelatedBy(IC.getOperand(1), IC.getOperand(0),
2635 ICmpInst::ICMP_NE)) {
2636 ++NumSnuggle;
2637 PS->modified = true;
2638 IC.setPredicate(Pred);
2639 }
2640 }
2641
2642 Pred = IC.getPredicate();
2643
Owen Andersoneed707b2009-07-24 23:12:02 +00002644 LLVMContext &Context = IC.getContext();
Owen Anderson001dbfe2009-07-16 18:04:31 +00002645
Nick Lewycky4c708752007-03-16 02:37:39 +00002646 if (ConstantInt *Op1 = dyn_cast<ConstantInt>(IC.getOperand(1))) {
2647 ConstantInt *NextVal = 0;
Nick Lewycky8ac40dd2007-04-07 02:30:14 +00002648 switch (Pred) {
Nick Lewycky4c708752007-03-16 02:37:39 +00002649 default: break;
2650 case ICmpInst::ICMP_SLT:
2651 case ICmpInst::ICMP_ULT:
2652 if (Op1->getValue() != 0)
Owen Andersoneed707b2009-07-24 23:12:02 +00002653 NextVal = ConstantInt::get(Context, Op1->getValue()-1);
Nick Lewycky4c708752007-03-16 02:37:39 +00002654 break;
2655 case ICmpInst::ICMP_SGT:
2656 case ICmpInst::ICMP_UGT:
2657 if (!Op1->getValue().isAllOnesValue())
Owen Andersoneed707b2009-07-24 23:12:02 +00002658 NextVal = ConstantInt::get(Context, Op1->getValue()+1);
Nick Lewycky4c708752007-03-16 02:37:39 +00002659 break;
Nick Lewycky4c708752007-03-16 02:37:39 +00002660 }
Nick Lewycky79cce5c2008-10-24 04:00:26 +00002661
Nick Lewycky4c708752007-03-16 02:37:39 +00002662 if (NextVal) {
Nick Lewycky29a05b62007-07-05 03:15:00 +00002663 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &IC);
Nick Lewycky4c708752007-03-16 02:37:39 +00002664 if (VRP.isRelatedBy(IC.getOperand(0), NextVal,
2665 ICmpInst::getInversePredicate(Pred))) {
Owen Anderson333c4002009-07-09 23:48:35 +00002666 ICmpInst *NewIC = new ICmpInst(&IC, ICmpInst::ICMP_EQ,
2667 IC.getOperand(0), NextVal, "");
Nick Lewycky4c708752007-03-16 02:37:39 +00002668 NewIC->takeName(&IC);
2669 IC.replaceAllUsesWith(NewIC);
Nick Lewycky29a05b62007-07-05 03:15:00 +00002670
2671 // XXX: prove this isn't necessary
2672 if (unsigned n = VN.valueNumber(&IC, PS->DTDFS->getRootNode()))
2673 if (VN.value(n) == &IC) IG.remove(n);
2674 VN.remove(&IC);
2675
Nick Lewycky4c708752007-03-16 02:37:39 +00002676 IC.eraseFromParent();
2677 ++NumSnuggle;
2678 PS->modified = true;
Nick Lewycky4c708752007-03-16 02:37:39 +00002679 }
2680 }
2681 }
Nick Lewycky3947a762006-08-30 02:46:48 +00002682 }
Nick Lewycky565706b2006-11-22 23:49:16 +00002683}
2684
Dan Gohman844731a2008-05-13 00:00:25 +00002685char PredicateSimplifier::ID = 0;
2686static RegisterPass<PredicateSimplifier>
2687X("predsimplify", "Predicate Simplifier");
2688
Nick Lewycky565706b2006-11-22 23:49:16 +00002689FunctionPass *llvm::createPredicateSimplifierPass() {
2690 return new PredicateSimplifier();
Nick Lewycky05450ae2006-08-28 22:44:55 +00002691}