1 //===-- PredicateSimplifier.cpp - Path Sensitive Simplifier ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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:
14 // void test(int *p, int *q)
20 // foo(); // unreachable
23 //===----------------------------------------------------------------------===//
25 // 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
28 // are stored in a lattice; LE can become LT or EQ, NE can become LT or GT.
30 // 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
32 // 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.
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:
43 // with four nodes representing the properties. The InequalityGraph provides
44 // 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
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:
55 // %P = icmp ne i32* %ptr, null
57 // br i1 %a label %cond_true, label %cond_false
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
62 // branch it can't infer anything from the "and" instruction.
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.
69 //===----------------------------------------------------------------------===//
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
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
77 // relationship and better stored in the InequalityGraph, nor an empty range
78 // since that is better stored in UnreachableBlocks.
80 //===----------------------------------------------------------------------===//
82 #define DEBUG_TYPE "predsimplify"
83 #include "llvm/Transforms/Scalar.h"
84 #include "llvm/Constants.h"
85 #include "llvm/DerivedTypes.h"
86 #include "llvm/Instructions.h"
87 #include "llvm/Pass.h"
88 #include "llvm/ADT/DepthFirstIterator.h"
89 #include "llvm/ADT/SetOperations.h"
90 #include "llvm/ADT/SetVector.h"
91 #include "llvm/ADT/Statistic.h"
92 #include "llvm/ADT/STLExtras.h"
93 #include "llvm/Analysis/Dominators.h"
94 #include "llvm/Assembly/Writer.h"
95 #include "llvm/Support/CFG.h"
96 #include "llvm/Support/Compiler.h"
97 #include "llvm/Support/ConstantRange.h"
98 #include "llvm/Support/Debug.h"
99 #include "llvm/Support/InstVisitor.h"
100 #include "llvm/Support/raw_ostream.h"
101 #include "llvm/Target/TargetData.h"
102 #include "llvm/Transforms/Utils/Local.h"
106 using namespace llvm;
108 STATISTIC(NumVarsReplaced, "Number of argument substitutions");
109 STATISTIC(NumInstruction , "Number of instructions removed");
110 STATISTIC(NumSimple , "Number of simple replacements");
111 STATISTIC(NumBlocks , "Number of blocks marked unreachable");
112 STATISTIC(NumSnuggle , "Number of comparisons snuggled");
114 static const ConstantRange empty(1, false);
120 friend class DomTreeDFS;
122 typedef std::vector<Node *>::iterator iterator;
123 typedef std::vector<Node *>::const_iterator const_iterator;
125 unsigned getDFSNumIn() const { return DFSin; }
126 unsigned getDFSNumOut() const { return DFSout; }
128 BasicBlock *getBlock() const { return BB; }
130 iterator begin() { return Children.begin(); }
131 iterator end() { return Children.end(); }
133 const_iterator begin() const { return Children.begin(); }
134 const_iterator end() const { return Children.end(); }
136 bool dominates(const Node *N) const {
137 return DFSin <= N->DFSin && DFSout >= N->DFSout;
140 bool DominatedBy(const Node *N) const {
141 return N->dominates(this);
144 /// Sorts by the number of descendants. With this, you can iterate
145 /// through a sorted list and the first matching entry is the most
146 /// specific match for your basic block. The order provided is stable;
147 /// DomTreeDFS::Nodes with the same number of descendants are sorted by
149 bool operator<(const Node &N) const {
150 unsigned spread = DFSout - DFSin;
151 unsigned N_spread = N.DFSout - N.DFSin;
152 if (spread == N_spread) return DFSin < N.DFSin;
153 return spread < N_spread;
155 bool operator>(const Node &N) const { return N < *this; }
158 unsigned DFSin, DFSout;
161 std::vector<Node *> Children;
164 // XXX: this may be slow. Instead of using "new" for each node, consider
165 // putting them in a vector to keep them contiguous.
166 explicit DomTreeDFS(DominatorTree *DT) {
167 std::stack<std::pair<Node *, DomTreeNode *> > S;
170 Entry->BB = DT->getRootNode()->getBlock();
171 S.push(std::make_pair(Entry, DT->getRootNode()));
173 NodeMap[Entry->BB] = Entry;
176 std::pair<Node *, DomTreeNode *> &Pair = S.top();
177 Node *N = Pair.first;
178 DomTreeNode *DTNode = Pair.second;
181 for (DomTreeNode::iterator I = DTNode->begin(), E = DTNode->end();
183 Node *NewNode = new Node;
184 NewNode->BB = (*I)->getBlock();
185 N->Children.push_back(NewNode);
186 S.push(std::make_pair(NewNode, *I));
188 NodeMap[NewNode->BB] = NewNode;
203 std::stack<Node *> S;
207 Node *N = S.top(); S.pop();
209 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I)
216 /// getRootNode - This returns the entry node for the CFG of the function.
217 Node *getRootNode() const { return Entry; }
219 /// getNodeForBlock - return the node for the specified basic block.
220 Node *getNodeForBlock(BasicBlock *BB) const {
221 if (!NodeMap.count(BB)) return 0;
222 return const_cast<DomTreeDFS*>(this)->NodeMap[BB];
225 /// dominates - returns true if the basic block for I1 dominates that of
226 /// the basic block for I2. If the instructions belong to the same basic
227 /// block, the instruction first instruction sequentially in the block is
228 /// considered dominating.
229 bool dominates(Instruction *I1, Instruction *I2) {
230 BasicBlock *BB1 = I1->getParent(),
231 *BB2 = I2->getParent();
233 if (isa<TerminatorInst>(I1)) return false;
234 if (isa<TerminatorInst>(I2)) return true;
235 if ( isa<PHINode>(I1) && !isa<PHINode>(I2)) return true;
236 if (!isa<PHINode>(I1) && isa<PHINode>(I2)) return false;
238 for (BasicBlock::const_iterator I = BB2->begin(), E = BB2->end();
240 if (&*I == I1) return true;
241 else if (&*I == I2) return false;
243 assert(!"Instructions not found in parent BasicBlock?");
245 Node *Node1 = getNodeForBlock(BB1),
246 *Node2 = getNodeForBlock(BB2);
247 return Node1 && Node2 && Node1->dominates(Node2);
249 return false; // Not reached
253 /// renumber - calculates the depth first search numberings and applies
254 /// them onto the nodes.
256 std::stack<std::pair<Node *, Node::iterator> > S;
260 S.push(std::make_pair(Entry, Entry->begin()));
263 std::pair<Node *, Node::iterator> &Pair = S.top();
264 Node *N = Pair.first;
265 Node::iterator &I = Pair.second;
273 S.push(std::make_pair(Next, Next->begin()));
279 virtual void dump() const {
280 dump(*cerr.stream());
283 void dump(std::ostream &os) const {
284 os << "Predicate simplifier DomTreeDFS: \n";
289 void dump(Node *N, int depth, std::ostream &os) const {
291 for (int i = 0; i < depth; ++i) { os << " "; }
292 os << "[" << depth << "] ";
294 os << N->getBlock()->getNameStr() << " (" << N->getDFSNumIn()
295 << ", " << N->getDFSNumOut() << ")\n";
297 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I)
303 std::map<BasicBlock *, Node *> NodeMap;
306 // SLT SGT ULT UGT EQ
307 // 0 1 0 1 0 -- GT 10
308 // 0 1 0 1 1 -- GE 11
309 // 0 1 1 0 0 -- SGTULT 12
310 // 0 1 1 0 1 -- SGEULE 13
311 // 0 1 1 1 0 -- SGT 14
312 // 0 1 1 1 1 -- SGE 15
313 // 1 0 0 1 0 -- SLTUGT 18
314 // 1 0 0 1 1 -- SLEUGE 19
315 // 1 0 1 0 0 -- LT 20
316 // 1 0 1 0 1 -- LE 21
317 // 1 0 1 1 0 -- SLT 22
318 // 1 0 1 1 1 -- SLE 23
319 // 1 1 0 1 0 -- UGT 26
320 // 1 1 0 1 1 -- UGE 27
321 // 1 1 1 0 0 -- ULT 28
322 // 1 1 1 0 1 -- ULE 29
323 // 1 1 1 1 0 -- NE 30
325 EQ_BIT = 1, UGT_BIT = 2, ULT_BIT = 4, SGT_BIT = 8, SLT_BIT = 16
328 GT = SGT_BIT | UGT_BIT,
330 LT = SLT_BIT | ULT_BIT,
332 NE = SLT_BIT | SGT_BIT | ULT_BIT | UGT_BIT,
333 SGTULT = SGT_BIT | ULT_BIT,
334 SGEULE = SGTULT | EQ_BIT,
335 SLTUGT = SLT_BIT | UGT_BIT,
336 SLEUGE = SLTUGT | EQ_BIT,
337 ULT = SLT_BIT | SGT_BIT | ULT_BIT,
338 UGT = SLT_BIT | SGT_BIT | UGT_BIT,
339 SLT = SLT_BIT | ULT_BIT | UGT_BIT,
340 SGT = SGT_BIT | ULT_BIT | UGT_BIT,
348 /// validPredicate - determines whether a given value is actually a lattice
349 /// value. Only used in assertions or debugging.
350 static bool validPredicate(LatticeVal LV) {
352 case GT: case GE: case LT: case LE: case NE:
353 case SGTULT: case SGT: case SGEULE:
354 case SLTUGT: case SLT: case SLEUGE:
356 case SLE: case SGE: case ULE: case UGE:
364 /// reversePredicate - reverse the direction of the inequality
365 static LatticeVal reversePredicate(LatticeVal LV) {
366 unsigned reverse = LV ^ (SLT_BIT|SGT_BIT|ULT_BIT|UGT_BIT); //preserve EQ_BIT
368 if ((reverse & (SLT_BIT|SGT_BIT)) == 0)
369 reverse |= (SLT_BIT|SGT_BIT);
371 if ((reverse & (ULT_BIT|UGT_BIT)) == 0)
372 reverse |= (ULT_BIT|UGT_BIT);
374 LatticeVal Rev = static_cast<LatticeVal>(reverse);
375 assert(validPredicate(Rev) && "Failed reversing predicate.");
379 /// ValueNumbering stores the scope-specific value numbers for a given Value.
380 class VISIBILITY_HIDDEN ValueNumbering {
382 /// VNPair is a tuple of {Value, index number, DomTreeDFS::Node}. It
383 /// includes the comparison operators necessary to allow you to store it
384 /// in a sorted vector.
385 class VISIBILITY_HIDDEN VNPair {
389 DomTreeDFS::Node *Subtree;
391 VNPair(Value *V, unsigned index, DomTreeDFS::Node *Subtree)
392 : V(V), index(index), Subtree(Subtree) {}
394 bool operator==(const VNPair &RHS) const {
395 return V == RHS.V && Subtree == RHS.Subtree;
398 bool operator<(const VNPair &RHS) const {
399 if (V != RHS.V) return V < RHS.V;
400 return *Subtree < *RHS.Subtree;
403 bool operator<(Value *RHS) const {
407 bool operator>(Value *RHS) const {
411 friend bool operator<(Value *RHS, const VNPair &pair) {
412 return pair.operator>(RHS);
416 typedef std::vector<VNPair> VNMapType;
419 /// The canonical choice for value number at index.
420 std::vector<Value *> Values;
426 virtual ~ValueNumbering() {}
427 virtual void dump() {
428 dump(*cerr.stream());
431 void dump(std::ostream &os) {
432 for (unsigned i = 1; i <= Values.size(); ++i) {
434 WriteAsOperand(os, Values[i-1]);
436 for (unsigned j = 0; j < VNMap.size(); ++j) {
437 if (VNMap[j].index == i) {
438 WriteAsOperand(os, VNMap[j].V);
439 os << " (" << VNMap[j].Subtree->getDFSNumIn() << ") ";
447 /// compare - returns true if V1 is a better canonical value than V2.
448 bool compare(Value *V1, Value *V2) const {
449 if (isa<Constant>(V1))
450 return !isa<Constant>(V2);
451 else if (isa<Constant>(V2))
453 else if (isa<Argument>(V1))
454 return !isa<Argument>(V2);
455 else if (isa<Argument>(V2))
458 Instruction *I1 = dyn_cast<Instruction>(V1);
459 Instruction *I2 = dyn_cast<Instruction>(V2);
462 return V1->getNumUses() < V2->getNumUses();
464 return DTDFS->dominates(I1, I2);
467 ValueNumbering(DomTreeDFS *DTDFS) : DTDFS(DTDFS) {}
469 /// valueNumber - finds the value number for V under the Subtree. If
470 /// there is no value number, returns zero.
471 unsigned valueNumber(Value *V, DomTreeDFS::Node *Subtree) {
472 if (!(isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) ||
473 V->getType() == Type::getVoidTy(V->getContext())) return 0;
475 VNMapType::iterator E = VNMap.end();
476 VNPair pair(V, 0, Subtree);
477 VNMapType::iterator I = std::lower_bound(VNMap.begin(), E, pair);
478 while (I != E && I->V == V) {
479 if (I->Subtree->dominates(Subtree))
486 /// getOrInsertVN - always returns a value number, creating it if necessary.
487 unsigned getOrInsertVN(Value *V, DomTreeDFS::Node *Subtree) {
488 if (unsigned n = valueNumber(V, Subtree))
494 /// newVN - creates a new value number. Value V must not already have a
495 /// value number assigned.
496 unsigned newVN(Value *V) {
497 assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
498 "Bad Value for value numbering.");
499 assert(V->getType() != Type::getVoidTy(V->getContext()) &&
500 "Won't value number a void value");
504 VNPair pair = VNPair(V, Values.size(), DTDFS->getRootNode());
505 VNMapType::iterator I = std::lower_bound(VNMap.begin(), VNMap.end(), pair);
506 assert((I == VNMap.end() || value(I->index) != V) &&
507 "Attempt to create a duplicate value number.");
508 VNMap.insert(I, pair);
510 return Values.size();
513 /// value - returns the Value associated with a value number.
514 Value *value(unsigned index) const {
515 assert(index != 0 && "Zero index is reserved for not found.");
516 assert(index <= Values.size() && "Index out of range.");
517 return Values[index-1];
520 /// canonicalize - return a Value that is equal to V under Subtree.
521 Value *canonicalize(Value *V, DomTreeDFS::Node *Subtree) {
522 if (isa<Constant>(V)) return V;
524 if (unsigned n = valueNumber(V, Subtree))
530 /// addEquality - adds that value V belongs to the set of equivalent
531 /// values defined by value number n under Subtree.
532 void addEquality(unsigned n, Value *V, DomTreeDFS::Node *Subtree) {
533 assert(canonicalize(value(n), Subtree) == value(n) &&
534 "Node's 'canonical' choice isn't best within this subtree.");
536 // Suppose that we are given "%x -> node #1 (%y)". The problem is that
537 // we may already have "%z -> node #2 (%x)" somewhere above us in the
538 // graph. We need to find those edges and add "%z -> node #1 (%y)"
539 // to keep the lookups canonical.
541 std::vector<Value *> ToRepoint(1, V);
543 if (unsigned Conflict = valueNumber(V, Subtree)) {
544 for (VNMapType::iterator I = VNMap.begin(), E = VNMap.end();
546 if (I->index == Conflict && I->Subtree->dominates(Subtree))
547 ToRepoint.push_back(I->V);
551 for (std::vector<Value *>::iterator VI = ToRepoint.begin(),
552 VE = ToRepoint.end(); VI != VE; ++VI) {
555 VNPair pair(V, n, Subtree);
556 VNMapType::iterator B = VNMap.begin(), E = VNMap.end();
557 VNMapType::iterator I = std::lower_bound(B, E, pair);
558 if (I != E && I->V == V && I->Subtree == Subtree)
559 I->index = n; // Update best choice
561 VNMap.insert(I, pair); // New Value
563 // XXX: we currently don't have to worry about updating values with
564 // more specific Subtrees, but we will need to for PHI node support.
567 Value *V_n = value(n);
568 if (isa<Constant>(V) && isa<Constant>(V_n)) {
569 assert(V == V_n && "Constant equals different constant?");
575 /// remove - removes all references to value V.
576 void remove(Value *V) {
577 VNMapType::iterator B = VNMap.begin(), E = VNMap.end();
578 VNPair pair(V, 0, DTDFS->getRootNode());
579 VNMapType::iterator J = std::upper_bound(B, E, pair);
580 VNMapType::iterator I = J;
582 while (I != B && (I == E || I->V == V)) --I;
588 /// The InequalityGraph stores the relationships between values.
589 /// Each Value in the graph is assigned to a Node. Nodes are pointer
590 /// comparable for equality. The caller is expected to maintain the logical
591 /// consistency of the system.
593 /// The InequalityGraph class may invalidate Node*s after any mutator call.
594 /// @brief The InequalityGraph stores the relationships between values.
595 class VISIBILITY_HIDDEN InequalityGraph {
597 DomTreeDFS::Node *TreeRoot;
599 InequalityGraph(); // DO NOT IMPLEMENT
600 InequalityGraph(InequalityGraph &); // DO NOT IMPLEMENT
602 InequalityGraph(ValueNumbering &VN, DomTreeDFS::Node *TreeRoot)
603 : VN(VN), TreeRoot(TreeRoot) {}
607 /// An Edge is contained inside a Node making one end of the edge implicit
608 /// and contains a pointer to the other end. The edge contains a lattice
609 /// value specifying the relationship and an DomTreeDFS::Node specifying
610 /// the root in the dominator tree to which this edge applies.
611 class VISIBILITY_HIDDEN Edge {
613 Edge(unsigned T, LatticeVal V, DomTreeDFS::Node *ST)
614 : To(T), LV(V), Subtree(ST) {}
618 DomTreeDFS::Node *Subtree;
620 bool operator<(const Edge &edge) const {
621 if (To != edge.To) return To < edge.To;
622 return *Subtree < *edge.Subtree;
625 bool operator<(unsigned to) const {
629 bool operator>(unsigned to) const {
633 friend bool operator<(unsigned to, const Edge &edge) {
634 return edge.operator>(to);
638 /// A single node in the InequalityGraph. This stores the canonical Value
639 /// for the node, as well as the relationships with the neighbours.
641 /// @brief A single node in the InequalityGraph.
642 class VISIBILITY_HIDDEN Node {
643 friend class InequalityGraph;
645 typedef SmallVector<Edge, 4> RelationsType;
646 RelationsType Relations;
648 // TODO: can this idea improve performance?
649 //friend class std::vector<Node>;
650 //Node(Node &N) { RelationsType.swap(N.RelationsType); }
653 typedef RelationsType::iterator iterator;
654 typedef RelationsType::const_iterator const_iterator;
658 virtual void dump() const {
659 dump(*cerr.stream());
662 void dump(std::ostream &os) const {
663 static const std::string names[32] =
664 { "000000", "000001", "000002", "000003", "000004", "000005",
665 "000006", "000007", "000008", "000009", " >", " >=",
666 " s>u<", "s>=u<=", " s>", " s>=", "000016", "000017",
667 " s<u>", "s<=u>=", " <", " <=", " s<", " s<=",
668 "000024", "000025", " u>", " u>=", " u<", " u<=",
670 for (Node::const_iterator NI = begin(), NE = end(); NI != NE; ++NI) {
671 os << names[NI->LV] << " " << NI->To
672 << " (" << NI->Subtree->getDFSNumIn() << "), ";
678 iterator begin() { return Relations.begin(); }
679 iterator end() { return Relations.end(); }
680 const_iterator begin() const { return Relations.begin(); }
681 const_iterator end() const { return Relations.end(); }
683 iterator find(unsigned n, DomTreeDFS::Node *Subtree) {
685 for (iterator I = std::lower_bound(begin(), E, n);
686 I != E && I->To == n; ++I) {
687 if (Subtree->DominatedBy(I->Subtree))
693 const_iterator find(unsigned n, DomTreeDFS::Node *Subtree) const {
694 const_iterator E = end();
695 for (const_iterator I = std::lower_bound(begin(), E, n);
696 I != E && I->To == n; ++I) {
697 if (Subtree->DominatedBy(I->Subtree))
703 /// update - updates the lattice value for a given node, creating a new
704 /// entry if one doesn't exist. The new lattice value must not be
705 /// inconsistent with any previously existing value.
706 void update(unsigned n, LatticeVal R, DomTreeDFS::Node *Subtree) {
707 assert(validPredicate(R) && "Invalid predicate.");
709 Edge edge(n, R, Subtree);
710 iterator B = begin(), E = end();
711 iterator I = std::lower_bound(B, E, edge);
714 while (J != E && J->To == n) {
715 if (Subtree->DominatedBy(J->Subtree))
720 if (J != E && J->To == n) {
721 edge.LV = static_cast<LatticeVal>(J->LV & R);
722 assert(validPredicate(edge.LV) && "Invalid union of lattice values.");
724 if (edge.LV == J->LV)
725 return; // This update adds nothing new.
729 // We also have to tighten any edge beneath our update.
730 for (iterator K = I - 1; K->To == n; --K) {
731 if (K->Subtree->DominatedBy(Subtree)) {
732 LatticeVal LV = static_cast<LatticeVal>(K->LV & edge.LV);
733 assert(validPredicate(LV) && "Invalid union of lattice values");
740 // Insert new edge at Subtree if it isn't already there.
741 if (I == E || I->To != n || Subtree != I->Subtree)
742 Relations.insert(I, edge);
748 std::vector<Node> Nodes;
751 /// node - returns the node object at a given value number. The pointer
752 /// returned may be invalidated on the next call to node().
753 Node *node(unsigned index) {
754 assert(VN.value(index)); // This triggers the necessary checks.
755 if (Nodes.size() < index) Nodes.resize(index);
756 return &Nodes[index-1];
759 /// isRelatedBy - true iff n1 op n2
760 bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
762 if (n1 == n2) return LV & EQ_BIT;
765 Node::iterator I = N1->find(n2, Subtree), E = N1->end();
766 if (I != E) return (I->LV & LV) == I->LV;
771 // The add* methods assume that your input is logically valid and may
772 // assertion-fail or infinitely loop if you attempt a contradiction.
774 /// addInequality - Sets n1 op n2.
775 /// It is also an error to call this on an inequality that is already true.
776 void addInequality(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
778 assert(n1 != n2 && "A node can't be inequal to itself.");
781 assert(!isRelatedBy(n1, n2, Subtree, reversePredicate(LV1)) &&
782 "Contradictory inequality.");
784 // Suppose we're adding %n1 < %n2. Find all the %a < %n1 and
785 // add %a < %n2 too. This keeps the graph fully connected.
787 // Break up the relationship into signed and unsigned comparison parts.
788 // If the signed parts of %a op1 %n1 match that of %n1 op2 %n2, and
789 // op1 and op2 aren't NE, then add %a op3 %n2. The new relationship
790 // should have the EQ_BIT iff it's set for both op1 and op2.
792 unsigned LV1_s = LV1 & (SLT_BIT|SGT_BIT);
793 unsigned LV1_u = LV1 & (ULT_BIT|UGT_BIT);
795 for (Node::iterator I = node(n1)->begin(), E = node(n1)->end(); I != E; ++I) {
796 if (I->LV != NE && I->To != n2) {
798 DomTreeDFS::Node *Local_Subtree = NULL;
799 if (Subtree->DominatedBy(I->Subtree))
800 Local_Subtree = Subtree;
801 else if (I->Subtree->DominatedBy(Subtree))
802 Local_Subtree = I->Subtree;
805 unsigned new_relationship = 0;
806 LatticeVal ILV = reversePredicate(I->LV);
807 unsigned ILV_s = ILV & (SLT_BIT|SGT_BIT);
808 unsigned ILV_u = ILV & (ULT_BIT|UGT_BIT);
810 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
811 new_relationship |= ILV_s;
812 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
813 new_relationship |= ILV_u;
815 if (new_relationship) {
816 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
817 new_relationship |= (SLT_BIT|SGT_BIT);
818 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
819 new_relationship |= (ULT_BIT|UGT_BIT);
820 if ((LV1 & EQ_BIT) && (ILV & EQ_BIT))
821 new_relationship |= EQ_BIT;
823 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
825 node(I->To)->update(n2, NewLV, Local_Subtree);
826 node(n2)->update(I->To, reversePredicate(NewLV), Local_Subtree);
832 for (Node::iterator I = node(n2)->begin(), E = node(n2)->end(); I != E; ++I) {
833 if (I->LV != NE && I->To != n1) {
834 DomTreeDFS::Node *Local_Subtree = NULL;
835 if (Subtree->DominatedBy(I->Subtree))
836 Local_Subtree = Subtree;
837 else if (I->Subtree->DominatedBy(Subtree))
838 Local_Subtree = I->Subtree;
841 unsigned new_relationship = 0;
842 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
843 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
845 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
846 new_relationship |= ILV_s;
848 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
849 new_relationship |= ILV_u;
851 if (new_relationship) {
852 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
853 new_relationship |= (SLT_BIT|SGT_BIT);
854 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
855 new_relationship |= (ULT_BIT|UGT_BIT);
856 if ((LV1 & EQ_BIT) && (I->LV & EQ_BIT))
857 new_relationship |= EQ_BIT;
859 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
861 node(n1)->update(I->To, NewLV, Local_Subtree);
862 node(I->To)->update(n1, reversePredicate(NewLV), Local_Subtree);
869 node(n1)->update(n2, LV1, Subtree);
870 node(n2)->update(n1, reversePredicate(LV1), Subtree);
873 /// remove - removes a node from the graph by removing all references to
875 void remove(unsigned n) {
877 for (Node::iterator NI = N->begin(), NE = N->end(); NI != NE; ++NI) {
878 Node::iterator Iter = node(NI->To)->find(n, TreeRoot);
880 node(NI->To)->Relations.erase(Iter);
881 Iter = node(NI->To)->find(n, TreeRoot);
882 } while (Iter != node(NI->To)->end());
884 N->Relations.clear();
888 virtual ~InequalityGraph() {}
889 virtual void dump() {
890 dump(*cerr.stream());
893 void dump(std::ostream &os) {
894 for (unsigned i = 1; i <= Nodes.size(); ++i) {
905 /// ValueRanges tracks the known integer ranges and anti-ranges of the nodes
906 /// in the InequalityGraph.
907 class VISIBILITY_HIDDEN ValueRanges {
910 LLVMContext *Context;
912 class VISIBILITY_HIDDEN ScopedRange {
913 typedef std::vector<std::pair<DomTreeDFS::Node *, ConstantRange> >
915 RangeListType RangeList;
917 static bool swo(const std::pair<DomTreeDFS::Node *, ConstantRange> &LHS,
918 const std::pair<DomTreeDFS::Node *, ConstantRange> &RHS) {
919 return *LHS.first < *RHS.first;
924 virtual ~ScopedRange() {}
925 virtual void dump() const {
926 dump(*cerr.stream());
929 void dump(std::ostream &os) const {
931 for (const_iterator I = begin(), E = end(); I != E; ++I) {
932 os << &I->second << " (" << I->first->getDFSNumIn() << "), ";
938 typedef RangeListType::iterator iterator;
939 typedef RangeListType::const_iterator const_iterator;
941 iterator begin() { return RangeList.begin(); }
942 iterator end() { return RangeList.end(); }
943 const_iterator begin() const { return RangeList.begin(); }
944 const_iterator end() const { return RangeList.end(); }
946 iterator find(DomTreeDFS::Node *Subtree) {
948 iterator I = std::lower_bound(begin(), E,
949 std::make_pair(Subtree, empty), swo);
951 while (I != E && !I->first->dominates(Subtree)) ++I;
955 const_iterator find(DomTreeDFS::Node *Subtree) const {
956 const_iterator E = end();
957 const_iterator I = std::lower_bound(begin(), E,
958 std::make_pair(Subtree, empty), swo);
960 while (I != E && !I->first->dominates(Subtree)) ++I;
964 void update(const ConstantRange &CR, DomTreeDFS::Node *Subtree) {
965 assert(!CR.isEmptySet() && "Empty ConstantRange.");
966 assert(!CR.isSingleElement() && "Refusing to store single element.");
970 std::lower_bound(begin(), E, std::make_pair(Subtree, empty), swo);
972 if (I != end() && I->first == Subtree) {
973 ConstantRange CR2 = I->second.intersectWith(CR);
974 assert(!CR2.isEmptySet() && !CR2.isSingleElement() &&
975 "Invalid union of ranges.");
978 RangeList.insert(I, std::make_pair(Subtree, CR));
982 std::vector<ScopedRange> Ranges;
984 void update(unsigned n, const ConstantRange &CR, DomTreeDFS::Node *Subtree){
985 if (CR.isFullSet()) return;
986 if (Ranges.size() < n) Ranges.resize(n);
987 Ranges[n-1].update(CR, Subtree);
990 /// create - Creates a ConstantRange that matches the given LatticeVal
991 /// relation with a given integer.
992 ConstantRange create(LatticeVal LV, const ConstantRange &CR) {
993 assert(!CR.isEmptySet() && "Can't deal with empty set.");
996 return ConstantRange::makeICmpRegion(ICmpInst::ICMP_NE, CR);
998 unsigned LV_s = LV & (SGT_BIT|SLT_BIT);
999 unsigned LV_u = LV & (UGT_BIT|ULT_BIT);
1000 bool hasEQ = LV & EQ_BIT;
1002 ConstantRange Range(CR.getBitWidth());
1004 if (LV_s == SGT_BIT) {
1005 Range = Range.intersectWith(ConstantRange::makeICmpRegion(
1006 hasEQ ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_SGT, CR));
1007 } else if (LV_s == SLT_BIT) {
1008 Range = Range.intersectWith(ConstantRange::makeICmpRegion(
1009 hasEQ ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_SLT, CR));
1012 if (LV_u == UGT_BIT) {
1013 Range = Range.intersectWith(ConstantRange::makeICmpRegion(
1014 hasEQ ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_UGT, CR));
1015 } else if (LV_u == ULT_BIT) {
1016 Range = Range.intersectWith(ConstantRange::makeICmpRegion(
1017 hasEQ ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT, CR));
1024 bool isCanonical(Value *V, DomTreeDFS::Node *Subtree) {
1025 return V == VN.canonicalize(V, Subtree);
1031 ValueRanges(ValueNumbering &VN, TargetData *TD, LLVMContext *C) :
1032 VN(VN), TD(TD), Context(C) {}
1035 virtual ~ValueRanges() {}
1037 virtual void dump() const {
1038 dump(*cerr.stream());
1041 void dump(std::ostream &os) const {
1042 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1043 os << (i+1) << " = ";
1050 /// range - looks up the ConstantRange associated with a value number.
1051 ConstantRange range(unsigned n, DomTreeDFS::Node *Subtree) {
1052 assert(VN.value(n)); // performs range checks
1054 if (n <= Ranges.size()) {
1055 ScopedRange::iterator I = Ranges[n-1].find(Subtree);
1056 if (I != Ranges[n-1].end()) return I->second;
1059 Value *V = VN.value(n);
1060 ConstantRange CR = range(V);
1064 /// range - determine a range from a Value without performing any lookups.
1065 ConstantRange range(Value *V) const {
1066 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
1067 return ConstantRange(C->getValue());
1068 else if (isa<ConstantPointerNull>(V))
1069 return ConstantRange(APInt::getNullValue(typeToWidth(V->getType())));
1071 return ConstantRange(typeToWidth(V->getType()));
1074 // typeToWidth - returns the number of bits necessary to store a value of
1075 // this type, or zero if unknown.
1076 uint32_t typeToWidth(const Type *Ty) const {
1078 return TD->getTypeSizeInBits(Ty);
1080 return Ty->getPrimitiveSizeInBits();
1083 static bool isRelatedBy(const ConstantRange &CR1, const ConstantRange &CR2,
1086 default: assert(!"Impossible lattice value!");
1088 return CR1.intersectWith(CR2).isEmptySet();
1090 return CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
1092 return CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
1094 return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
1096 return CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
1098 return CR1.getSignedMax().slt(CR2.getSignedMin());
1100 return CR1.getSignedMax().sle(CR2.getSignedMin());
1102 return CR1.getSignedMin().sgt(CR2.getSignedMax());
1104 return CR1.getSignedMin().sge(CR2.getSignedMax());
1106 return CR1.getUnsignedMax().ult(CR2.getUnsignedMin()) &&
1107 CR1.getSignedMax().slt(CR2.getUnsignedMin());
1109 return CR1.getUnsignedMax().ule(CR2.getUnsignedMin()) &&
1110 CR1.getSignedMax().sle(CR2.getUnsignedMin());
1112 return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax()) &&
1113 CR1.getSignedMin().sgt(CR2.getSignedMax());
1115 return CR1.getUnsignedMin().uge(CR2.getUnsignedMax()) &&
1116 CR1.getSignedMin().sge(CR2.getSignedMax());
1118 return CR1.getSignedMax().slt(CR2.getSignedMin()) &&
1119 CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
1121 return CR1.getSignedMax().sle(CR2.getSignedMin()) &&
1122 CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
1124 return CR1.getSignedMin().sgt(CR2.getSignedMax()) &&
1125 CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
1127 return CR1.getSignedMin().sge(CR2.getSignedMax()) &&
1128 CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
1132 bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
1134 ConstantRange CR1 = range(n1, Subtree);
1135 ConstantRange CR2 = range(n2, Subtree);
1137 // True iff all values in CR1 are LV to all values in CR2.
1138 return isRelatedBy(CR1, CR2, LV);
1141 void addToWorklist(Value *V, Constant *C, ICmpInst::Predicate Pred,
1143 void markBlock(VRPSolver *VRP);
1145 void mergeInto(Value **I, unsigned n, unsigned New,
1146 DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
1147 ConstantRange CR_New = range(New, Subtree);
1148 ConstantRange Merged = CR_New;
1150 for (; n != 0; ++I, --n) {
1151 unsigned i = VN.valueNumber(*I, Subtree);
1152 ConstantRange CR_Kill = i ? range(i, Subtree) : range(*I);
1153 if (CR_Kill.isFullSet()) continue;
1154 Merged = Merged.intersectWith(CR_Kill);
1157 if (Merged.isFullSet() || Merged == CR_New) return;
1159 applyRange(New, Merged, Subtree, VRP);
1162 void applyRange(unsigned n, const ConstantRange &CR,
1163 DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
1164 ConstantRange Merged = CR.intersectWith(range(n, Subtree));
1165 if (Merged.isEmptySet()) {
1170 if (const APInt *I = Merged.getSingleElement()) {
1171 Value *V = VN.value(n); // XXX: redesign worklist.
1172 const Type *Ty = V->getType();
1173 if (Ty->isInteger()) {
1174 addToWorklist(V, ConstantInt::get(*Context, *I),
1175 ICmpInst::ICMP_EQ, VRP);
1177 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1178 assert(*I == 0 && "Pointer is null but not zero?");
1179 addToWorklist(V, ConstantPointerNull::get(PTy),
1180 ICmpInst::ICMP_EQ, VRP);
1185 update(n, Merged, Subtree);
1188 void addNotEquals(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
1190 ConstantRange CR1 = range(n1, Subtree);
1191 ConstantRange CR2 = range(n2, Subtree);
1193 uint32_t W = CR1.getBitWidth();
1195 if (const APInt *I = CR1.getSingleElement()) {
1196 if (CR2.isFullSet()) {
1197 ConstantRange NewCR2(CR1.getUpper(), CR1.getLower());
1198 applyRange(n2, NewCR2, Subtree, VRP);
1199 } else if (*I == CR2.getLower()) {
1200 APInt NewLower(CR2.getLower() + 1),
1201 NewUpper(CR2.getUpper());
1202 if (NewLower == NewUpper)
1203 NewLower = NewUpper = APInt::getMinValue(W);
1205 ConstantRange NewCR2(NewLower, NewUpper);
1206 applyRange(n2, NewCR2, Subtree, VRP);
1207 } else if (*I == CR2.getUpper() - 1) {
1208 APInt NewLower(CR2.getLower()),
1209 NewUpper(CR2.getUpper() - 1);
1210 if (NewLower == NewUpper)
1211 NewLower = NewUpper = APInt::getMinValue(W);
1213 ConstantRange NewCR2(NewLower, NewUpper);
1214 applyRange(n2, NewCR2, Subtree, VRP);
1218 if (const APInt *I = CR2.getSingleElement()) {
1219 if (CR1.isFullSet()) {
1220 ConstantRange NewCR1(CR2.getUpper(), CR2.getLower());
1221 applyRange(n1, NewCR1, Subtree, VRP);
1222 } else if (*I == CR1.getLower()) {
1223 APInt NewLower(CR1.getLower() + 1),
1224 NewUpper(CR1.getUpper());
1225 if (NewLower == NewUpper)
1226 NewLower = NewUpper = APInt::getMinValue(W);
1228 ConstantRange NewCR1(NewLower, NewUpper);
1229 applyRange(n1, NewCR1, Subtree, VRP);
1230 } else if (*I == CR1.getUpper() - 1) {
1231 APInt NewLower(CR1.getLower()),
1232 NewUpper(CR1.getUpper() - 1);
1233 if (NewLower == NewUpper)
1234 NewLower = NewUpper = APInt::getMinValue(W);
1236 ConstantRange NewCR1(NewLower, NewUpper);
1237 applyRange(n1, NewCR1, Subtree, VRP);
1242 void addInequality(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
1243 LatticeVal LV, VRPSolver *VRP) {
1244 assert(!isRelatedBy(n1, n2, Subtree, LV) && "Asked to do useless work.");
1247 addNotEquals(n1, n2, Subtree, VRP);
1251 ConstantRange CR1 = range(n1, Subtree);
1252 ConstantRange CR2 = range(n2, Subtree);
1254 if (!CR1.isSingleElement()) {
1255 ConstantRange NewCR1 = CR1.intersectWith(create(LV, CR2));
1257 applyRange(n1, NewCR1, Subtree, VRP);
1260 if (!CR2.isSingleElement()) {
1261 ConstantRange NewCR2 = CR2.intersectWith(
1262 create(reversePredicate(LV), CR1));
1264 applyRange(n2, NewCR2, Subtree, VRP);
1269 /// UnreachableBlocks keeps tracks of blocks that are for one reason or
1270 /// another discovered to be unreachable. This is used to cull the graph when
1271 /// analyzing instructions, and to mark blocks with the "unreachable"
1272 /// terminator instruction after the function has executed.
1273 class VISIBILITY_HIDDEN UnreachableBlocks {
1275 std::vector<BasicBlock *> DeadBlocks;
1278 /// mark - mark a block as dead
1279 void mark(BasicBlock *BB) {
1280 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
1281 std::vector<BasicBlock *>::iterator I =
1282 std::lower_bound(DeadBlocks.begin(), E, BB);
1284 if (I == E || *I != BB) DeadBlocks.insert(I, BB);
1287 /// isDead - returns whether a block is known to be dead already
1288 bool isDead(BasicBlock *BB) {
1289 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
1290 std::vector<BasicBlock *>::iterator I =
1291 std::lower_bound(DeadBlocks.begin(), E, BB);
1293 return I != E && *I == BB;
1296 /// kill - replace the dead blocks' terminator with an UnreachableInst.
1298 bool modified = false;
1299 for (std::vector<BasicBlock *>::iterator I = DeadBlocks.begin(),
1300 E = DeadBlocks.end(); I != E; ++I) {
1301 BasicBlock *BB = *I;
1303 DEBUG(errs() << "unreachable block: " << BB->getName() << "\n");
1305 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
1307 BasicBlock *Succ = *SI;
1308 Succ->removePredecessor(BB);
1311 TerminatorInst *TI = BB->getTerminator();
1312 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1313 TI->eraseFromParent();
1314 new UnreachableInst(BB->getContext(), BB);
1323 /// VRPSolver keeps track of how changes to one variable affect other
1324 /// variables, and forwards changes along to the InequalityGraph. It
1325 /// also maintains the correct choice for "canonical" in the IG.
1326 /// @brief VRPSolver calculates inferences from a new relationship.
1327 class VISIBILITY_HIDDEN VRPSolver {
1329 friend class ValueRanges;
1333 ICmpInst::Predicate Op;
1335 BasicBlock *ContextBB; // XXX use a DomTreeDFS::Node instead
1336 Instruction *ContextInst;
1338 std::deque<Operation> WorkList;
1341 InequalityGraph &IG;
1342 UnreachableBlocks &UB;
1345 DomTreeDFS::Node *Top;
1347 Instruction *TopInst;
1349 LLVMContext *Context;
1351 typedef InequalityGraph::Node Node;
1353 // below - true if the Instruction is dominated by the current context
1354 // block or instruction
1355 bool below(Instruction *I) {
1356 BasicBlock *BB = I->getParent();
1357 if (TopInst && TopInst->getParent() == BB) {
1358 if (isa<TerminatorInst>(TopInst)) return false;
1359 if (isa<TerminatorInst>(I)) return true;
1360 if ( isa<PHINode>(TopInst) && !isa<PHINode>(I)) return true;
1361 if (!isa<PHINode>(TopInst) && isa<PHINode>(I)) return false;
1363 for (BasicBlock::const_iterator Iter = BB->begin(), E = BB->end();
1364 Iter != E; ++Iter) {
1365 if (&*Iter == TopInst) return true;
1366 else if (&*Iter == I) return false;
1368 assert(!"Instructions not found in parent BasicBlock?");
1370 DomTreeDFS::Node *Node = DTDFS->getNodeForBlock(BB);
1371 if (!Node) return false;
1372 return Top->dominates(Node);
1374 return false; // Not reached
1377 // aboveOrBelow - true if the Instruction either dominates or is dominated
1378 // by the current context block or instruction
1379 bool aboveOrBelow(Instruction *I) {
1380 BasicBlock *BB = I->getParent();
1381 DomTreeDFS::Node *Node = DTDFS->getNodeForBlock(BB);
1382 if (!Node) return false;
1384 return Top == Node || Top->dominates(Node) || Node->dominates(Top);
1387 bool makeEqual(Value *V1, Value *V2) {
1388 DEBUG(errs() << "makeEqual(" << *V1 << ", " << *V2 << ")\n");
1389 DEBUG(errs() << "context is ");
1391 errs() << "I: " << *TopInst << "\n";
1393 errs() << "BB: " << TopBB->getName()
1394 << "(" << Top->getDFSNumIn() << ")\n");
1396 assert(V1->getType() == V2->getType() &&
1397 "Can't make two values with different types equal.");
1399 if (V1 == V2) return true;
1401 if (isa<Constant>(V1) && isa<Constant>(V2))
1404 unsigned n1 = VN.valueNumber(V1, Top), n2 = VN.valueNumber(V2, Top);
1407 if (n1 == n2) return true;
1408 if (IG.isRelatedBy(n1, n2, Top, NE)) return false;
1411 if (n1) assert(V1 == VN.value(n1) && "Value isn't canonical.");
1412 if (n2) assert(V2 == VN.value(n2) && "Value isn't canonical.");
1414 assert(!VN.compare(V2, V1) && "Please order parameters to makeEqual.");
1416 assert(!isa<Constant>(V2) && "Tried to remove a constant.");
1418 SetVector<unsigned> Remove;
1419 if (n2) Remove.insert(n2);
1422 // Suppose we're being told that %x == %y, and %x <= %z and %y >= %z.
1423 // We can't just merge %x and %y because the relationship with %z would
1424 // be EQ and that's invalid. What we're doing is looking for any nodes
1425 // %z such that %x <= %z and %y >= %z, and vice versa.
1427 Node::iterator end = IG.node(n2)->end();
1429 // Find the intersection between N1 and N2 which is dominated by
1430 // Top. If we find %x where N1 <= %x <= N2 (or >=) then add %x to
1432 for (Node::iterator I = IG.node(n1)->begin(), E = IG.node(n1)->end();
1434 if (!(I->LV & EQ_BIT) || !Top->DominatedBy(I->Subtree)) continue;
1436 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
1437 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
1438 Node::iterator NI = IG.node(n2)->find(I->To, Top);
1440 LatticeVal NILV = reversePredicate(NI->LV);
1441 unsigned NILV_s = NILV & (SLT_BIT|SGT_BIT);
1442 unsigned NILV_u = NILV & (ULT_BIT|UGT_BIT);
1444 if ((ILV_s != (SLT_BIT|SGT_BIT) && ILV_s == NILV_s) ||
1445 (ILV_u != (ULT_BIT|UGT_BIT) && ILV_u == NILV_u))
1446 Remove.insert(I->To);
1450 // See if one of the nodes about to be removed is actually a better
1451 // canonical choice than n1.
1452 unsigned orig_n1 = n1;
1453 SetVector<unsigned>::iterator DontRemove = Remove.end();
1454 for (SetVector<unsigned>::iterator I = Remove.begin()+1 /* skip n2 */,
1455 E = Remove.end(); I != E; ++I) {
1457 Value *V = VN.value(n);
1458 if (VN.compare(V, V1)) {
1464 if (DontRemove != Remove.end()) {
1465 unsigned n = *DontRemove;
1467 Remove.insert(orig_n1);
1471 // We'd like to allow makeEqual on two values to perform a simple
1472 // substitution without creating nodes in the IG whenever possible.
1474 // The first iteration through this loop operates on V2 before going
1475 // through the Remove list and operating on those too. If all of the
1476 // iterations performed simple replacements then we exit early.
1477 bool mergeIGNode = false;
1479 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
1480 if (i) R = VN.value(Remove[i]); // skip n2.
1482 // Try to replace the whole instruction. If we can, we're done.
1483 Instruction *I2 = dyn_cast<Instruction>(R);
1484 if (I2 && below(I2)) {
1485 std::vector<Instruction *> ToNotify;
1486 for (Value::use_iterator UI = I2->use_begin(), UE = I2->use_end();
1488 Use &TheUse = UI.getUse();
1490 Instruction *I = cast<Instruction>(TheUse.getUser());
1491 ToNotify.push_back(I);
1494 DEBUG(errs() << "Simply removing " << *I2
1495 << ", replacing with " << *V1 << "\n");
1496 I2->replaceAllUsesWith(V1);
1497 // leave it dead; it'll get erased later.
1501 for (std::vector<Instruction *>::iterator II = ToNotify.begin(),
1502 IE = ToNotify.end(); II != IE; ++II) {
1509 // Otherwise, replace all dominated uses.
1510 for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
1512 Use &TheUse = UI.getUse();
1514 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
1524 // If that killed the instruction, stop here.
1525 if (I2 && isInstructionTriviallyDead(I2)) {
1526 DEBUG(errs() << "Killed all uses of " << *I2
1527 << ", replacing with " << *V1 << "\n");
1531 // If we make it to here, then we will need to create a node for N1.
1532 // Otherwise, we can skip out early!
1536 if (!isa<Constant>(V1)) {
1537 if (Remove.empty()) {
1538 VR.mergeInto(&V2, 1, VN.getOrInsertVN(V1, Top), Top, this);
1540 std::vector<Value*> RemoveVals;
1541 RemoveVals.reserve(Remove.size());
1543 for (SetVector<unsigned>::iterator I = Remove.begin(),
1544 E = Remove.end(); I != E; ++I) {
1545 Value *V = VN.value(*I);
1546 if (!V->use_empty())
1547 RemoveVals.push_back(V);
1549 VR.mergeInto(&RemoveVals[0], RemoveVals.size(),
1550 VN.getOrInsertVN(V1, Top), Top, this);
1556 if (!n1) n1 = VN.getOrInsertVN(V1, Top);
1557 IG.node(n1); // Ensure that IG.Nodes won't get resized
1559 // Migrate relationships from removed nodes to N1.
1560 for (SetVector<unsigned>::iterator I = Remove.begin(), E = Remove.end();
1563 for (Node::iterator NI = IG.node(n)->begin(), NE = IG.node(n)->end();
1565 if (NI->Subtree->DominatedBy(Top)) {
1567 assert((NI->LV & EQ_BIT) && "Node inequal to itself.");
1570 if (Remove.count(NI->To))
1573 IG.node(NI->To)->update(n1, reversePredicate(NI->LV), Top);
1574 IG.node(n1)->update(NI->To, NI->LV, Top);
1579 // Point V2 (and all items in Remove) to N1.
1581 VN.addEquality(n1, V2, Top);
1583 for (SetVector<unsigned>::iterator I = Remove.begin(),
1584 E = Remove.end(); I != E; ++I) {
1585 VN.addEquality(n1, VN.value(*I), Top);
1589 // If !Remove.empty() then V2 = Remove[0]->getValue().
1590 // Even when Remove is empty, we still want to process V2.
1592 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
1593 if (i) R = VN.value(Remove[i]); // skip n2.
1595 if (Instruction *I2 = dyn_cast<Instruction>(R)) {
1596 if (aboveOrBelow(I2))
1599 for (Value::use_iterator UI = V2->use_begin(), UE = V2->use_end();
1601 Use &TheUse = UI.getUse();
1603 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
1604 if (aboveOrBelow(I))
1611 // re-opsToDef all dominated users of V1.
1612 if (Instruction *I = dyn_cast<Instruction>(V1)) {
1613 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1615 Use &TheUse = UI.getUse();
1617 Value *V = TheUse.getUser();
1618 if (!V->use_empty()) {
1619 Instruction *Inst = cast<Instruction>(V);
1620 if (aboveOrBelow(Inst))
1629 /// cmpInstToLattice - converts an CmpInst::Predicate to lattice value
1630 /// Requires that the lattice value be valid; does not accept ICMP_EQ.
1631 static LatticeVal cmpInstToLattice(ICmpInst::Predicate Pred) {
1633 case ICmpInst::ICMP_EQ:
1634 assert(!"No matching lattice value.");
1635 return static_cast<LatticeVal>(EQ_BIT);
1637 assert(!"Invalid 'icmp' predicate.");
1638 case ICmpInst::ICMP_NE:
1640 case ICmpInst::ICMP_UGT:
1642 case ICmpInst::ICMP_UGE:
1644 case ICmpInst::ICMP_ULT:
1646 case ICmpInst::ICMP_ULE:
1648 case ICmpInst::ICMP_SGT:
1650 case ICmpInst::ICMP_SGE:
1652 case ICmpInst::ICMP_SLT:
1654 case ICmpInst::ICMP_SLE:
1660 VRPSolver(ValueNumbering &VN, InequalityGraph &IG, UnreachableBlocks &UB,
1661 ValueRanges &VR, DomTreeDFS *DTDFS, bool &modified,
1668 Top(DTDFS->getNodeForBlock(TopBB)),
1672 Context(&TopBB->getContext())
1674 assert(Top && "VRPSolver created for unreachable basic block.");
1677 VRPSolver(ValueNumbering &VN, InequalityGraph &IG, UnreachableBlocks &UB,
1678 ValueRanges &VR, DomTreeDFS *DTDFS, bool &modified,
1679 Instruction *TopInst)
1685 Top(DTDFS->getNodeForBlock(TopInst->getParent())),
1686 TopBB(TopInst->getParent()),
1689 Context(&TopInst->getContext())
1691 assert(Top && "VRPSolver created for unreachable basic block.");
1692 assert(Top->getBlock() == TopInst->getParent() && "Context mismatch.");
1695 bool isRelatedBy(Value *V1, Value *V2, ICmpInst::Predicate Pred) const {
1696 if (Constant *C1 = dyn_cast<Constant>(V1))
1697 if (Constant *C2 = dyn_cast<Constant>(V2))
1698 return ConstantExpr::getCompare(Pred, C1, C2) ==
1699 ConstantInt::getTrue(*Context);
1701 unsigned n1 = VN.valueNumber(V1, Top);
1702 unsigned n2 = VN.valueNumber(V2, Top);
1705 if (n1 == n2) return Pred == ICmpInst::ICMP_EQ ||
1706 Pred == ICmpInst::ICMP_ULE ||
1707 Pred == ICmpInst::ICMP_UGE ||
1708 Pred == ICmpInst::ICMP_SLE ||
1709 Pred == ICmpInst::ICMP_SGE;
1710 if (Pred == ICmpInst::ICMP_EQ) return false;
1711 if (IG.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
1712 if (VR.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
1715 if ((n1 && !n2 && isa<Constant>(V2)) ||
1716 (n2 && !n1 && isa<Constant>(V1))) {
1717 ConstantRange CR1 = n1 ? VR.range(n1, Top) : VR.range(V1);
1718 ConstantRange CR2 = n2 ? VR.range(n2, Top) : VR.range(V2);
1720 if (Pred == ICmpInst::ICMP_EQ)
1721 return CR1.isSingleElement() &&
1722 CR1.getSingleElement() == CR2.getSingleElement();
1724 return VR.isRelatedBy(CR1, CR2, cmpInstToLattice(Pred));
1726 if (Pred == ICmpInst::ICMP_EQ) return V1 == V2;
1730 /// add - adds a new property to the work queue
1731 void add(Value *V1, Value *V2, ICmpInst::Predicate Pred,
1732 Instruction *I = NULL) {
1733 DEBUG(errs() << "adding " << *V1 << " " << Pred << " " << *V2);
1735 DEBUG(errs() << " context: " << *I);
1737 DEBUG(errs() << " default context (" << Top->getDFSNumIn() << ")");
1738 DEBUG(errs() << "\n");
1740 assert(V1->getType() == V2->getType() &&
1741 "Can't relate two values with different types.");
1743 WorkList.push_back(Operation());
1744 Operation &O = WorkList.back();
1745 O.LHS = V1, O.RHS = V2, O.Op = Pred, O.ContextInst = I;
1746 O.ContextBB = I ? I->getParent() : TopBB;
1749 /// defToOps - Given an instruction definition that we've learned something
1750 /// new about, find any new relationships between its operands.
1751 void defToOps(Instruction *I) {
1752 Instruction *NewContext = below(I) ? I : TopInst;
1753 Value *Canonical = VN.canonicalize(I, Top);
1755 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1756 const Type *Ty = BO->getType();
1757 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
1759 Value *Op0 = VN.canonicalize(BO->getOperand(0), Top);
1760 Value *Op1 = VN.canonicalize(BO->getOperand(1), Top);
1762 // TODO: "and i32 -1, %x" EQ %y then %x EQ %y.
1764 switch (BO->getOpcode()) {
1765 case Instruction::And: {
1766 // "and i32 %a, %b" EQ -1 then %a EQ -1 and %b EQ -1
1767 ConstantInt *CI = cast<ConstantInt>(Constant::getAllOnesValue(Ty));
1768 if (Canonical == CI) {
1769 add(CI, Op0, ICmpInst::ICMP_EQ, NewContext);
1770 add(CI, Op1, ICmpInst::ICMP_EQ, NewContext);
1773 case Instruction::Or: {
1774 // "or i32 %a, %b" EQ 0 then %a EQ 0 and %b EQ 0
1775 Constant *Zero = Constant::getNullValue(Ty);
1776 if (Canonical == Zero) {
1777 add(Zero, Op0, ICmpInst::ICMP_EQ, NewContext);
1778 add(Zero, Op1, ICmpInst::ICMP_EQ, NewContext);
1781 case Instruction::Xor: {
1782 // "xor i32 %c, %a" EQ %b then %a EQ %c ^ %b
1783 // "xor i32 %c, %a" EQ %c then %a EQ 0
1784 // "xor i32 %c, %a" NE %c then %a NE 0
1785 // Repeat the above, with order of operands reversed.
1788 if (!isa<Constant>(LHS)) std::swap(LHS, RHS);
1790 if (ConstantInt *CI = dyn_cast<ConstantInt>(Canonical)) {
1791 if (ConstantInt *Arg = dyn_cast<ConstantInt>(LHS)) {
1793 ConstantInt::get(*Context, CI->getValue() ^ Arg->getValue()),
1794 ICmpInst::ICMP_EQ, NewContext);
1797 if (Canonical == LHS) {
1798 if (isa<ConstantInt>(Canonical))
1799 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_EQ,
1801 } else if (isRelatedBy(LHS, Canonical, ICmpInst::ICMP_NE)) {
1802 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_NE,
1809 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
1810 // "icmp ult i32 %a, %y" EQ true then %a u< y
1813 if (Canonical == ConstantInt::getTrue(*Context)) {
1814 add(IC->getOperand(0), IC->getOperand(1), IC->getPredicate(),
1816 } else if (Canonical == ConstantInt::getFalse(*Context)) {
1817 add(IC->getOperand(0), IC->getOperand(1),
1818 ICmpInst::getInversePredicate(IC->getPredicate()), NewContext);
1820 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
1821 if (I->getType()->isFPOrFPVector()) return;
1823 // Given: "%a = select i1 %x, i32 %b, i32 %c"
1824 // %a EQ %b and %b NE %c then %x EQ true
1825 // %a EQ %c and %b NE %c then %x EQ false
1827 Value *True = SI->getTrueValue();
1828 Value *False = SI->getFalseValue();
1829 if (isRelatedBy(True, False, ICmpInst::ICMP_NE)) {
1830 if (Canonical == VN.canonicalize(True, Top) ||
1831 isRelatedBy(Canonical, False, ICmpInst::ICMP_NE))
1832 add(SI->getCondition(), ConstantInt::getTrue(*Context),
1833 ICmpInst::ICMP_EQ, NewContext);
1834 else if (Canonical == VN.canonicalize(False, Top) ||
1835 isRelatedBy(Canonical, True, ICmpInst::ICMP_NE))
1836 add(SI->getCondition(), ConstantInt::getFalse(*Context),
1837 ICmpInst::ICMP_EQ, NewContext);
1839 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1840 for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
1841 OE = GEPI->idx_end(); OI != OE; ++OI) {
1842 ConstantInt *Op = dyn_cast<ConstantInt>(VN.canonicalize(*OI, Top));
1843 if (!Op || !Op->isZero()) return;
1845 // TODO: The GEPI indices are all zero. Copy from definition to operand,
1846 // jumping the type plane as needed.
1847 if (isRelatedBy(GEPI, Constant::getNullValue(GEPI->getType()),
1848 ICmpInst::ICMP_NE)) {
1849 Value *Ptr = GEPI->getPointerOperand();
1850 add(Ptr, Constant::getNullValue(Ptr->getType()), ICmpInst::ICMP_NE,
1853 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
1854 const Type *SrcTy = CI->getSrcTy();
1856 unsigned ci = VN.getOrInsertVN(CI, Top);
1857 uint32_t W = VR.typeToWidth(SrcTy);
1859 ConstantRange CR = VR.range(ci, Top);
1861 if (CR.isFullSet()) return;
1863 switch (CI->getOpcode()) {
1865 case Instruction::ZExt:
1866 case Instruction::SExt:
1867 VR.applyRange(VN.getOrInsertVN(CI->getOperand(0), Top),
1868 CR.truncate(W), Top, this);
1870 case Instruction::BitCast:
1871 VR.applyRange(VN.getOrInsertVN(CI->getOperand(0), Top),
1878 /// opsToDef - A new relationship was discovered involving one of this
1879 /// instruction's operands. Find any new relationship involving the
1880 /// definition, or another operand.
1881 void opsToDef(Instruction *I) {
1882 Instruction *NewContext = below(I) ? I : TopInst;
1884 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1885 Value *Op0 = VN.canonicalize(BO->getOperand(0), Top);
1886 Value *Op1 = VN.canonicalize(BO->getOperand(1), Top);
1888 if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0))
1889 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
1890 add(BO, ConstantExpr::get(BO->getOpcode(), CI0, CI1),
1891 ICmpInst::ICMP_EQ, NewContext);
1895 // "%y = and i1 true, %x" then %x EQ %y
1896 // "%y = or i1 false, %x" then %x EQ %y
1897 // "%x = add i32 %y, 0" then %x EQ %y
1898 // "%x = mul i32 %y, 0" then %x EQ 0
1900 Instruction::BinaryOps Opcode = BO->getOpcode();
1901 const Type *Ty = BO->getType();
1902 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
1904 Constant *Zero = Constant::getNullValue(Ty);
1905 Constant *One = ConstantInt::get(Ty, 1);
1906 ConstantInt *AllOnes = cast<ConstantInt>(Constant::getAllOnesValue(Ty));
1910 case Instruction::LShr:
1911 case Instruction::AShr:
1912 case Instruction::Shl:
1914 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1918 case Instruction::Sub:
1920 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1923 if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0)) {
1924 unsigned n_ci0 = VN.getOrInsertVN(Op1, Top);
1925 ConstantRange CR = VR.range(n_ci0, Top);
1926 if (!CR.isFullSet()) {
1927 CR.subtract(CI0->getValue());
1928 unsigned n_bo = VN.getOrInsertVN(BO, Top);
1929 VR.applyRange(n_bo, CR, Top, this);
1933 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
1934 unsigned n_ci1 = VN.getOrInsertVN(Op0, Top);
1935 ConstantRange CR = VR.range(n_ci1, Top);
1936 if (!CR.isFullSet()) {
1937 CR.subtract(CI1->getValue());
1938 unsigned n_bo = VN.getOrInsertVN(BO, Top);
1939 VR.applyRange(n_bo, CR, Top, this);
1944 case Instruction::Or:
1945 if (Op0 == AllOnes || Op1 == AllOnes) {
1946 add(BO, AllOnes, ICmpInst::ICMP_EQ, NewContext);
1950 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1952 } else if (Op1 == Zero) {
1953 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1957 case Instruction::Add:
1958 if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0)) {
1959 unsigned n_ci0 = VN.getOrInsertVN(Op1, Top);
1960 ConstantRange CR = VR.range(n_ci0, Top);
1961 if (!CR.isFullSet()) {
1962 CR.subtract(-CI0->getValue());
1963 unsigned n_bo = VN.getOrInsertVN(BO, Top);
1964 VR.applyRange(n_bo, CR, Top, this);
1968 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
1969 unsigned n_ci1 = VN.getOrInsertVN(Op0, Top);
1970 ConstantRange CR = VR.range(n_ci1, Top);
1971 if (!CR.isFullSet()) {
1972 CR.subtract(-CI1->getValue());
1973 unsigned n_bo = VN.getOrInsertVN(BO, Top);
1974 VR.applyRange(n_bo, CR, Top, this);
1979 case Instruction::Xor:
1981 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1983 } else if (Op1 == Zero) {
1984 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1988 case Instruction::And:
1989 if (Op0 == AllOnes) {
1990 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1992 } else if (Op1 == AllOnes) {
1993 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1996 if (Op0 == Zero || Op1 == Zero) {
1997 add(BO, Zero, ICmpInst::ICMP_EQ, NewContext);
2001 case Instruction::Mul:
2002 if (Op0 == Zero || Op1 == Zero) {
2003 add(BO, Zero, ICmpInst::ICMP_EQ, NewContext);
2007 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
2009 } else if (Op1 == One) {
2010 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
2016 // "%x = add i32 %y, %z" and %x EQ %y then %z EQ 0
2017 // "%x = add i32 %y, %z" and %x EQ %z then %y EQ 0
2018 // "%x = shl i32 %y, %z" and %x EQ %y and %y NE 0 then %z EQ 0
2019 // "%x = udiv i32 %y, %z" and %x EQ %y and %y NE 0 then %z EQ 1
2021 Value *Known = Op0, *Unknown = Op1,
2022 *TheBO = VN.canonicalize(BO, Top);
2023 if (Known != TheBO) std::swap(Known, Unknown);
2024 if (Known == TheBO) {
2027 case Instruction::LShr:
2028 case Instruction::AShr:
2029 case Instruction::Shl:
2030 if (!isRelatedBy(Known, Zero, ICmpInst::ICMP_NE)) break;
2031 // otherwise, fall-through.
2032 case Instruction::Sub:
2033 if (Unknown == Op0) break;
2034 // otherwise, fall-through.
2035 case Instruction::Xor:
2036 case Instruction::Add:
2037 add(Unknown, Zero, ICmpInst::ICMP_EQ, NewContext);
2039 case Instruction::UDiv:
2040 case Instruction::SDiv:
2041 if (Unknown == Op1) break;
2042 if (isRelatedBy(Known, Zero, ICmpInst::ICMP_NE))
2043 add(Unknown, One, ICmpInst::ICMP_EQ, NewContext);
2048 // TODO: "%a = add i32 %b, 1" and %b > %z then %a >= %z.
2050 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
2051 // "%a = icmp ult i32 %b, %c" and %b u< %c then %a EQ true
2052 // "%a = icmp ult i32 %b, %c" and %b u>= %c then %a EQ false
2055 Value *Op0 = VN.canonicalize(IC->getOperand(0), Top);
2056 Value *Op1 = VN.canonicalize(IC->getOperand(1), Top);
2058 ICmpInst::Predicate Pred = IC->getPredicate();
2059 if (isRelatedBy(Op0, Op1, Pred))
2060 add(IC, ConstantInt::getTrue(*Context), ICmpInst::ICMP_EQ, NewContext);
2061 else if (isRelatedBy(Op0, Op1, ICmpInst::getInversePredicate(Pred)))
2062 add(IC, ConstantInt::getFalse(*Context),
2063 ICmpInst::ICMP_EQ, NewContext);
2065 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
2066 if (I->getType()->isFPOrFPVector()) return;
2068 // Given: "%a = select i1 %x, i32 %b, i32 %c"
2069 // %x EQ true then %a EQ %b
2070 // %x EQ false then %a EQ %c
2071 // %b EQ %c then %a EQ %b
2073 Value *Canonical = VN.canonicalize(SI->getCondition(), Top);
2074 if (Canonical == ConstantInt::getTrue(*Context)) {
2075 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
2076 } else if (Canonical == ConstantInt::getFalse(*Context)) {
2077 add(SI, SI->getFalseValue(), ICmpInst::ICMP_EQ, NewContext);
2078 } else if (VN.canonicalize(SI->getTrueValue(), Top) ==
2079 VN.canonicalize(SI->getFalseValue(), Top)) {
2080 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
2082 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2083 const Type *DestTy = CI->getDestTy();
2084 if (DestTy->isFPOrFPVector()) return;
2086 Value *Op = VN.canonicalize(CI->getOperand(0), Top);
2087 Instruction::CastOps Opcode = CI->getOpcode();
2089 if (Constant *C = dyn_cast<Constant>(Op)) {
2090 add(CI, ConstantExpr::getCast(Opcode, C, DestTy),
2091 ICmpInst::ICMP_EQ, NewContext);
2094 uint32_t W = VR.typeToWidth(DestTy);
2095 unsigned ci = VN.getOrInsertVN(CI, Top);
2096 ConstantRange CR = VR.range(VN.getOrInsertVN(Op, Top), Top);
2098 if (!CR.isFullSet()) {
2101 case Instruction::ZExt:
2102 VR.applyRange(ci, CR.zeroExtend(W), Top, this);
2104 case Instruction::SExt:
2105 VR.applyRange(ci, CR.signExtend(W), Top, this);
2107 case Instruction::Trunc: {
2108 ConstantRange Result = CR.truncate(W);
2109 if (!Result.isFullSet())
2110 VR.applyRange(ci, Result, Top, this);
2112 case Instruction::BitCast:
2113 VR.applyRange(ci, CR, Top, this);
2115 // TODO: other casts?
2118 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
2119 for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
2120 OE = GEPI->idx_end(); OI != OE; ++OI) {
2121 ConstantInt *Op = dyn_cast<ConstantInt>(VN.canonicalize(*OI, Top));
2122 if (!Op || !Op->isZero()) return;
2124 // TODO: The GEPI indices are all zero. Copy from operand to definition,
2125 // jumping the type plane as needed.
2126 Value *Ptr = GEPI->getPointerOperand();
2127 if (isRelatedBy(Ptr, Constant::getNullValue(Ptr->getType()),
2128 ICmpInst::ICMP_NE)) {
2129 add(GEPI, Constant::getNullValue(GEPI->getType()), ICmpInst::ICMP_NE,
2135 /// solve - process the work queue
2137 //DEBUG(errs() << "WorkList entry, size: " << WorkList.size() << "\n");
2138 while (!WorkList.empty()) {
2139 //DEBUG(errs() << "WorkList size: " << WorkList.size() << "\n");
2141 Operation &O = WorkList.front();
2142 TopInst = O.ContextInst;
2143 TopBB = O.ContextBB;
2144 Top = DTDFS->getNodeForBlock(TopBB); // XXX move this into Context
2146 O.LHS = VN.canonicalize(O.LHS, Top);
2147 O.RHS = VN.canonicalize(O.RHS, Top);
2149 assert(O.LHS == VN.canonicalize(O.LHS, Top) && "Canonicalize isn't.");
2150 assert(O.RHS == VN.canonicalize(O.RHS, Top) && "Canonicalize isn't.");
2152 DEBUG(errs() << "solving " << *O.LHS << " " << O.Op << " " << *O.RHS;
2154 errs() << " context inst: " << *O.ContextInst;
2156 errs() << " context block: " << O.ContextBB->getName();
2163 // If they're both Constant, skip it. Check for contradiction and mark
2164 // the BB as unreachable if so.
2165 if (Constant *CI_L = dyn_cast<Constant>(O.LHS)) {
2166 if (Constant *CI_R = dyn_cast<Constant>(O.RHS)) {
2167 if (ConstantExpr::getCompare(O.Op, CI_L, CI_R) ==
2168 ConstantInt::getFalse(*Context))
2171 WorkList.pop_front();
2176 if (VN.compare(O.LHS, O.RHS)) {
2177 std::swap(O.LHS, O.RHS);
2178 O.Op = ICmpInst::getSwappedPredicate(O.Op);
2181 if (O.Op == ICmpInst::ICMP_EQ) {
2182 if (!makeEqual(O.RHS, O.LHS))
2185 LatticeVal LV = cmpInstToLattice(O.Op);
2187 if ((LV & EQ_BIT) &&
2188 isRelatedBy(O.LHS, O.RHS, ICmpInst::getSwappedPredicate(O.Op))) {
2189 if (!makeEqual(O.RHS, O.LHS))
2192 if (isRelatedBy(O.LHS, O.RHS, ICmpInst::getInversePredicate(O.Op))){
2194 WorkList.pop_front();
2198 unsigned n1 = VN.getOrInsertVN(O.LHS, Top);
2199 unsigned n2 = VN.getOrInsertVN(O.RHS, Top);
2202 if (O.Op != ICmpInst::ICMP_UGE && O.Op != ICmpInst::ICMP_ULE &&
2203 O.Op != ICmpInst::ICMP_SGE && O.Op != ICmpInst::ICMP_SLE)
2206 WorkList.pop_front();
2210 if (VR.isRelatedBy(n1, n2, Top, LV) ||
2211 IG.isRelatedBy(n1, n2, Top, LV)) {
2212 WorkList.pop_front();
2216 VR.addInequality(n1, n2, Top, LV, this);
2217 if ((!isa<ConstantInt>(O.RHS) && !isa<ConstantInt>(O.LHS)) ||
2219 IG.addInequality(n1, n2, Top, LV);
2221 if (Instruction *I1 = dyn_cast<Instruction>(O.LHS)) {
2222 if (aboveOrBelow(I1))
2225 if (isa<Instruction>(O.LHS) || isa<Argument>(O.LHS)) {
2226 for (Value::use_iterator UI = O.LHS->use_begin(),
2227 UE = O.LHS->use_end(); UI != UE;) {
2228 Use &TheUse = UI.getUse();
2230 Instruction *I = cast<Instruction>(TheUse.getUser());
2231 if (aboveOrBelow(I))
2235 if (Instruction *I2 = dyn_cast<Instruction>(O.RHS)) {
2236 if (aboveOrBelow(I2))
2239 if (isa<Instruction>(O.RHS) || isa<Argument>(O.RHS)) {
2240 for (Value::use_iterator UI = O.RHS->use_begin(),
2241 UE = O.RHS->use_end(); UI != UE;) {
2242 Use &TheUse = UI.getUse();
2244 Instruction *I = cast<Instruction>(TheUse.getUser());
2245 if (aboveOrBelow(I))
2251 WorkList.pop_front();
2256 void ValueRanges::addToWorklist(Value *V, Constant *C,
2257 ICmpInst::Predicate Pred, VRPSolver *VRP) {
2258 VRP->add(V, C, Pred, VRP->TopInst);
2261 void ValueRanges::markBlock(VRPSolver *VRP) {
2262 VRP->UB.mark(VRP->TopBB);
2265 /// PredicateSimplifier - This class is a simplifier that replaces
2266 /// one equivalent variable with another. It also tracks what
2267 /// can't be equal and will solve setcc instructions when possible.
2268 /// @brief Root of the predicate simplifier optimization.
2269 class VISIBILITY_HIDDEN PredicateSimplifier : public FunctionPass {
2273 InequalityGraph *IG;
2274 UnreachableBlocks UB;
2277 std::vector<DomTreeDFS::Node *> WorkList;
2279 LLVMContext *Context;
2281 static char ID; // Pass identification, replacement for typeid
2282 PredicateSimplifier() : FunctionPass(&ID) {}
2284 bool runOnFunction(Function &F);
2286 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
2287 AU.addRequiredID(BreakCriticalEdgesID);
2288 AU.addRequired<DominatorTree>();
2292 /// Forwards - Adds new properties to VRPSolver and uses them to
2293 /// simplify instructions. Because new properties sometimes apply to
2294 /// a transition from one BasicBlock to another, this will use the
2295 /// PredicateSimplifier::proceedToSuccessor(s) interface to enter the
2297 /// @brief Performs abstract execution of the program.
2298 class VISIBILITY_HIDDEN Forwards : public InstVisitor<Forwards> {
2299 friend class InstVisitor<Forwards>;
2300 PredicateSimplifier *PS;
2301 DomTreeDFS::Node *DTNode;
2305 InequalityGraph &IG;
2306 UnreachableBlocks &UB;
2309 Forwards(PredicateSimplifier *PS, DomTreeDFS::Node *DTNode)
2310 : PS(PS), DTNode(DTNode), VN(*PS->VN), IG(*PS->IG), UB(PS->UB),
2313 void visitTerminatorInst(TerminatorInst &TI);
2314 void visitBranchInst(BranchInst &BI);
2315 void visitSwitchInst(SwitchInst &SI);
2317 void visitAllocaInst(AllocaInst &AI);
2318 void visitLoadInst(LoadInst &LI);
2319 void visitStoreInst(StoreInst &SI);
2321 void visitSExtInst(SExtInst &SI);
2322 void visitZExtInst(ZExtInst &ZI);
2324 void visitBinaryOperator(BinaryOperator &BO);
2325 void visitICmpInst(ICmpInst &IC);
2328 // Used by terminator instructions to proceed from the current basic
2329 // block to the next. Verifies that "current" dominates "next",
2330 // then calls visitBasicBlock.
2331 void proceedToSuccessors(DomTreeDFS::Node *Current) {
2332 for (DomTreeDFS::Node::iterator I = Current->begin(),
2333 E = Current->end(); I != E; ++I) {
2334 WorkList.push_back(*I);
2338 void proceedToSuccessor(DomTreeDFS::Node *Next) {
2339 WorkList.push_back(Next);
2342 // Visits each instruction in the basic block.
2343 void visitBasicBlock(DomTreeDFS::Node *Node) {
2344 BasicBlock *BB = Node->getBlock();
2345 DEBUG(errs() << "Entering Basic Block: " << BB->getName()
2346 << " (" << Node->getDFSNumIn() << ")\n");
2347 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2348 visitInstruction(I++, Node);
2352 // Tries to simplify each Instruction and add new properties.
2353 void visitInstruction(Instruction *I, DomTreeDFS::Node *DT) {
2354 DEBUG(errs() << "Considering instruction " << *I << "\n");
2359 // Sometimes instructions are killed in earlier analysis.
2360 if (isInstructionTriviallyDead(I)) {
2363 if (unsigned n = VN->valueNumber(I, DTDFS->getRootNode()))
2364 if (VN->value(n) == I) IG->remove(n);
2366 I->eraseFromParent();
2371 // Try to replace the whole instruction.
2372 Value *V = VN->canonicalize(I, DT);
2373 assert(V == I && "Late instruction canonicalization.");
2377 DEBUG(errs() << "Removing " << *I << ", replacing with " << *V << "\n");
2378 if (unsigned n = VN->valueNumber(I, DTDFS->getRootNode()))
2379 if (VN->value(n) == I) IG->remove(n);
2381 I->replaceAllUsesWith(V);
2382 I->eraseFromParent();
2386 // Try to substitute operands.
2387 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2388 Value *Oper = I->getOperand(i);
2389 Value *V = VN->canonicalize(Oper, DT);
2390 assert(V == Oper && "Late operand canonicalization.");
2394 DEBUG(errs() << "Resolving " << *I);
2395 I->setOperand(i, V);
2396 DEBUG(errs() << " into " << *I);
2401 std::string name = I->getParent()->getName();
2402 DEBUG(errs() << "push (%" << name << ")\n");
2403 Forwards visit(this, DT);
2405 DEBUG(errs() << "pop (%" << name << ")\n");
2409 bool PredicateSimplifier::runOnFunction(Function &F) {
2410 DominatorTree *DT = &getAnalysis<DominatorTree>();
2411 DTDFS = new DomTreeDFS(DT);
2412 TargetData *TD = getAnalysisIfAvailable<TargetData>();
2414 // FIXME: PredicateSimplifier should still be able to do basic
2415 // optimizations without TargetData. But for now, just exit if
2416 // it's not available.
2417 if (!TD) return false;
2419 Context = &F.getContext();
2421 DEBUG(errs() << "Entering Function: " << F.getName() << "\n");
2424 DomTreeDFS::Node *Root = DTDFS->getRootNode();
2425 VN = new ValueNumbering(DTDFS);
2426 IG = new InequalityGraph(*VN, Root);
2427 VR = new ValueRanges(*VN, TD, Context);
2428 WorkList.push_back(Root);
2431 DomTreeDFS::Node *DTNode = WorkList.back();
2432 WorkList.pop_back();
2433 if (!UB.isDead(DTNode->getBlock())) visitBasicBlock(DTNode);
2434 } while (!WorkList.empty());
2441 modified |= UB.kill();
2446 void PredicateSimplifier::Forwards::visitTerminatorInst(TerminatorInst &TI) {
2447 PS->proceedToSuccessors(DTNode);
2450 void PredicateSimplifier::Forwards::visitBranchInst(BranchInst &BI) {
2451 if (BI.isUnconditional()) {
2452 PS->proceedToSuccessors(DTNode);
2456 Value *Condition = BI.getCondition();
2457 BasicBlock *TrueDest = BI.getSuccessor(0);
2458 BasicBlock *FalseDest = BI.getSuccessor(1);
2460 if (isa<Constant>(Condition) || TrueDest == FalseDest) {
2461 PS->proceedToSuccessors(DTNode);
2465 LLVMContext *Context = &BI.getContext();
2467 for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
2469 BasicBlock *Dest = (*I)->getBlock();
2470 DEBUG(errs() << "Branch thinking about %" << Dest->getName()
2471 << "(" << PS->DTDFS->getNodeForBlock(Dest)->getDFSNumIn() << ")\n");
2473 if (Dest == TrueDest) {
2474 DEBUG(errs() << "(" << DTNode->getBlock()->getName()
2475 << ") true set:\n");
2476 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
2477 VRP.add(ConstantInt::getTrue(*Context), Condition, ICmpInst::ICMP_EQ);
2482 } else if (Dest == FalseDest) {
2483 DEBUG(errs() << "(" << DTNode->getBlock()->getName()
2484 << ") false set:\n");
2485 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
2486 VRP.add(ConstantInt::getFalse(*Context), Condition, ICmpInst::ICMP_EQ);
2493 PS->proceedToSuccessor(*I);
2497 void PredicateSimplifier::Forwards::visitSwitchInst(SwitchInst &SI) {
2498 Value *Condition = SI.getCondition();
2500 // Set the EQProperty in each of the cases BBs, and the NEProperties
2501 // in the default BB.
2503 for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
2505 BasicBlock *BB = (*I)->getBlock();
2506 DEBUG(errs() << "Switch thinking about BB %" << BB->getName()
2507 << "(" << PS->DTDFS->getNodeForBlock(BB)->getDFSNumIn() << ")\n");
2509 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, BB);
2510 if (BB == SI.getDefaultDest()) {
2511 for (unsigned i = 1, e = SI.getNumCases(); i < e; ++i)
2512 if (SI.getSuccessor(i) != BB)
2513 VRP.add(Condition, SI.getCaseValue(i), ICmpInst::ICMP_NE);
2515 } else if (ConstantInt *CI = SI.findCaseDest(BB)) {
2516 VRP.add(Condition, CI, ICmpInst::ICMP_EQ);
2519 PS->proceedToSuccessor(*I);
2523 void PredicateSimplifier::Forwards::visitAllocaInst(AllocaInst &AI) {
2524 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &AI);
2525 VRP.add(Constant::getNullValue(AI.getType()),
2526 &AI, ICmpInst::ICMP_NE);
2530 void PredicateSimplifier::Forwards::visitLoadInst(LoadInst &LI) {
2531 Value *Ptr = LI.getPointerOperand();
2532 // avoid "load i8* null" -> null NE null.
2533 if (isa<Constant>(Ptr)) return;
2535 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &LI);
2536 VRP.add(Constant::getNullValue(Ptr->getType()),
2537 Ptr, ICmpInst::ICMP_NE);
2541 void PredicateSimplifier::Forwards::visitStoreInst(StoreInst &SI) {
2542 Value *Ptr = SI.getPointerOperand();
2543 if (isa<Constant>(Ptr)) return;
2545 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
2546 VRP.add(Constant::getNullValue(Ptr->getType()),
2547 Ptr, ICmpInst::ICMP_NE);
2551 void PredicateSimplifier::Forwards::visitSExtInst(SExtInst &SI) {
2552 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
2553 LLVMContext &Context = SI.getContext();
2554 uint32_t SrcBitWidth = cast<IntegerType>(SI.getSrcTy())->getBitWidth();
2555 uint32_t DstBitWidth = cast<IntegerType>(SI.getDestTy())->getBitWidth();
2556 APInt Min(APInt::getHighBitsSet(DstBitWidth, DstBitWidth-SrcBitWidth+1));
2557 APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth-1));
2558 VRP.add(ConstantInt::get(Context, Min), &SI, ICmpInst::ICMP_SLE);
2559 VRP.add(ConstantInt::get(Context, Max), &SI, ICmpInst::ICMP_SGE);
2563 void PredicateSimplifier::Forwards::visitZExtInst(ZExtInst &ZI) {
2564 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &ZI);
2565 LLVMContext &Context = ZI.getContext();
2566 uint32_t SrcBitWidth = cast<IntegerType>(ZI.getSrcTy())->getBitWidth();
2567 uint32_t DstBitWidth = cast<IntegerType>(ZI.getDestTy())->getBitWidth();
2568 APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth));
2569 VRP.add(ConstantInt::get(Context, Max), &ZI, ICmpInst::ICMP_UGE);
2573 void PredicateSimplifier::Forwards::visitBinaryOperator(BinaryOperator &BO) {
2574 Instruction::BinaryOps ops = BO.getOpcode();
2578 case Instruction::URem:
2579 case Instruction::SRem:
2580 case Instruction::UDiv:
2581 case Instruction::SDiv: {
2582 Value *Divisor = BO.getOperand(1);
2583 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2584 VRP.add(Constant::getNullValue(Divisor->getType()),
2585 Divisor, ICmpInst::ICMP_NE);
2593 case Instruction::Shl: {
2594 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2595 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
2598 case Instruction::AShr: {
2599 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2600 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_SLE);
2603 case Instruction::LShr:
2604 case Instruction::UDiv: {
2605 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2606 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
2609 case Instruction::URem: {
2610 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2611 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
2614 case Instruction::And: {
2615 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2616 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
2617 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
2620 case Instruction::Or: {
2621 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2622 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
2623 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_UGE);
2629 void PredicateSimplifier::Forwards::visitICmpInst(ICmpInst &IC) {
2630 // If possible, squeeze the ICmp predicate into something simpler.
2631 // Eg., if x = [0, 4) and we're being asked icmp uge %x, 3 then change
2632 // the predicate to eq.
2634 // XXX: once we do full PHI handling, modifying the instruction in the
2635 // Forwards visitor will cause missed optimizations.
2637 ICmpInst::Predicate Pred = IC.getPredicate();
2641 case ICmpInst::ICMP_ULE: Pred = ICmpInst::ICMP_ULT; break;
2642 case ICmpInst::ICMP_UGE: Pred = ICmpInst::ICMP_UGT; break;
2643 case ICmpInst::ICMP_SLE: Pred = ICmpInst::ICMP_SLT; break;
2644 case ICmpInst::ICMP_SGE: Pred = ICmpInst::ICMP_SGT; break;
2646 if (Pred != IC.getPredicate()) {
2647 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &IC);
2648 if (VRP.isRelatedBy(IC.getOperand(1), IC.getOperand(0),
2649 ICmpInst::ICMP_NE)) {
2651 PS->modified = true;
2652 IC.setPredicate(Pred);
2656 Pred = IC.getPredicate();
2658 LLVMContext &Context = IC.getContext();
2660 if (ConstantInt *Op1 = dyn_cast<ConstantInt>(IC.getOperand(1))) {
2661 ConstantInt *NextVal = 0;
2664 case ICmpInst::ICMP_SLT:
2665 case ICmpInst::ICMP_ULT:
2666 if (Op1->getValue() != 0)
2667 NextVal = ConstantInt::get(Context, Op1->getValue()-1);
2669 case ICmpInst::ICMP_SGT:
2670 case ICmpInst::ICMP_UGT:
2671 if (!Op1->getValue().isAllOnesValue())
2672 NextVal = ConstantInt::get(Context, Op1->getValue()+1);
2677 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &IC);
2678 if (VRP.isRelatedBy(IC.getOperand(0), NextVal,
2679 ICmpInst::getInversePredicate(Pred))) {
2680 ICmpInst *NewIC = new ICmpInst(&IC, ICmpInst::ICMP_EQ,
2681 IC.getOperand(0), NextVal, "");
2682 NewIC->takeName(&IC);
2683 IC.replaceAllUsesWith(NewIC);
2685 // XXX: prove this isn't necessary
2686 if (unsigned n = VN.valueNumber(&IC, PS->DTDFS->getRootNode()))
2687 if (VN.value(n) == &IC) IG.remove(n);
2690 IC.eraseFromParent();
2692 PS->modified = true;
2699 char PredicateSimplifier::ID = 0;
2700 static RegisterPass<PredicateSimplifier>
2701 X("predsimplify", "Predicate Simplifier");
2703 FunctionPass *llvm::createPredicateSimplifierPass() {
2704 return new PredicateSimplifier();