1 //===-- PredicateSimplifier.cpp - Path Sensitive Simplifier ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Nick Lewycky and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
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
73 // %b = [0, 254]. Because we store these by Value*, you should always
74 // canonicalize through the InequalityGraph first.
76 // It never stores an empty range, because that means that the code is
77 // unreachable. It never stores a single-element range since that's an equality
78 // relationship and better stored in the InequalityGraph, nor an empty range
79 // since that is better stored in UnreachableBlocks.
81 //===----------------------------------------------------------------------===//
83 #define DEBUG_TYPE "predsimplify"
84 #include "llvm/Transforms/Scalar.h"
85 #include "llvm/Constants.h"
86 #include "llvm/DerivedTypes.h"
87 #include "llvm/Instructions.h"
88 #include "llvm/Pass.h"
89 #include "llvm/ADT/DepthFirstIterator.h"
90 #include "llvm/ADT/SetOperations.h"
91 #include "llvm/ADT/SetVector.h"
92 #include "llvm/ADT/Statistic.h"
93 #include "llvm/ADT/STLExtras.h"
94 #include "llvm/Analysis/Dominators.h"
95 #include "llvm/Assembly/Writer.h"
96 #include "llvm/Support/CFG.h"
97 #include "llvm/Support/Compiler.h"
98 #include "llvm/Support/ConstantRange.h"
99 #include "llvm/Support/Debug.h"
100 #include "llvm/Support/InstVisitor.h"
101 #include "llvm/Target/TargetData.h"
102 #include "llvm/Transforms/Utils/Local.h"
107 using namespace llvm;
109 STATISTIC(NumVarsReplaced, "Number of argument substitutions");
110 STATISTIC(NumInstruction , "Number of instructions removed");
111 STATISTIC(NumSimple , "Number of simple replacements");
112 STATISTIC(NumBlocks , "Number of blocks marked unreachable");
113 STATISTIC(NumSnuggle , "Number of comparisons snuggled");
119 friend class DomTreeDFS;
121 typedef std::vector<Node *>::iterator iterator;
122 typedef std::vector<Node *>::const_iterator const_iterator;
124 unsigned getDFSNumIn() const { return DFSin; }
125 unsigned getDFSNumOut() const { return DFSout; }
127 BasicBlock *getBlock() const { return BB; }
129 iterator begin() { return Children.begin(); }
130 iterator end() { return Children.end(); }
132 const_iterator begin() const { return Children.begin(); }
133 const_iterator end() const { return Children.end(); }
135 bool dominates(const Node *N) const {
136 return DFSin <= N->DFSin && DFSout >= N->DFSout;
139 bool DominatedBy(const Node *N) const {
140 return N->dominates(this);
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
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;
152 return spread < N_spread;
154 bool operator>(const Node &N) const { return N < *this; }
157 unsigned DFSin, DFSout;
160 std::vector<Node *> Children;
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;
169 Entry->BB = DT->getRootNode()->getBlock();
170 S.push(std::make_pair(Entry, DT->getRootNode()));
172 NodeMap[Entry->BB] = Entry;
175 std::pair<Node *, DomTreeNode *> &Pair = S.top();
176 Node *N = Pair.first;
177 DomTreeNode *DTNode = Pair.second;
180 for (DomTreeNode::iterator I = DTNode->begin(), E = DTNode->end();
182 Node *NewNode = new Node;
183 NewNode->BB = (*I)->getBlock();
184 N->Children.push_back(NewNode);
185 S.push(std::make_pair(NewNode, *I));
187 NodeMap[NewNode->BB] = NewNode;
202 std::stack<Node *> S;
206 Node *N = S.top(); S.pop();
208 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I)
215 Node *getRootNode() const { return Entry; }
217 Node *getNodeForBlock(BasicBlock *BB) const {
218 if (!NodeMap.count(BB)) return 0;
219 return const_cast<DomTreeDFS*>(this)->NodeMap[BB];
222 bool dominates(Instruction *I1, Instruction *I2) {
223 BasicBlock *BB1 = I1->getParent(),
224 *BB2 = I2->getParent();
226 if (isa<TerminatorInst>(I1)) return false;
227 if (isa<TerminatorInst>(I2)) return true;
228 if ( isa<PHINode>(I1) && !isa<PHINode>(I2)) return true;
229 if (!isa<PHINode>(I1) && isa<PHINode>(I2)) return false;
231 for (BasicBlock::const_iterator I = BB2->begin(), E = BB2->end();
233 if (&*I == I1) return true;
234 else if (&*I == I2) return false;
236 assert(!"Instructions not found in parent BasicBlock?");
238 Node *Node1 = getNodeForBlock(BB1),
239 *Node2 = getNodeForBlock(BB2);
240 return Node1 && Node2 && Node1->dominates(Node2);
245 std::stack<std::pair<Node *, Node::iterator> > S;
249 S.push(std::make_pair(Entry, Entry->begin()));
252 std::pair<Node *, Node::iterator> &Pair = S.top();
253 Node *N = Pair.first;
254 Node::iterator &I = Pair.second;
262 S.push(std::make_pair(Next, Next->begin()));
268 virtual void dump() const {
269 dump(*cerr.stream());
272 void dump(std::ostream &os) const {
273 os << "Predicate simplifier DomTreeDFS: \n";
278 void dump(Node *N, int depth, std::ostream &os) const {
280 for (int i = 0; i < depth; ++i) { os << " "; }
281 os << "[" << depth << "] ";
283 os << N->getBlock()->getName() << " (" << N->getDFSNumIn()
284 << ", " << N->getDFSNumOut() << ")\n";
286 for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I)
292 std::map<BasicBlock *, Node *> NodeMap;
295 // SLT SGT ULT UGT EQ
296 // 0 1 0 1 0 -- GT 10
297 // 0 1 0 1 1 -- GE 11
298 // 0 1 1 0 0 -- SGTULT 12
299 // 0 1 1 0 1 -- SGEULE 13
300 // 0 1 1 1 0 -- SGT 14
301 // 0 1 1 1 1 -- SGE 15
302 // 1 0 0 1 0 -- SLTUGT 18
303 // 1 0 0 1 1 -- SLEUGE 19
304 // 1 0 1 0 0 -- LT 20
305 // 1 0 1 0 1 -- LE 21
306 // 1 0 1 1 0 -- SLT 22
307 // 1 0 1 1 1 -- SLE 23
308 // 1 1 0 1 0 -- UGT 26
309 // 1 1 0 1 1 -- UGE 27
310 // 1 1 1 0 0 -- ULT 28
311 // 1 1 1 0 1 -- ULE 29
312 // 1 1 1 1 0 -- NE 30
314 EQ_BIT = 1, UGT_BIT = 2, ULT_BIT = 4, SGT_BIT = 8, SLT_BIT = 16
317 GT = SGT_BIT | UGT_BIT,
319 LT = SLT_BIT | ULT_BIT,
321 NE = SLT_BIT | SGT_BIT | ULT_BIT | UGT_BIT,
322 SGTULT = SGT_BIT | ULT_BIT,
323 SGEULE = SGTULT | EQ_BIT,
324 SLTUGT = SLT_BIT | UGT_BIT,
325 SLEUGE = SLTUGT | EQ_BIT,
326 ULT = SLT_BIT | SGT_BIT | ULT_BIT,
327 UGT = SLT_BIT | SGT_BIT | UGT_BIT,
328 SLT = SLT_BIT | ULT_BIT | UGT_BIT,
329 SGT = SGT_BIT | ULT_BIT | UGT_BIT,
336 static bool validPredicate(LatticeVal LV) {
338 case GT: case GE: case LT: case LE: case NE:
339 case SGTULT: case SGT: case SGEULE:
340 case SLTUGT: case SLT: case SLEUGE:
342 case SLE: case SGE: case ULE: case UGE:
349 /// reversePredicate - reverse the direction of the inequality
350 static LatticeVal reversePredicate(LatticeVal LV) {
351 unsigned reverse = LV ^ (SLT_BIT|SGT_BIT|ULT_BIT|UGT_BIT); //preserve EQ_BIT
353 if ((reverse & (SLT_BIT|SGT_BIT)) == 0)
354 reverse |= (SLT_BIT|SGT_BIT);
356 if ((reverse & (ULT_BIT|UGT_BIT)) == 0)
357 reverse |= (ULT_BIT|UGT_BIT);
359 LatticeVal Rev = static_cast<LatticeVal>(reverse);
360 assert(validPredicate(Rev) && "Failed reversing predicate.");
364 /// ValueNumbering stores the scope-specific value numbers for a given Value.
365 class VISIBILITY_HIDDEN ValueNumbering {
366 class VISIBILITY_HIDDEN VNPair {
370 DomTreeDFS::Node *Subtree;
372 VNPair(Value *V, unsigned index, DomTreeDFS::Node *Subtree)
373 : V(V), index(index), Subtree(Subtree) {}
375 bool operator==(const VNPair &RHS) const {
376 return V == RHS.V && Subtree == RHS.Subtree;
379 bool operator<(const VNPair &RHS) const {
380 if (V != RHS.V) return V < RHS.V;
381 return *Subtree < *RHS.Subtree;
384 bool operator<(Value *RHS) const {
389 typedef std::vector<VNPair> VNMapType;
392 std::vector<Value *> Values;
398 virtual ~ValueNumbering() {}
399 virtual void dump() {
400 dump(*cerr.stream());
403 void dump(std::ostream &os) {
404 for (unsigned i = 1; i <= Values.size(); ++i) {
406 WriteAsOperand(os, Values[i-1]);
408 for (unsigned j = 0; j < VNMap.size(); ++j) {
409 if (VNMap[j].index == i) {
410 WriteAsOperand(os, VNMap[j].V);
411 os << " (" << VNMap[j].Subtree->getDFSNumIn() << ") ";
419 /// compare - returns true if V1 is a better canonical value than V2.
420 bool compare(Value *V1, Value *V2) const {
421 if (isa<Constant>(V1))
422 return !isa<Constant>(V2);
423 else if (isa<Constant>(V2))
425 else if (isa<Argument>(V1))
426 return !isa<Argument>(V2);
427 else if (isa<Argument>(V2))
430 Instruction *I1 = dyn_cast<Instruction>(V1);
431 Instruction *I2 = dyn_cast<Instruction>(V2);
434 return V1->getNumUses() < V2->getNumUses();
436 return DTDFS->dominates(I1, I2);
439 ValueNumbering(DomTreeDFS *DTDFS) : DTDFS(DTDFS) {}
441 /// valueNumber - finds the value number for V under the Subtree. If
442 /// there is no value number, returns zero.
443 unsigned valueNumber(Value *V, DomTreeDFS::Node *Subtree) {
444 if (!(isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V))
445 || V->getType() == Type::VoidTy) return 0;
447 VNMapType::iterator E = VNMap.end();
448 VNPair pair(V, 0, Subtree);
449 VNMapType::iterator I = std::lower_bound(VNMap.begin(), E, pair);
450 while (I != E && I->V == V) {
451 if (I->Subtree->dominates(Subtree))
458 /// getOrInsertVN - always returns a value number, creating it if necessary.
459 unsigned getOrInsertVN(Value *V, DomTreeDFS::Node *Subtree) {
460 if (unsigned n = valueNumber(V, Subtree))
466 /// newVN - creates a new value number. Value V must not already have a
467 /// value number assigned.
468 unsigned newVN(Value *V) {
469 assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
470 "Bad Value for value numbering.");
471 assert(V->getType() != Type::VoidTy && "Won't value number a void value");
475 VNPair pair = VNPair(V, Values.size(), DTDFS->getRootNode());
476 VNMapType::iterator I = std::lower_bound(VNMap.begin(), VNMap.end(), pair);
477 assert((I == VNMap.end() || value(I->index) != V) &&
478 "Attempt to create a duplicate value number.");
479 VNMap.insert(I, pair);
481 return Values.size();
484 /// value - returns the Value associated with a value number.
485 Value *value(unsigned index) const {
486 assert(index != 0 && "Zero index is reserved for not found.");
487 assert(index <= Values.size() && "Index out of range.");
488 return Values[index-1];
491 /// canonicalize - return a Value that is equal to V under Subtree.
492 Value *canonicalize(Value *V, DomTreeDFS::Node *Subtree) {
493 if (isa<Constant>(V)) return V;
495 if (unsigned n = valueNumber(V, Subtree))
501 /// addEquality - adds that value V belongs to the set of equivalent
502 /// values defined by value number n under Subtree.
503 void addEquality(unsigned n, Value *V, DomTreeDFS::Node *Subtree) {
504 assert(canonicalize(value(n), Subtree) == value(n) &&
505 "Node's 'canonical' choice isn't best within this subtree.");
507 // Suppose that we are given "%x -> node #1 (%y)". The problem is that
508 // we may already have "%z -> node #2 (%x)" somewhere above us in the
509 // graph. We need to find those edges and add "%z -> node #1 (%y)"
510 // to keep the lookups canonical.
512 std::vector<Value *> ToRepoint(1, V);
514 if (unsigned Conflict = valueNumber(V, Subtree)) {
515 for (VNMapType::iterator I = VNMap.begin(), E = VNMap.end();
517 if (I->index == Conflict && I->Subtree->dominates(Subtree))
518 ToRepoint.push_back(I->V);
522 for (std::vector<Value *>::iterator VI = ToRepoint.begin(),
523 VE = ToRepoint.end(); VI != VE; ++VI) {
526 VNPair pair(V, n, Subtree);
527 VNMapType::iterator B = VNMap.begin(), E = VNMap.end();
528 VNMapType::iterator I = std::lower_bound(B, E, pair);
529 if (I != E && I->V == V && I->Subtree == Subtree)
530 I->index = n; // Update best choice
532 VNMap.insert(I, pair); // New Value
534 // XXX: we currently don't have to worry about updating values with
535 // more specific Subtrees, but we will need to for PHI node support.
538 Value *V_n = value(n);
539 if (isa<Constant>(V) && isa<Constant>(V_n)) {
540 assert(V == V_n && "Constant equals different constant?");
546 /// remove - removes all references to value V.
547 void remove(Value *V) {
548 VNMapType::iterator B = VNMap.begin(), E = VNMap.end();
549 VNPair pair(V, 0, DTDFS->getRootNode());
550 VNMapType::iterator J = std::upper_bound(B, E, pair);
551 VNMapType::iterator I = J;
553 while (I != B && (I == E || I->V == V)) --I;
559 /// The InequalityGraph stores the relationships between values.
560 /// Each Value in the graph is assigned to a Node. Nodes are pointer
561 /// comparable for equality. The caller is expected to maintain the logical
562 /// consistency of the system.
564 /// The InequalityGraph class may invalidate Node*s after any mutator call.
565 /// @brief The InequalityGraph stores the relationships between values.
566 class VISIBILITY_HIDDEN InequalityGraph {
568 DomTreeDFS::Node *TreeRoot;
570 InequalityGraph(); // DO NOT IMPLEMENT
571 InequalityGraph(InequalityGraph &); // DO NOT IMPLEMENT
573 InequalityGraph(ValueNumbering &VN, DomTreeDFS::Node *TreeRoot)
574 : VN(VN), TreeRoot(TreeRoot) {}
578 /// An Edge is contained inside a Node making one end of the edge implicit
579 /// and contains a pointer to the other end. The edge contains a lattice
580 /// value specifying the relationship and an DomTreeDFS::Node specifying
581 /// the root in the dominator tree to which this edge applies.
582 class VISIBILITY_HIDDEN Edge {
584 Edge(unsigned T, LatticeVal V, DomTreeDFS::Node *ST)
585 : To(T), LV(V), Subtree(ST) {}
589 DomTreeDFS::Node *Subtree;
591 bool operator<(const Edge &edge) const {
592 if (To != edge.To) return To < edge.To;
593 return *Subtree < *edge.Subtree;
596 bool operator<(unsigned to) const {
600 bool operator>(unsigned to) const {
604 friend bool operator<(unsigned to, const Edge &edge) {
605 return edge.operator>(to);
609 /// A single node in the InequalityGraph. This stores the canonical Value
610 /// for the node, as well as the relationships with the neighbours.
612 /// @brief A single node in the InequalityGraph.
613 class VISIBILITY_HIDDEN Node {
614 friend class InequalityGraph;
616 typedef SmallVector<Edge, 4> RelationsType;
617 RelationsType Relations;
619 // TODO: can this idea improve performance?
620 //friend class std::vector<Node>;
621 //Node(Node &N) { RelationsType.swap(N.RelationsType); }
624 typedef RelationsType::iterator iterator;
625 typedef RelationsType::const_iterator const_iterator;
629 virtual void dump() const {
630 dump(*cerr.stream());
633 void dump(std::ostream &os) const {
634 static const std::string names[32] =
635 { "000000", "000001", "000002", "000003", "000004", "000005",
636 "000006", "000007", "000008", "000009", " >", " >=",
637 " s>u<", "s>=u<=", " s>", " s>=", "000016", "000017",
638 " s<u>", "s<=u>=", " <", " <=", " s<", " s<=",
639 "000024", "000025", " u>", " u>=", " u<", " u<=",
641 for (Node::const_iterator NI = begin(), NE = end(); NI != NE; ++NI) {
642 os << names[NI->LV] << " " << NI->To
643 << " (" << NI->Subtree->getDFSNumIn() << "), ";
649 iterator begin() { return Relations.begin(); }
650 iterator end() { return Relations.end(); }
651 const_iterator begin() const { return Relations.begin(); }
652 const_iterator end() const { return Relations.end(); }
654 iterator find(unsigned n, DomTreeDFS::Node *Subtree) {
656 for (iterator I = std::lower_bound(begin(), E, n);
657 I != E && I->To == n; ++I) {
658 if (Subtree->DominatedBy(I->Subtree))
664 const_iterator find(unsigned n, DomTreeDFS::Node *Subtree) const {
665 const_iterator E = end();
666 for (const_iterator I = std::lower_bound(begin(), E, n);
667 I != E && I->To == n; ++I) {
668 if (Subtree->DominatedBy(I->Subtree))
674 /// Updates the lattice value for a given node. Create a new entry if
675 /// one doesn't exist, otherwise it merges the values. The new lattice
676 /// value must not be inconsistent with any previously existing value.
677 void update(unsigned n, LatticeVal R, DomTreeDFS::Node *Subtree) {
678 assert(validPredicate(R) && "Invalid predicate.");
679 iterator I = find(n, Subtree);
681 Edge edge(n, R, Subtree);
682 iterator Insert = std::lower_bound(begin(), end(), edge);
683 Relations.insert(Insert, edge);
685 LatticeVal LV = static_cast<LatticeVal>(I->LV & R);
686 assert(validPredicate(LV) && "Invalid union of lattice values.");
688 if (Subtree != I->Subtree) {
689 assert(Subtree->DominatedBy(I->Subtree) &&
690 "Find returned subtree that doesn't apply.");
692 Edge edge(n, R, Subtree);
693 iterator Insert = std::lower_bound(begin(), end(), edge);
694 Relations.insert(Insert, edge); // invalidates I
695 I = find(n, Subtree);
698 // Also, we have to tighten any edge that Subtree dominates.
699 for (iterator B = begin(); I->To == n; --I) {
700 if (I->Subtree->DominatedBy(Subtree)) {
701 LatticeVal LV = static_cast<LatticeVal>(I->LV & R);
702 assert(validPredicate(LV) && "Invalid union of lattice values");
714 std::vector<Node> Nodes;
717 /// node - returns the node object at a given value number. The pointer
718 /// returned may be invalidated on the next call to node().
719 Node *node(unsigned index) {
720 assert(VN.value(index)); // This triggers the necessary checks.
721 if (Nodes.size() < index) Nodes.resize(index);
722 return &Nodes[index-1];
725 /// isRelatedBy - true iff n1 op n2
726 bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
728 if (n1 == n2) return LV & EQ_BIT;
731 Node::iterator I = N1->find(n2, Subtree), E = N1->end();
732 if (I != E) return (I->LV & LV) == I->LV;
737 // The add* methods assume that your input is logically valid and may
738 // assertion-fail or infinitely loop if you attempt a contradiction.
740 /// addInequality - Sets n1 op n2.
741 /// It is also an error to call this on an inequality that is already true.
742 void addInequality(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
744 assert(n1 != n2 && "A node can't be inequal to itself.");
747 assert(!isRelatedBy(n1, n2, Subtree, reversePredicate(LV1)) &&
748 "Contradictory inequality.");
750 // Suppose we're adding %n1 < %n2. Find all the %a < %n1 and
751 // add %a < %n2 too. This keeps the graph fully connected.
753 // Break up the relationship into signed and unsigned comparison parts.
754 // If the signed parts of %a op1 %n1 match that of %n1 op2 %n2, and
755 // op1 and op2 aren't NE, then add %a op3 %n2. The new relationship
756 // should have the EQ_BIT iff it's set for both op1 and op2.
758 unsigned LV1_s = LV1 & (SLT_BIT|SGT_BIT);
759 unsigned LV1_u = LV1 & (ULT_BIT|UGT_BIT);
761 for (Node::iterator I = node(n1)->begin(), E = node(n1)->end(); I != E; ++I) {
762 if (I->LV != NE && I->To != n2) {
764 DomTreeDFS::Node *Local_Subtree = NULL;
765 if (Subtree->DominatedBy(I->Subtree))
766 Local_Subtree = Subtree;
767 else if (I->Subtree->DominatedBy(Subtree))
768 Local_Subtree = I->Subtree;
771 unsigned new_relationship = 0;
772 LatticeVal ILV = reversePredicate(I->LV);
773 unsigned ILV_s = ILV & (SLT_BIT|SGT_BIT);
774 unsigned ILV_u = ILV & (ULT_BIT|UGT_BIT);
776 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
777 new_relationship |= ILV_s;
778 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
779 new_relationship |= ILV_u;
781 if (new_relationship) {
782 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
783 new_relationship |= (SLT_BIT|SGT_BIT);
784 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
785 new_relationship |= (ULT_BIT|UGT_BIT);
786 if ((LV1 & EQ_BIT) && (ILV & EQ_BIT))
787 new_relationship |= EQ_BIT;
789 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
791 node(I->To)->update(n2, NewLV, Local_Subtree);
792 node(n2)->update(I->To, reversePredicate(NewLV), Local_Subtree);
798 for (Node::iterator I = node(n2)->begin(), E = node(n2)->end(); I != E; ++I) {
799 if (I->LV != NE && I->To != n1) {
800 DomTreeDFS::Node *Local_Subtree = NULL;
801 if (Subtree->DominatedBy(I->Subtree))
802 Local_Subtree = Subtree;
803 else if (I->Subtree->DominatedBy(Subtree))
804 Local_Subtree = I->Subtree;
807 unsigned new_relationship = 0;
808 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
809 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
811 if (LV1_s != (SLT_BIT|SGT_BIT) && ILV_s == LV1_s)
812 new_relationship |= ILV_s;
814 if (LV1_u != (ULT_BIT|UGT_BIT) && ILV_u == LV1_u)
815 new_relationship |= ILV_u;
817 if (new_relationship) {
818 if ((new_relationship & (SLT_BIT|SGT_BIT)) == 0)
819 new_relationship |= (SLT_BIT|SGT_BIT);
820 if ((new_relationship & (ULT_BIT|UGT_BIT)) == 0)
821 new_relationship |= (ULT_BIT|UGT_BIT);
822 if ((LV1 & EQ_BIT) && (I->LV & EQ_BIT))
823 new_relationship |= EQ_BIT;
825 LatticeVal NewLV = static_cast<LatticeVal>(new_relationship);
827 node(n1)->update(I->To, NewLV, Local_Subtree);
828 node(I->To)->update(n1, reversePredicate(NewLV), Local_Subtree);
835 node(n1)->update(n2, LV1, Subtree);
836 node(n2)->update(n1, reversePredicate(LV1), Subtree);
839 /// remove - removes a node from the graph by removing all references to
841 void remove(unsigned n) {
843 for (Node::iterator NI = N->begin(), NE = N->end(); NI != NE; ++NI) {
844 Node::iterator Iter = node(NI->To)->find(n, TreeRoot);
846 node(NI->To)->Relations.erase(Iter);
847 Iter = node(NI->To)->find(n, TreeRoot);
848 } while (Iter != node(NI->To)->end());
850 N->Relations.clear();
854 virtual ~InequalityGraph() {}
855 virtual void dump() {
856 dump(*cerr.stream());
859 void dump(std::ostream &os) {
860 for (unsigned i = 1; i <= Nodes.size(); ++i) {
871 /// ValueRanges tracks the known integer ranges and anti-ranges of the nodes
872 /// in the InequalityGraph.
873 class VISIBILITY_HIDDEN ValueRanges {
877 class VISIBILITY_HIDDEN ScopedRange {
878 typedef std::vector<std::pair<DomTreeDFS::Node *, ConstantRange> >
880 RangeListType RangeList;
882 static bool swo(const std::pair<DomTreeDFS::Node *, ConstantRange> &LHS,
883 const std::pair<DomTreeDFS::Node *, ConstantRange> &RHS) {
884 return *LHS.first < *RHS.first;
889 virtual ~ScopedRange() {}
890 virtual void dump() const {
891 dump(*cerr.stream());
894 void dump(std::ostream &os) const {
896 for (const_iterator I = begin(), E = end(); I != E; ++I) {
897 os << I->second << " (" << I->first->getDFSNumIn() << "), ";
903 typedef RangeListType::iterator iterator;
904 typedef RangeListType::const_iterator const_iterator;
906 iterator begin() { return RangeList.begin(); }
907 iterator end() { return RangeList.end(); }
908 const_iterator begin() const { return RangeList.begin(); }
909 const_iterator end() const { return RangeList.end(); }
911 iterator find(DomTreeDFS::Node *Subtree) {
912 static ConstantRange empty(1, false);
914 iterator I = std::lower_bound(begin(), E,
915 std::make_pair(Subtree, empty), swo);
917 while (I != E && !I->first->dominates(Subtree)) ++I;
921 const_iterator find(DomTreeDFS::Node *Subtree) const {
922 static const ConstantRange empty(1, false);
923 const_iterator E = end();
924 const_iterator I = std::lower_bound(begin(), E,
925 std::make_pair(Subtree, empty), swo);
927 while (I != E && !I->first->dominates(Subtree)) ++I;
931 void update(const ConstantRange &CR, DomTreeDFS::Node *Subtree) {
932 assert(!CR.isEmptySet() && "Empty ConstantRange.");
933 assert(!CR.isSingleElement() && "Won't store single element.");
935 static ConstantRange empty(1, false);
938 std::lower_bound(begin(), E, std::make_pair(Subtree, empty), swo);
940 if (I != end() && I->first == Subtree) {
941 ConstantRange CR2 = I->second.intersectWith(CR);
942 assert(!CR2.isEmptySet() && !CR2.isSingleElement() &&
943 "Invalid union of ranges.");
946 RangeList.insert(I, std::make_pair(Subtree, CR));
950 std::vector<ScopedRange> Ranges;
952 void update(unsigned n, const ConstantRange &CR, DomTreeDFS::Node *Subtree){
953 if (CR.isFullSet()) return;
954 if (Ranges.size() < n) Ranges.resize(n);
955 Ranges[n-1].update(CR, Subtree);
958 /// create - Creates a ConstantRange that matches the given LatticeVal
959 /// relation with a given integer.
960 ConstantRange create(LatticeVal LV, const ConstantRange &CR) {
961 assert(!CR.isEmptySet() && "Can't deal with empty set.");
964 return makeConstantRange(ICmpInst::ICMP_NE, CR);
966 unsigned LV_s = LV & (SGT_BIT|SLT_BIT);
967 unsigned LV_u = LV & (UGT_BIT|ULT_BIT);
968 bool hasEQ = LV & EQ_BIT;
970 ConstantRange Range(CR.getBitWidth());
972 if (LV_s == SGT_BIT) {
973 Range = Range.intersectWith(makeConstantRange(
974 hasEQ ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_SGT, CR));
975 } else if (LV_s == SLT_BIT) {
976 Range = Range.intersectWith(makeConstantRange(
977 hasEQ ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_SLT, CR));
980 if (LV_u == UGT_BIT) {
981 Range = Range.intersectWith(makeConstantRange(
982 hasEQ ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_UGT, CR));
983 } else if (LV_u == ULT_BIT) {
984 Range = Range.intersectWith(makeConstantRange(
985 hasEQ ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT, CR));
991 /// makeConstantRange - Creates a ConstantRange representing the set of all
992 /// value that match the ICmpInst::Predicate with any of the values in CR.
993 ConstantRange makeConstantRange(ICmpInst::Predicate ICmpOpcode,
994 const ConstantRange &CR) {
995 uint32_t W = CR.getBitWidth();
996 switch (ICmpOpcode) {
997 default: assert(!"Invalid ICmp opcode to makeConstantRange()");
998 case ICmpInst::ICMP_EQ:
999 return ConstantRange(CR.getLower(), CR.getUpper());
1000 case ICmpInst::ICMP_NE:
1001 if (CR.isSingleElement())
1002 return ConstantRange(CR.getUpper(), CR.getLower());
1003 return ConstantRange(W);
1004 case ICmpInst::ICMP_ULT:
1005 return ConstantRange(APInt::getMinValue(W), CR.getUnsignedMax());
1006 case ICmpInst::ICMP_SLT:
1007 return ConstantRange(APInt::getSignedMinValue(W), CR.getSignedMax());
1008 case ICmpInst::ICMP_ULE: {
1009 APInt UMax(CR.getUnsignedMax());
1010 if (UMax.isMaxValue())
1011 return ConstantRange(W);
1012 return ConstantRange(APInt::getMinValue(W), UMax + 1);
1014 case ICmpInst::ICMP_SLE: {
1015 APInt SMax(CR.getSignedMax());
1016 if (SMax.isMaxSignedValue() || (SMax+1).isMaxSignedValue())
1017 return ConstantRange(W);
1018 return ConstantRange(APInt::getSignedMinValue(W), SMax + 1);
1020 case ICmpInst::ICMP_UGT:
1021 return ConstantRange(CR.getUnsignedMin() + 1, APInt::getNullValue(W));
1022 case ICmpInst::ICMP_SGT:
1023 return ConstantRange(CR.getSignedMin() + 1,
1024 APInt::getSignedMinValue(W));
1025 case ICmpInst::ICMP_UGE: {
1026 APInt UMin(CR.getUnsignedMin());
1027 if (UMin.isMinValue())
1028 return ConstantRange(W);
1029 return ConstantRange(UMin, APInt::getNullValue(W));
1031 case ICmpInst::ICMP_SGE: {
1032 APInt SMin(CR.getSignedMin());
1033 if (SMin.isMinSignedValue())
1034 return ConstantRange(W);
1035 return ConstantRange(SMin, APInt::getSignedMinValue(W));
1041 bool isCanonical(Value *V, DomTreeDFS::Node *Subtree) {
1042 return V == VN.canonicalize(V, Subtree);
1048 ValueRanges(ValueNumbering &VN, TargetData *TD) : VN(VN), TD(TD) {}
1051 virtual ~ValueRanges() {}
1053 virtual void dump() const {
1054 dump(*cerr.stream());
1057 void dump(std::ostream &os) const {
1058 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
1059 os << (i+1) << " = ";
1066 /// range - looks up the ConstantRange associated with a value number.
1067 ConstantRange range(unsigned n, DomTreeDFS::Node *Subtree) {
1068 assert(VN.value(n)); // performs range checks
1070 if (n <= Ranges.size()) {
1071 ScopedRange::iterator I = Ranges[n-1].find(Subtree);
1072 if (I != Ranges[n-1].end()) return I->second;
1075 Value *V = VN.value(n);
1076 ConstantRange CR = range(V);
1080 /// range - determine a range from a Value without performing any lookups.
1081 ConstantRange range(Value *V) const {
1082 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
1083 return ConstantRange(C->getValue());
1084 else if (isa<ConstantPointerNull>(V))
1085 return ConstantRange(APInt::getNullValue(typeToWidth(V->getType())));
1087 return typeToWidth(V->getType());
1090 // typeToWidth - returns the number of bits necessary to store a value of
1091 // this type, or zero if unknown.
1092 uint32_t typeToWidth(const Type *Ty) const {
1094 return TD->getTypeSizeInBits(Ty);
1096 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
1097 return ITy->getBitWidth();
1102 static bool isRelatedBy(const ConstantRange &CR1, const ConstantRange &CR2,
1105 default: assert(!"Impossible lattice value!");
1107 return CR1.intersectWith(CR2).isEmptySet();
1109 return CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
1111 return CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
1113 return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
1115 return CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
1117 return CR1.getSignedMax().slt(CR2.getSignedMin());
1119 return CR1.getSignedMax().sle(CR2.getSignedMin());
1121 return CR1.getSignedMin().sgt(CR2.getSignedMax());
1123 return CR1.getSignedMin().sge(CR2.getSignedMax());
1125 return CR1.getUnsignedMax().ult(CR2.getUnsignedMin()) &&
1126 CR1.getSignedMax().slt(CR2.getUnsignedMin());
1128 return CR1.getUnsignedMax().ule(CR2.getUnsignedMin()) &&
1129 CR1.getSignedMax().sle(CR2.getUnsignedMin());
1131 return CR1.getUnsignedMin().ugt(CR2.getUnsignedMax()) &&
1132 CR1.getSignedMin().sgt(CR2.getSignedMax());
1134 return CR1.getUnsignedMin().uge(CR2.getUnsignedMax()) &&
1135 CR1.getSignedMin().sge(CR2.getSignedMax());
1137 return CR1.getSignedMax().slt(CR2.getSignedMin()) &&
1138 CR1.getUnsignedMin().ugt(CR2.getUnsignedMax());
1140 return CR1.getSignedMax().sle(CR2.getSignedMin()) &&
1141 CR1.getUnsignedMin().uge(CR2.getUnsignedMax());
1143 return CR1.getSignedMin().sgt(CR2.getSignedMax()) &&
1144 CR1.getUnsignedMax().ult(CR2.getUnsignedMin());
1146 return CR1.getSignedMin().sge(CR2.getSignedMax()) &&
1147 CR1.getUnsignedMax().ule(CR2.getUnsignedMin());
1151 bool isRelatedBy(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
1153 ConstantRange CR1 = range(n1, Subtree);
1154 ConstantRange CR2 = range(n2, Subtree);
1156 // True iff all values in CR1 are LV to all values in CR2.
1157 return isRelatedBy(CR1, CR2, LV);
1160 void addToWorklist(Value *V, Constant *C, ICmpInst::Predicate Pred,
1162 void markBlock(VRPSolver *VRP);
1164 void mergeInto(Value **I, unsigned n, unsigned New,
1165 DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
1166 ConstantRange CR_New = range(New, Subtree);
1167 ConstantRange Merged = CR_New;
1169 for (; n != 0; ++I, --n) {
1170 unsigned i = VN.valueNumber(*I, Subtree);
1171 ConstantRange CR_Kill = i ? range(i, Subtree) : range(*I);
1172 if (CR_Kill.isFullSet()) continue;
1173 Merged = Merged.intersectWith(CR_Kill);
1176 if (Merged.isFullSet() || Merged == CR_New) return;
1178 applyRange(New, Merged, Subtree, VRP);
1181 void applyRange(unsigned n, const ConstantRange &CR,
1182 DomTreeDFS::Node *Subtree, VRPSolver *VRP) {
1183 ConstantRange Merged = CR.intersectWith(range(n, Subtree));
1184 if (Merged.isEmptySet()) {
1189 if (const APInt *I = Merged.getSingleElement()) {
1190 Value *V = VN.value(n); // XXX: redesign worklist.
1191 const Type *Ty = V->getType();
1192 if (Ty->isInteger()) {
1193 addToWorklist(V, ConstantInt::get(*I), ICmpInst::ICMP_EQ, VRP);
1195 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1196 assert(*I == 0 && "Pointer is null but not zero?");
1197 addToWorklist(V, ConstantPointerNull::get(PTy),
1198 ICmpInst::ICMP_EQ, VRP);
1203 update(n, Merged, Subtree);
1206 void addNotEquals(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
1208 ConstantRange CR1 = range(n1, Subtree);
1209 ConstantRange CR2 = range(n2, Subtree);
1211 uint32_t W = CR1.getBitWidth();
1213 if (const APInt *I = CR1.getSingleElement()) {
1214 if (CR2.isFullSet()) {
1215 ConstantRange NewCR2(CR1.getUpper(), CR1.getLower());
1216 applyRange(n2, NewCR2, Subtree, VRP);
1217 } else if (*I == CR2.getLower()) {
1218 APInt NewLower(CR2.getLower() + 1),
1219 NewUpper(CR2.getUpper());
1220 if (NewLower == NewUpper)
1221 NewLower = NewUpper = APInt::getMinValue(W);
1223 ConstantRange NewCR2(NewLower, NewUpper);
1224 applyRange(n2, NewCR2, Subtree, VRP);
1225 } else if (*I == CR2.getUpper() - 1) {
1226 APInt NewLower(CR2.getLower()),
1227 NewUpper(CR2.getUpper() - 1);
1228 if (NewLower == NewUpper)
1229 NewLower = NewUpper = APInt::getMinValue(W);
1231 ConstantRange NewCR2(NewLower, NewUpper);
1232 applyRange(n2, NewCR2, Subtree, VRP);
1236 if (const APInt *I = CR2.getSingleElement()) {
1237 if (CR1.isFullSet()) {
1238 ConstantRange NewCR1(CR2.getUpper(), CR2.getLower());
1239 applyRange(n1, NewCR1, Subtree, VRP);
1240 } else if (*I == CR1.getLower()) {
1241 APInt NewLower(CR1.getLower() + 1),
1242 NewUpper(CR1.getUpper());
1243 if (NewLower == NewUpper)
1244 NewLower = NewUpper = APInt::getMinValue(W);
1246 ConstantRange NewCR1(NewLower, NewUpper);
1247 applyRange(n1, NewCR1, Subtree, VRP);
1248 } else if (*I == CR1.getUpper() - 1) {
1249 APInt NewLower(CR1.getLower()),
1250 NewUpper(CR1.getUpper() - 1);
1251 if (NewLower == NewUpper)
1252 NewLower = NewUpper = APInt::getMinValue(W);
1254 ConstantRange NewCR1(NewLower, NewUpper);
1255 applyRange(n1, NewCR1, Subtree, VRP);
1260 void addInequality(unsigned n1, unsigned n2, DomTreeDFS::Node *Subtree,
1261 LatticeVal LV, VRPSolver *VRP) {
1262 assert(!isRelatedBy(n1, n2, Subtree, LV) && "Asked to do useless work.");
1265 addNotEquals(n1, n2, Subtree, VRP);
1269 ConstantRange CR1 = range(n1, Subtree);
1270 ConstantRange CR2 = range(n2, Subtree);
1272 if (!CR1.isSingleElement()) {
1273 ConstantRange NewCR1 = CR1.intersectWith(create(LV, CR2));
1275 applyRange(n1, NewCR1, Subtree, VRP);
1278 if (!CR2.isSingleElement()) {
1279 ConstantRange NewCR2 = CR2.intersectWith(create(reversePredicate(LV),
1282 applyRange(n2, NewCR2, Subtree, VRP);
1287 /// UnreachableBlocks keeps tracks of blocks that are for one reason or
1288 /// another discovered to be unreachable. This is used to cull the graph when
1289 /// analyzing instructions, and to mark blocks with the "unreachable"
1290 /// terminator instruction after the function has executed.
1291 class VISIBILITY_HIDDEN UnreachableBlocks {
1293 std::vector<BasicBlock *> DeadBlocks;
1296 /// mark - mark a block as dead
1297 void mark(BasicBlock *BB) {
1298 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
1299 std::vector<BasicBlock *>::iterator I =
1300 std::lower_bound(DeadBlocks.begin(), E, BB);
1302 if (I == E || *I != BB) DeadBlocks.insert(I, BB);
1305 /// isDead - returns whether a block is known to be dead already
1306 bool isDead(BasicBlock *BB) {
1307 std::vector<BasicBlock *>::iterator E = DeadBlocks.end();
1308 std::vector<BasicBlock *>::iterator I =
1309 std::lower_bound(DeadBlocks.begin(), E, BB);
1311 return I != E && *I == BB;
1314 /// kill - replace the dead blocks' terminator with an UnreachableInst.
1316 bool modified = false;
1317 for (std::vector<BasicBlock *>::iterator I = DeadBlocks.begin(),
1318 E = DeadBlocks.end(); I != E; ++I) {
1319 BasicBlock *BB = *I;
1321 DOUT << "unreachable block: " << BB->getName() << "\n";
1323 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
1325 BasicBlock *Succ = *SI;
1326 Succ->removePredecessor(BB);
1329 TerminatorInst *TI = BB->getTerminator();
1330 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1331 TI->eraseFromParent();
1332 new UnreachableInst(BB);
1341 /// VRPSolver keeps track of how changes to one variable affect other
1342 /// variables, and forwards changes along to the InequalityGraph. It
1343 /// also maintains the correct choice for "canonical" in the IG.
1344 /// @brief VRPSolver calculates inferences from a new relationship.
1345 class VISIBILITY_HIDDEN VRPSolver {
1347 friend class ValueRanges;
1351 ICmpInst::Predicate Op;
1353 BasicBlock *ContextBB; // XXX use a DomTreeDFS::Node instead
1354 Instruction *ContextInst;
1356 std::deque<Operation> WorkList;
1359 InequalityGraph &IG;
1360 UnreachableBlocks &UB;
1363 DomTreeDFS::Node *Top;
1365 Instruction *TopInst;
1368 typedef InequalityGraph::Node Node;
1370 // below - true if the Instruction is dominated by the current context
1371 // block or instruction
1372 bool below(Instruction *I) {
1373 BasicBlock *BB = I->getParent();
1374 if (TopInst && TopInst->getParent() == BB) {
1375 if (isa<TerminatorInst>(TopInst)) return false;
1376 if (isa<TerminatorInst>(I)) return true;
1377 if ( isa<PHINode>(TopInst) && !isa<PHINode>(I)) return true;
1378 if (!isa<PHINode>(TopInst) && isa<PHINode>(I)) return false;
1380 for (BasicBlock::const_iterator Iter = BB->begin(), E = BB->end();
1381 Iter != E; ++Iter) {
1382 if (&*Iter == TopInst) return true;
1383 else if (&*Iter == I) return false;
1385 assert(!"Instructions not found in parent BasicBlock?");
1387 DomTreeDFS::Node *Node = DTDFS->getNodeForBlock(BB);
1388 if (!Node) return false;
1389 return Top->dominates(Node);
1393 // aboveOrBelow - true if the Instruction either dominates or is dominated
1394 // by the current context block or instruction
1395 bool aboveOrBelow(Instruction *I) {
1396 BasicBlock *BB = I->getParent();
1397 DomTreeDFS::Node *Node = DTDFS->getNodeForBlock(BB);
1398 if (!Node) return false;
1400 return Top == Node || Top->dominates(Node) || Node->dominates(Top);
1403 bool makeEqual(Value *V1, Value *V2) {
1404 DOUT << "makeEqual(" << *V1 << ", " << *V2 << ")\n";
1405 DOUT << "context is ";
1406 if (TopInst) DOUT << "I: " << *TopInst << "\n";
1407 else DOUT << "BB: " << TopBB->getName()
1408 << "(" << Top->getDFSNumIn() << ")\n";
1410 assert(V1->getType() == V2->getType() &&
1411 "Can't make two values with different types equal.");
1413 if (V1 == V2) return true;
1415 if (isa<Constant>(V1) && isa<Constant>(V2))
1418 unsigned n1 = VN.valueNumber(V1, Top), n2 = VN.valueNumber(V2, Top);
1421 if (n1 == n2) return true;
1422 if (IG.isRelatedBy(n1, n2, Top, NE)) return false;
1425 if (n1) assert(V1 == VN.value(n1) && "Value isn't canonical.");
1426 if (n2) assert(V2 == VN.value(n2) && "Value isn't canonical.");
1428 assert(!VN.compare(V2, V1) && "Please order parameters to makeEqual.");
1430 assert(!isa<Constant>(V2) && "Tried to remove a constant.");
1432 SetVector<unsigned> Remove;
1433 if (n2) Remove.insert(n2);
1436 // Suppose we're being told that %x == %y, and %x <= %z and %y >= %z.
1437 // We can't just merge %x and %y because the relationship with %z would
1438 // be EQ and that's invalid. What we're doing is looking for any nodes
1439 // %z such that %x <= %z and %y >= %z, and vice versa.
1441 Node::iterator end = IG.node(n2)->end();
1443 // Find the intersection between N1 and N2 which is dominated by
1444 // Top. If we find %x where N1 <= %x <= N2 (or >=) then add %x to
1446 for (Node::iterator I = IG.node(n1)->begin(), E = IG.node(n1)->end();
1448 if (!(I->LV & EQ_BIT) || !Top->DominatedBy(I->Subtree)) continue;
1450 unsigned ILV_s = I->LV & (SLT_BIT|SGT_BIT);
1451 unsigned ILV_u = I->LV & (ULT_BIT|UGT_BIT);
1452 Node::iterator NI = IG.node(n2)->find(I->To, Top);
1454 LatticeVal NILV = reversePredicate(NI->LV);
1455 unsigned NILV_s = NILV & (SLT_BIT|SGT_BIT);
1456 unsigned NILV_u = NILV & (ULT_BIT|UGT_BIT);
1458 if ((ILV_s != (SLT_BIT|SGT_BIT) && ILV_s == NILV_s) ||
1459 (ILV_u != (ULT_BIT|UGT_BIT) && ILV_u == NILV_u))
1460 Remove.insert(I->To);
1464 // See if one of the nodes about to be removed is actually a better
1465 // canonical choice than n1.
1466 unsigned orig_n1 = n1;
1467 SetVector<unsigned>::iterator DontRemove = Remove.end();
1468 for (SetVector<unsigned>::iterator I = Remove.begin()+1 /* skip n2 */,
1469 E = Remove.end(); I != E; ++I) {
1471 Value *V = VN.value(n);
1472 if (VN.compare(V, V1)) {
1478 if (DontRemove != Remove.end()) {
1479 unsigned n = *DontRemove;
1481 Remove.insert(orig_n1);
1485 // We'd like to allow makeEqual on two values to perform a simple
1486 // substitution without every creating nodes in the IG whenever possible.
1488 // The first iteration through this loop operates on V2 before going
1489 // through the Remove list and operating on those too. If all of the
1490 // iterations performed simple replacements then we exit early.
1491 bool mergeIGNode = false;
1493 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
1494 if (i) R = VN.value(Remove[i]); // skip n2.
1496 // Try to replace the whole instruction. If we can, we're done.
1497 Instruction *I2 = dyn_cast<Instruction>(R);
1498 if (I2 && below(I2)) {
1499 std::vector<Instruction *> ToNotify;
1500 for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
1502 Use &TheUse = UI.getUse();
1504 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser()))
1505 ToNotify.push_back(I);
1508 DOUT << "Simply removing " << *I2
1509 << ", replacing with " << *V1 << "\n";
1510 I2->replaceAllUsesWith(V1);
1511 // leave it dead; it'll get erased later.
1515 for (std::vector<Instruction *>::iterator II = ToNotify.begin(),
1516 IE = ToNotify.end(); II != IE; ++II) {
1523 // Otherwise, replace all dominated uses.
1524 for (Value::use_iterator UI = R->use_begin(), UE = R->use_end();
1526 Use &TheUse = UI.getUse();
1528 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
1538 // If that killed the instruction, stop here.
1539 if (I2 && isInstructionTriviallyDead(I2)) {
1540 DOUT << "Killed all uses of " << *I2
1541 << ", replacing with " << *V1 << "\n";
1545 // If we make it to here, then we will need to create a node for N1.
1546 // Otherwise, we can skip out early!
1550 if (!isa<Constant>(V1)) {
1551 if (Remove.empty()) {
1552 VR.mergeInto(&V2, 1, VN.getOrInsertVN(V1, Top), Top, this);
1554 std::vector<Value*> RemoveVals;
1555 RemoveVals.reserve(Remove.size());
1557 for (SetVector<unsigned>::iterator I = Remove.begin(),
1558 E = Remove.end(); I != E; ++I) {
1559 Value *V = VN.value(*I);
1560 if (!V->use_empty())
1561 RemoveVals.push_back(V);
1563 VR.mergeInto(&RemoveVals[0], RemoveVals.size(),
1564 VN.getOrInsertVN(V1, Top), Top, this);
1570 if (!n1) n1 = VN.getOrInsertVN(V1, Top);
1572 // Migrate relationships from removed nodes to N1.
1573 for (SetVector<unsigned>::iterator I = Remove.begin(), E = Remove.end();
1576 for (Node::iterator NI = IG.node(n)->begin(), NE = IG.node(n)->end();
1578 if (NI->Subtree->DominatedBy(Top)) {
1580 assert((NI->LV & EQ_BIT) && "Node inequal to itself.");
1583 if (Remove.count(NI->To))
1586 IG.node(NI->To)->update(n1, reversePredicate(NI->LV), Top);
1587 IG.node(n1)->update(NI->To, NI->LV, Top);
1592 // Point V2 (and all items in Remove) to N1.
1594 VN.addEquality(n1, V2, Top);
1596 for (SetVector<unsigned>::iterator I = Remove.begin(),
1597 E = Remove.end(); I != E; ++I) {
1598 VN.addEquality(n1, VN.value(*I), Top);
1602 // If !Remove.empty() then V2 = Remove[0]->getValue().
1603 // Even when Remove is empty, we still want to process V2.
1605 for (Value *R = V2; i == 0 || i < Remove.size(); ++i) {
1606 if (i) R = VN.value(Remove[i]); // skip n2.
1608 if (Instruction *I2 = dyn_cast<Instruction>(R)) {
1609 if (aboveOrBelow(I2))
1612 for (Value::use_iterator UI = V2->use_begin(), UE = V2->use_end();
1614 Use &TheUse = UI.getUse();
1616 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
1617 if (aboveOrBelow(I))
1624 // re-opsToDef all dominated users of V1.
1625 if (Instruction *I = dyn_cast<Instruction>(V1)) {
1626 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
1628 Use &TheUse = UI.getUse();
1630 Value *V = TheUse.getUser();
1631 if (!V->use_empty()) {
1632 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
1633 if (aboveOrBelow(Inst))
1643 /// cmpInstToLattice - converts an CmpInst::Predicate to lattice value
1644 /// Requires that the lattice value be valid; does not accept ICMP_EQ.
1645 static LatticeVal cmpInstToLattice(ICmpInst::Predicate Pred) {
1647 case ICmpInst::ICMP_EQ:
1648 assert(!"No matching lattice value.");
1649 return static_cast<LatticeVal>(EQ_BIT);
1651 assert(!"Invalid 'icmp' predicate.");
1652 case ICmpInst::ICMP_NE:
1654 case ICmpInst::ICMP_UGT:
1656 case ICmpInst::ICMP_UGE:
1658 case ICmpInst::ICMP_ULT:
1660 case ICmpInst::ICMP_ULE:
1662 case ICmpInst::ICMP_SGT:
1664 case ICmpInst::ICMP_SGE:
1666 case ICmpInst::ICMP_SLT:
1668 case ICmpInst::ICMP_SLE:
1674 VRPSolver(ValueNumbering &VN, InequalityGraph &IG, UnreachableBlocks &UB,
1675 ValueRanges &VR, DomTreeDFS *DTDFS, bool &modified,
1682 Top(DTDFS->getNodeForBlock(TopBB)),
1687 assert(Top && "VRPSolver created for unreachable basic block.");
1690 VRPSolver(ValueNumbering &VN, InequalityGraph &IG, UnreachableBlocks &UB,
1691 ValueRanges &VR, DomTreeDFS *DTDFS, bool &modified,
1692 Instruction *TopInst)
1698 Top(DTDFS->getNodeForBlock(TopInst->getParent())),
1699 TopBB(TopInst->getParent()),
1703 assert(Top && "VRPSolver created for unreachable basic block.");
1704 assert(Top->getBlock() == TopInst->getParent() && "Context mismatch.");
1707 bool isRelatedBy(Value *V1, Value *V2, ICmpInst::Predicate Pred) const {
1708 if (Constant *C1 = dyn_cast<Constant>(V1))
1709 if (Constant *C2 = dyn_cast<Constant>(V2))
1710 return ConstantExpr::getCompare(Pred, C1, C2) ==
1711 ConstantInt::getTrue();
1713 unsigned n1 = VN.valueNumber(V1, Top);
1714 unsigned n2 = VN.valueNumber(V2, Top);
1717 if (n1 == n2) return Pred == ICmpInst::ICMP_EQ ||
1718 Pred == ICmpInst::ICMP_ULE ||
1719 Pred == ICmpInst::ICMP_UGE ||
1720 Pred == ICmpInst::ICMP_SLE ||
1721 Pred == ICmpInst::ICMP_SGE;
1722 if (Pred == ICmpInst::ICMP_EQ) return false;
1723 if (IG.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
1724 if (VR.isRelatedBy(n1, n2, Top, cmpInstToLattice(Pred))) return true;
1727 if ((n1 && !n2 && isa<Constant>(V2)) ||
1728 (n2 && !n1 && isa<Constant>(V1))) {
1729 ConstantRange CR1 = n1 ? VR.range(n1, Top) : VR.range(V1);
1730 ConstantRange CR2 = n2 ? VR.range(n2, Top) : VR.range(V2);
1732 if (Pred == ICmpInst::ICMP_EQ)
1733 return CR1.isSingleElement() &&
1734 CR1.getSingleElement() == CR2.getSingleElement();
1736 return VR.isRelatedBy(CR1, CR2, cmpInstToLattice(Pred));
1738 if (Pred == ICmpInst::ICMP_EQ) return V1 == V2;
1742 /// add - adds a new property to the work queue
1743 void add(Value *V1, Value *V2, ICmpInst::Predicate Pred,
1744 Instruction *I = NULL) {
1745 DOUT << "adding " << *V1 << " " << Pred << " " << *V2;
1746 if (I) DOUT << " context: " << *I;
1747 else DOUT << " default context (" << Top->getDFSNumIn() << ")";
1750 assert(V1->getType() == V2->getType() &&
1751 "Can't relate two values with different types.");
1753 WorkList.push_back(Operation());
1754 Operation &O = WorkList.back();
1755 O.LHS = V1, O.RHS = V2, O.Op = Pred, O.ContextInst = I;
1756 O.ContextBB = I ? I->getParent() : TopBB;
1759 /// defToOps - Given an instruction definition that we've learned something
1760 /// new about, find any new relationships between its operands.
1761 void defToOps(Instruction *I) {
1762 Instruction *NewContext = below(I) ? I : TopInst;
1763 Value *Canonical = VN.canonicalize(I, Top);
1765 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1766 const Type *Ty = BO->getType();
1767 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
1769 Value *Op0 = VN.canonicalize(BO->getOperand(0), Top);
1770 Value *Op1 = VN.canonicalize(BO->getOperand(1), Top);
1772 // TODO: "and i32 -1, %x" EQ %y then %x EQ %y.
1774 switch (BO->getOpcode()) {
1775 case Instruction::And: {
1776 // "and i32 %a, %b" EQ -1 then %a EQ -1 and %b EQ -1
1777 ConstantInt *CI = ConstantInt::getAllOnesValue(Ty);
1778 if (Canonical == CI) {
1779 add(CI, Op0, ICmpInst::ICMP_EQ, NewContext);
1780 add(CI, Op1, ICmpInst::ICMP_EQ, NewContext);
1783 case Instruction::Or: {
1784 // "or i32 %a, %b" EQ 0 then %a EQ 0 and %b EQ 0
1785 Constant *Zero = Constant::getNullValue(Ty);
1786 if (Canonical == Zero) {
1787 add(Zero, Op0, ICmpInst::ICMP_EQ, NewContext);
1788 add(Zero, Op1, ICmpInst::ICMP_EQ, NewContext);
1791 case Instruction::Xor: {
1792 // "xor i32 %c, %a" EQ %b then %a EQ %c ^ %b
1793 // "xor i32 %c, %a" EQ %c then %a EQ 0
1794 // "xor i32 %c, %a" NE %c then %a NE 0
1795 // Repeat the above, with order of operands reversed.
1798 if (!isa<Constant>(LHS)) std::swap(LHS, RHS);
1800 if (ConstantInt *CI = dyn_cast<ConstantInt>(Canonical)) {
1801 if (ConstantInt *Arg = dyn_cast<ConstantInt>(LHS)) {
1802 add(RHS, ConstantInt::get(CI->getValue() ^ Arg->getValue()),
1803 ICmpInst::ICMP_EQ, NewContext);
1806 if (Canonical == LHS) {
1807 if (isa<ConstantInt>(Canonical))
1808 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_EQ,
1810 } else if (isRelatedBy(LHS, Canonical, ICmpInst::ICMP_NE)) {
1811 add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_NE,
1818 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
1819 // "icmp ult i32 %a, %y" EQ true then %a u< y
1822 if (Canonical == ConstantInt::getTrue()) {
1823 add(IC->getOperand(0), IC->getOperand(1), IC->getPredicate(),
1825 } else if (Canonical == ConstantInt::getFalse()) {
1826 add(IC->getOperand(0), IC->getOperand(1),
1827 ICmpInst::getInversePredicate(IC->getPredicate()), NewContext);
1829 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
1830 if (I->getType()->isFPOrFPVector()) return;
1832 // Given: "%a = select i1 %x, i32 %b, i32 %c"
1833 // %a EQ %b and %b NE %c then %x EQ true
1834 // %a EQ %c and %b NE %c then %x EQ false
1836 Value *True = SI->getTrueValue();
1837 Value *False = SI->getFalseValue();
1838 if (isRelatedBy(True, False, ICmpInst::ICMP_NE)) {
1839 if (Canonical == VN.canonicalize(True, Top) ||
1840 isRelatedBy(Canonical, False, ICmpInst::ICMP_NE))
1841 add(SI->getCondition(), ConstantInt::getTrue(),
1842 ICmpInst::ICMP_EQ, NewContext);
1843 else if (Canonical == VN.canonicalize(False, Top) ||
1844 isRelatedBy(Canonical, True, ICmpInst::ICMP_NE))
1845 add(SI->getCondition(), ConstantInt::getFalse(),
1846 ICmpInst::ICMP_EQ, NewContext);
1848 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1849 for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
1850 OE = GEPI->idx_end(); OI != OE; ++OI) {
1851 ConstantInt *Op = dyn_cast<ConstantInt>(VN.canonicalize(*OI, Top));
1852 if (!Op || !Op->isZero()) return;
1854 // TODO: The GEPI indices are all zero. Copy from definition to operand,
1855 // jumping the type plane as needed.
1856 if (isRelatedBy(GEPI, Constant::getNullValue(GEPI->getType()),
1857 ICmpInst::ICMP_NE)) {
1858 Value *Ptr = GEPI->getPointerOperand();
1859 add(Ptr, Constant::getNullValue(Ptr->getType()), ICmpInst::ICMP_NE,
1862 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
1863 const Type *SrcTy = CI->getSrcTy();
1865 unsigned ci = VN.getOrInsertVN(CI, Top);
1866 uint32_t W = VR.typeToWidth(SrcTy);
1868 ConstantRange CR = VR.range(ci, Top);
1870 if (CR.isFullSet()) return;
1872 switch (CI->getOpcode()) {
1874 case Instruction::ZExt:
1875 case Instruction::SExt:
1876 VR.applyRange(VN.getOrInsertVN(CI->getOperand(0), Top),
1877 CR.truncate(W), Top, this);
1879 case Instruction::BitCast:
1880 VR.applyRange(VN.getOrInsertVN(CI->getOperand(0), Top),
1887 /// opsToDef - A new relationship was discovered involving one of this
1888 /// instruction's operands. Find any new relationship involving the
1889 /// definition, or another operand.
1890 void opsToDef(Instruction *I) {
1891 Instruction *NewContext = below(I) ? I : TopInst;
1893 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1894 Value *Op0 = VN.canonicalize(BO->getOperand(0), Top);
1895 Value *Op1 = VN.canonicalize(BO->getOperand(1), Top);
1897 if (ConstantInt *CI0 = dyn_cast<ConstantInt>(Op0))
1898 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(Op1)) {
1899 add(BO, ConstantExpr::get(BO->getOpcode(), CI0, CI1),
1900 ICmpInst::ICMP_EQ, NewContext);
1904 // "%y = and i1 true, %x" then %x EQ %y
1905 // "%y = or i1 false, %x" then %x EQ %y
1906 // "%x = add i32 %y, 0" then %x EQ %y
1907 // "%x = mul i32 %y, 0" then %x EQ 0
1909 Instruction::BinaryOps Opcode = BO->getOpcode();
1910 const Type *Ty = BO->getType();
1911 assert(!Ty->isFPOrFPVector() && "Float in work queue!");
1913 Constant *Zero = Constant::getNullValue(Ty);
1914 ConstantInt *AllOnes = ConstantInt::getAllOnesValue(Ty);
1918 case Instruction::LShr:
1919 case Instruction::AShr:
1920 case Instruction::Shl:
1921 case Instruction::Sub:
1923 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1927 case Instruction::Or:
1928 if (Op0 == AllOnes || Op1 == AllOnes) {
1929 add(BO, AllOnes, ICmpInst::ICMP_EQ, NewContext);
1932 case Instruction::Xor:
1933 case Instruction::Add:
1935 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1937 } else if (Op1 == Zero) {
1938 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1942 case Instruction::And:
1943 if (Op0 == AllOnes) {
1944 add(BO, Op1, ICmpInst::ICMP_EQ, NewContext);
1946 } else if (Op1 == AllOnes) {
1947 add(BO, Op0, ICmpInst::ICMP_EQ, NewContext);
1951 case Instruction::Mul:
1952 if (Op0 == Zero || Op1 == Zero) {
1953 add(BO, Zero, ICmpInst::ICMP_EQ, NewContext);
1959 // "%x = add i32 %y, %z" and %x EQ %y then %z EQ 0
1960 // "%x = add i32 %y, %z" and %x EQ %z then %y EQ 0
1961 // "%x = shl i32 %y, %z" and %x EQ %y and %y NE 0 then %z EQ 0
1962 // "%x = udiv i32 %y, %z" and %x EQ %y then %z EQ 1
1964 Value *Known = Op0, *Unknown = Op1,
1965 *TheBO = VN.canonicalize(BO, Top);
1966 if (Known != TheBO) std::swap(Known, Unknown);
1967 if (Known == TheBO) {
1970 case Instruction::LShr:
1971 case Instruction::AShr:
1972 case Instruction::Shl:
1973 if (!isRelatedBy(Known, Zero, ICmpInst::ICMP_NE)) break;
1974 // otherwise, fall-through.
1975 case Instruction::Sub:
1976 if (Unknown == Op1) break;
1977 // otherwise, fall-through.
1978 case Instruction::Xor:
1979 case Instruction::Add:
1980 add(Unknown, Zero, ICmpInst::ICMP_EQ, NewContext);
1982 case Instruction::UDiv:
1983 case Instruction::SDiv:
1984 if (Unknown == Op1) break;
1985 if (isRelatedBy(Known, Zero, ICmpInst::ICMP_NE)) {
1986 Constant *One = ConstantInt::get(Ty, 1);
1987 add(Unknown, One, ICmpInst::ICMP_EQ, NewContext);
1993 // TODO: "%a = add i32 %b, 1" and %b > %z then %a >= %z.
1995 } else if (ICmpInst *IC = dyn_cast<ICmpInst>(I)) {
1996 // "%a = icmp ult i32 %b, %c" and %b u< %c then %a EQ true
1997 // "%a = icmp ult i32 %b, %c" and %b u>= %c then %a EQ false
2000 Value *Op0 = VN.canonicalize(IC->getOperand(0), Top);
2001 Value *Op1 = VN.canonicalize(IC->getOperand(1), Top);
2003 ICmpInst::Predicate Pred = IC->getPredicate();
2004 if (isRelatedBy(Op0, Op1, Pred))
2005 add(IC, ConstantInt::getTrue(), ICmpInst::ICMP_EQ, NewContext);
2006 else if (isRelatedBy(Op0, Op1, ICmpInst::getInversePredicate(Pred)))
2007 add(IC, ConstantInt::getFalse(), ICmpInst::ICMP_EQ, NewContext);
2009 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
2010 if (I->getType()->isFPOrFPVector()) return;
2012 // Given: "%a = select i1 %x, i32 %b, i32 %c"
2013 // %x EQ true then %a EQ %b
2014 // %x EQ false then %a EQ %c
2015 // %b EQ %c then %a EQ %b
2017 Value *Canonical = VN.canonicalize(SI->getCondition(), Top);
2018 if (Canonical == ConstantInt::getTrue()) {
2019 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
2020 } else if (Canonical == ConstantInt::getFalse()) {
2021 add(SI, SI->getFalseValue(), ICmpInst::ICMP_EQ, NewContext);
2022 } else if (VN.canonicalize(SI->getTrueValue(), Top) ==
2023 VN.canonicalize(SI->getFalseValue(), Top)) {
2024 add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
2026 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2027 const Type *DestTy = CI->getDestTy();
2028 if (DestTy->isFPOrFPVector()) return;
2030 Value *Op = VN.canonicalize(CI->getOperand(0), Top);
2031 Instruction::CastOps Opcode = CI->getOpcode();
2033 if (Constant *C = dyn_cast<Constant>(Op)) {
2034 add(CI, ConstantExpr::getCast(Opcode, C, DestTy),
2035 ICmpInst::ICMP_EQ, NewContext);
2038 uint32_t W = VR.typeToWidth(DestTy);
2039 unsigned ci = VN.getOrInsertVN(CI, Top);
2040 ConstantRange CR = VR.range(VN.getOrInsertVN(Op, Top), Top);
2042 if (!CR.isFullSet()) {
2045 case Instruction::ZExt:
2046 VR.applyRange(ci, CR.zeroExtend(W), Top, this);
2048 case Instruction::SExt:
2049 VR.applyRange(ci, CR.signExtend(W), Top, this);
2051 case Instruction::Trunc: {
2052 ConstantRange Result = CR.truncate(W);
2053 if (!Result.isFullSet())
2054 VR.applyRange(ci, Result, Top, this);
2056 case Instruction::BitCast:
2057 VR.applyRange(ci, CR, Top, this);
2059 // TODO: other casts?
2062 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
2063 for (GetElementPtrInst::op_iterator OI = GEPI->idx_begin(),
2064 OE = GEPI->idx_end(); OI != OE; ++OI) {
2065 ConstantInt *Op = dyn_cast<ConstantInt>(VN.canonicalize(*OI, Top));
2066 if (!Op || !Op->isZero()) return;
2068 // TODO: The GEPI indices are all zero. Copy from operand to definition,
2069 // jumping the type plane as needed.
2070 Value *Ptr = GEPI->getPointerOperand();
2071 if (isRelatedBy(Ptr, Constant::getNullValue(Ptr->getType()),
2072 ICmpInst::ICMP_NE)) {
2073 add(GEPI, Constant::getNullValue(GEPI->getType()), ICmpInst::ICMP_NE,
2079 /// solve - process the work queue
2081 //DOUT << "WorkList entry, size: " << WorkList.size() << "\n";
2082 while (!WorkList.empty()) {
2083 //DOUT << "WorkList size: " << WorkList.size() << "\n";
2085 Operation &O = WorkList.front();
2086 TopInst = O.ContextInst;
2087 TopBB = O.ContextBB;
2088 Top = DTDFS->getNodeForBlock(TopBB); // XXX move this into Context
2090 O.LHS = VN.canonicalize(O.LHS, Top);
2091 O.RHS = VN.canonicalize(O.RHS, Top);
2093 assert(O.LHS == VN.canonicalize(O.LHS, Top) && "Canonicalize isn't.");
2094 assert(O.RHS == VN.canonicalize(O.RHS, Top) && "Canonicalize isn't.");
2096 DOUT << "solving " << *O.LHS << " " << O.Op << " " << *O.RHS;
2097 if (O.ContextInst) DOUT << " context inst: " << *O.ContextInst;
2098 else DOUT << " context block: " << O.ContextBB->getName();
2105 // If they're both Constant, skip it. Check for contradiction and mark
2106 // the BB as unreachable if so.
2107 if (Constant *CI_L = dyn_cast<Constant>(O.LHS)) {
2108 if (Constant *CI_R = dyn_cast<Constant>(O.RHS)) {
2109 if (ConstantExpr::getCompare(O.Op, CI_L, CI_R) ==
2110 ConstantInt::getFalse())
2113 WorkList.pop_front();
2118 if (VN.compare(O.LHS, O.RHS)) {
2119 std::swap(O.LHS, O.RHS);
2120 O.Op = ICmpInst::getSwappedPredicate(O.Op);
2123 if (O.Op == ICmpInst::ICMP_EQ) {
2124 if (!makeEqual(O.RHS, O.LHS))
2127 LatticeVal LV = cmpInstToLattice(O.Op);
2129 if ((LV & EQ_BIT) &&
2130 isRelatedBy(O.LHS, O.RHS, ICmpInst::getSwappedPredicate(O.Op))) {
2131 if (!makeEqual(O.RHS, O.LHS))
2134 if (isRelatedBy(O.LHS, O.RHS, ICmpInst::getInversePredicate(O.Op))){
2136 WorkList.pop_front();
2140 unsigned n1 = VN.getOrInsertVN(O.LHS, Top);
2141 unsigned n2 = VN.getOrInsertVN(O.RHS, Top);
2144 if (O.Op != ICmpInst::ICMP_UGE && O.Op != ICmpInst::ICMP_ULE &&
2145 O.Op != ICmpInst::ICMP_SGE && O.Op != ICmpInst::ICMP_SLE)
2148 WorkList.pop_front();
2152 if (VR.isRelatedBy(n1, n2, Top, LV) ||
2153 IG.isRelatedBy(n1, n2, Top, LV)) {
2154 WorkList.pop_front();
2158 VR.addInequality(n1, n2, Top, LV, this);
2159 if ((!isa<ConstantInt>(O.RHS) && !isa<ConstantInt>(O.LHS)) ||
2161 IG.addInequality(n1, n2, Top, LV);
2163 if (Instruction *I1 = dyn_cast<Instruction>(O.LHS)) {
2164 if (aboveOrBelow(I1))
2167 if (isa<Instruction>(O.LHS) || isa<Argument>(O.LHS)) {
2168 for (Value::use_iterator UI = O.LHS->use_begin(),
2169 UE = O.LHS->use_end(); UI != UE;) {
2170 Use &TheUse = UI.getUse();
2172 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
2173 if (aboveOrBelow(I))
2178 if (Instruction *I2 = dyn_cast<Instruction>(O.RHS)) {
2179 if (aboveOrBelow(I2))
2182 if (isa<Instruction>(O.RHS) || isa<Argument>(O.RHS)) {
2183 for (Value::use_iterator UI = O.RHS->use_begin(),
2184 UE = O.RHS->use_end(); UI != UE;) {
2185 Use &TheUse = UI.getUse();
2187 if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
2188 if (aboveOrBelow(I))
2195 WorkList.pop_front();
2200 void ValueRanges::addToWorklist(Value *V, Constant *C,
2201 ICmpInst::Predicate Pred, VRPSolver *VRP) {
2202 VRP->add(V, C, Pred, VRP->TopInst);
2205 void ValueRanges::markBlock(VRPSolver *VRP) {
2206 VRP->UB.mark(VRP->TopBB);
2209 /// PredicateSimplifier - This class is a simplifier that replaces
2210 /// one equivalent variable with another. It also tracks what
2211 /// can't be equal and will solve setcc instructions when possible.
2212 /// @brief Root of the predicate simplifier optimization.
2213 class VISIBILITY_HIDDEN PredicateSimplifier : public FunctionPass {
2217 InequalityGraph *IG;
2218 UnreachableBlocks UB;
2221 std::vector<DomTreeDFS::Node *> WorkList;
2224 static char ID; // Pass identification, replacement for typeid
2225 PredicateSimplifier() : FunctionPass((intptr_t)&ID) {}
2227 bool runOnFunction(Function &F);
2229 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
2230 AU.addRequiredID(BreakCriticalEdgesID);
2231 AU.addRequired<DominatorTree>();
2232 AU.addRequired<TargetData>();
2233 AU.addPreserved<TargetData>();
2237 /// Forwards - Adds new properties into PropertySet and uses them to
2238 /// simplify instructions. Because new properties sometimes apply to
2239 /// a transition from one BasicBlock to another, this will use the
2240 /// PredicateSimplifier::proceedToSuccessor(s) interface to enter the
2241 /// basic block with the new PropertySet.
2242 /// @brief Performs abstract execution of the program.
2243 class VISIBILITY_HIDDEN Forwards : public InstVisitor<Forwards> {
2244 friend class InstVisitor<Forwards>;
2245 PredicateSimplifier *PS;
2246 DomTreeDFS::Node *DTNode;
2250 InequalityGraph &IG;
2251 UnreachableBlocks &UB;
2254 Forwards(PredicateSimplifier *PS, DomTreeDFS::Node *DTNode)
2255 : PS(PS), DTNode(DTNode), VN(*PS->VN), IG(*PS->IG), UB(PS->UB),
2258 void visitTerminatorInst(TerminatorInst &TI);
2259 void visitBranchInst(BranchInst &BI);
2260 void visitSwitchInst(SwitchInst &SI);
2262 void visitAllocaInst(AllocaInst &AI);
2263 void visitLoadInst(LoadInst &LI);
2264 void visitStoreInst(StoreInst &SI);
2266 void visitSExtInst(SExtInst &SI);
2267 void visitZExtInst(ZExtInst &ZI);
2269 void visitBinaryOperator(BinaryOperator &BO);
2270 void visitICmpInst(ICmpInst &IC);
2273 // Used by terminator instructions to proceed from the current basic
2274 // block to the next. Verifies that "current" dominates "next",
2275 // then calls visitBasicBlock.
2276 void proceedToSuccessors(DomTreeDFS::Node *Current) {
2277 for (DomTreeDFS::Node::iterator I = Current->begin(),
2278 E = Current->end(); I != E; ++I) {
2279 WorkList.push_back(*I);
2283 void proceedToSuccessor(DomTreeDFS::Node *Next) {
2284 WorkList.push_back(Next);
2287 // Visits each instruction in the basic block.
2288 void visitBasicBlock(DomTreeDFS::Node *Node) {
2289 BasicBlock *BB = Node->getBlock();
2290 DOUT << "Entering Basic Block: " << BB->getName()
2291 << " (" << Node->getDFSNumIn() << ")\n";
2292 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2293 visitInstruction(I++, Node);
2297 // Tries to simplify each Instruction and add new properties to
2299 void visitInstruction(Instruction *I, DomTreeDFS::Node *DT) {
2300 DOUT << "Considering instruction " << *I << "\n";
2305 // Sometimes instructions are killed in earlier analysis.
2306 if (isInstructionTriviallyDead(I)) {
2309 if (unsigned n = VN->valueNumber(I, DTDFS->getRootNode()))
2310 if (VN->value(n) == I) IG->remove(n);
2312 I->eraseFromParent();
2317 // Try to replace the whole instruction.
2318 Value *V = VN->canonicalize(I, DT);
2319 assert(V == I && "Late instruction canonicalization.");
2323 DOUT << "Removing " << *I << ", replacing with " << *V << "\n";
2324 if (unsigned n = VN->valueNumber(I, DTDFS->getRootNode()))
2325 if (VN->value(n) == I) IG->remove(n);
2327 I->replaceAllUsesWith(V);
2328 I->eraseFromParent();
2332 // Try to substitute operands.
2333 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2334 Value *Oper = I->getOperand(i);
2335 Value *V = VN->canonicalize(Oper, DT);
2336 assert(V == Oper && "Late operand canonicalization.");
2340 DOUT << "Resolving " << *I;
2341 I->setOperand(i, V);
2342 DOUT << " into " << *I;
2347 std::string name = I->getParent()->getName();
2348 DOUT << "push (%" << name << ")\n";
2349 Forwards visit(this, DT);
2351 DOUT << "pop (%" << name << ")\n";
2355 bool PredicateSimplifier::runOnFunction(Function &F) {
2356 DominatorTree *DT = &getAnalysis<DominatorTree>();
2357 DTDFS = new DomTreeDFS(DT);
2358 TargetData *TD = &getAnalysis<TargetData>();
2360 DOUT << "Entering Function: " << F.getName() << "\n";
2363 DomTreeDFS::Node *Root = DTDFS->getRootNode();
2364 VN = new ValueNumbering(DTDFS);
2365 IG = new InequalityGraph(*VN, Root);
2366 VR = new ValueRanges(*VN, TD);
2367 WorkList.push_back(Root);
2370 DomTreeDFS::Node *DTNode = WorkList.back();
2371 WorkList.pop_back();
2372 if (!UB.isDead(DTNode->getBlock())) visitBasicBlock(DTNode);
2373 } while (!WorkList.empty());
2379 modified |= UB.kill();
2384 void PredicateSimplifier::Forwards::visitTerminatorInst(TerminatorInst &TI) {
2385 PS->proceedToSuccessors(DTNode);
2388 void PredicateSimplifier::Forwards::visitBranchInst(BranchInst &BI) {
2389 if (BI.isUnconditional()) {
2390 PS->proceedToSuccessors(DTNode);
2394 Value *Condition = BI.getCondition();
2395 BasicBlock *TrueDest = BI.getSuccessor(0);
2396 BasicBlock *FalseDest = BI.getSuccessor(1);
2398 if (isa<Constant>(Condition) || TrueDest == FalseDest) {
2399 PS->proceedToSuccessors(DTNode);
2403 for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
2405 BasicBlock *Dest = (*I)->getBlock();
2406 DOUT << "Branch thinking about %" << Dest->getName()
2407 << "(" << PS->DTDFS->getNodeForBlock(Dest)->getDFSNumIn() << ")\n";
2409 if (Dest == TrueDest) {
2410 DOUT << "(" << DTNode->getBlock()->getName() << ") true set:\n";
2411 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
2412 VRP.add(ConstantInt::getTrue(), Condition, ICmpInst::ICMP_EQ);
2417 } else if (Dest == FalseDest) {
2418 DOUT << "(" << DTNode->getBlock()->getName() << ") false set:\n";
2419 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
2420 VRP.add(ConstantInt::getFalse(), Condition, ICmpInst::ICMP_EQ);
2427 PS->proceedToSuccessor(*I);
2431 void PredicateSimplifier::Forwards::visitSwitchInst(SwitchInst &SI) {
2432 Value *Condition = SI.getCondition();
2434 // Set the EQProperty in each of the cases BBs, and the NEProperties
2435 // in the default BB.
2437 for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
2439 BasicBlock *BB = (*I)->getBlock();
2440 DOUT << "Switch thinking about BB %" << BB->getName()
2441 << "(" << PS->DTDFS->getNodeForBlock(BB)->getDFSNumIn() << ")\n";
2443 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, BB);
2444 if (BB == SI.getDefaultDest()) {
2445 for (unsigned i = 1, e = SI.getNumCases(); i < e; ++i)
2446 if (SI.getSuccessor(i) != BB)
2447 VRP.add(Condition, SI.getCaseValue(i), ICmpInst::ICMP_NE);
2449 } else if (ConstantInt *CI = SI.findCaseDest(BB)) {
2450 VRP.add(Condition, CI, ICmpInst::ICMP_EQ);
2453 PS->proceedToSuccessor(*I);
2457 void PredicateSimplifier::Forwards::visitAllocaInst(AllocaInst &AI) {
2458 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &AI);
2459 VRP.add(Constant::getNullValue(AI.getType()), &AI, ICmpInst::ICMP_NE);
2463 void PredicateSimplifier::Forwards::visitLoadInst(LoadInst &LI) {
2464 Value *Ptr = LI.getPointerOperand();
2465 // avoid "load uint* null" -> null NE null.
2466 if (isa<Constant>(Ptr)) return;
2468 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &LI);
2469 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
2473 void PredicateSimplifier::Forwards::visitStoreInst(StoreInst &SI) {
2474 Value *Ptr = SI.getPointerOperand();
2475 if (isa<Constant>(Ptr)) return;
2477 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
2478 VRP.add(Constant::getNullValue(Ptr->getType()), Ptr, ICmpInst::ICMP_NE);
2482 void PredicateSimplifier::Forwards::visitSExtInst(SExtInst &SI) {
2483 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
2484 uint32_t SrcBitWidth = cast<IntegerType>(SI.getSrcTy())->getBitWidth();
2485 uint32_t DstBitWidth = cast<IntegerType>(SI.getDestTy())->getBitWidth();
2486 APInt Min(APInt::getHighBitsSet(DstBitWidth, DstBitWidth-SrcBitWidth+1));
2487 APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth-1));
2488 VRP.add(ConstantInt::get(Min), &SI, ICmpInst::ICMP_SLE);
2489 VRP.add(ConstantInt::get(Max), &SI, ICmpInst::ICMP_SGE);
2493 void PredicateSimplifier::Forwards::visitZExtInst(ZExtInst &ZI) {
2494 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &ZI);
2495 uint32_t SrcBitWidth = cast<IntegerType>(ZI.getSrcTy())->getBitWidth();
2496 uint32_t DstBitWidth = cast<IntegerType>(ZI.getDestTy())->getBitWidth();
2497 APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth));
2498 VRP.add(ConstantInt::get(Max), &ZI, ICmpInst::ICMP_UGE);
2502 void PredicateSimplifier::Forwards::visitBinaryOperator(BinaryOperator &BO) {
2503 Instruction::BinaryOps ops = BO.getOpcode();
2507 case Instruction::URem:
2508 case Instruction::SRem:
2509 case Instruction::UDiv:
2510 case Instruction::SDiv: {
2511 Value *Divisor = BO.getOperand(1);
2512 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2513 VRP.add(Constant::getNullValue(Divisor->getType()), Divisor,
2522 case Instruction::Shl: {
2523 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2524 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
2527 case Instruction::AShr: {
2528 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2529 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_SLE);
2532 case Instruction::LShr:
2533 case Instruction::UDiv: {
2534 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2535 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
2538 case Instruction::URem: {
2539 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2540 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
2543 case Instruction::And: {
2544 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2545 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_ULE);
2546 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_ULE);
2549 case Instruction::Or: {
2550 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
2551 VRP.add(&BO, BO.getOperand(0), ICmpInst::ICMP_UGE);
2552 VRP.add(&BO, BO.getOperand(1), ICmpInst::ICMP_UGE);
2558 void PredicateSimplifier::Forwards::visitICmpInst(ICmpInst &IC) {
2559 // If possible, squeeze the ICmp predicate into something simpler.
2560 // Eg., if x = [0, 4) and we're being asked icmp uge %x, 3 then change
2561 // the predicate to eq.
2563 // XXX: once we do full PHI handling, modifying the instruction in the
2564 // Forwards visitor will cause missed optimizations.
2566 ICmpInst::Predicate Pred = IC.getPredicate();
2570 case ICmpInst::ICMP_ULE: Pred = ICmpInst::ICMP_ULT; break;
2571 case ICmpInst::ICMP_UGE: Pred = ICmpInst::ICMP_UGT; break;
2572 case ICmpInst::ICMP_SLE: Pred = ICmpInst::ICMP_SLT; break;
2573 case ICmpInst::ICMP_SGE: Pred = ICmpInst::ICMP_SGT; break;
2575 if (Pred != IC.getPredicate()) {
2576 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &IC);
2577 if (VRP.isRelatedBy(IC.getOperand(1), IC.getOperand(0),
2578 ICmpInst::ICMP_NE)) {
2580 PS->modified = true;
2581 IC.setPredicate(Pred);
2585 Pred = IC.getPredicate();
2587 if (ConstantInt *Op1 = dyn_cast<ConstantInt>(IC.getOperand(1))) {
2588 ConstantInt *NextVal = 0;
2591 case ICmpInst::ICMP_SLT:
2592 case ICmpInst::ICMP_ULT:
2593 if (Op1->getValue() != 0)
2594 NextVal = ConstantInt::get(Op1->getValue()-1);
2596 case ICmpInst::ICMP_SGT:
2597 case ICmpInst::ICMP_UGT:
2598 if (!Op1->getValue().isAllOnesValue())
2599 NextVal = ConstantInt::get(Op1->getValue()+1);
2604 VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &IC);
2605 if (VRP.isRelatedBy(IC.getOperand(0), NextVal,
2606 ICmpInst::getInversePredicate(Pred))) {
2607 ICmpInst *NewIC = new ICmpInst(ICmpInst::ICMP_EQ, IC.getOperand(0),
2609 NewIC->takeName(&IC);
2610 IC.replaceAllUsesWith(NewIC);
2612 // XXX: prove this isn't necessary
2613 if (unsigned n = VN.valueNumber(&IC, PS->DTDFS->getRootNode()))
2614 if (VN.value(n) == &IC) IG.remove(n);
2617 IC.eraseFromParent();
2619 PS->modified = true;
2625 char PredicateSimplifier::ID = 0;
2626 RegisterPass<PredicateSimplifier> X("predsimplify",
2627 "Predicate Simplifier");
2630 FunctionPass *llvm::createPredicateSimplifierPass() {
2631 return new PredicateSimplifier();