blob: 9b7f1284566b39a5b7d99f431a62466237c98c17 [file] [log] [blame]
Nick Lewycky05450ae2006-08-28 22:44:55 +00001//===-- PredicateSimplifier.cpp - Path Sensitive Simplifier -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Nick Lewycky and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===------------------------------------------------------------------===//
9//
10// Path-sensitive optimizer. In a branch where x == y, replace uses of
11// x with y. Permits further optimization, such as the elimination of
12// the unreachable call:
13//
14// void test(int *p, int *q)
15// {
16// if (p != q)
17// return;
18//
19// if (*p != *q)
20// foo(); // unreachable
21// }
22//
23//===------------------------------------------------------------------===//
24//
25// This optimization works by substituting %q for %p when protected by a
Nick Lewycky3947a762006-08-30 02:46:48 +000026// conditional that assures us of that fact. Properties are stored as
27// relationships between two values.
Nick Lewycky05450ae2006-08-28 22:44:55 +000028//
29//===------------------------------------------------------------------===//
30
Nick Lewycky05450ae2006-08-28 22:44:55 +000031#define DEBUG_TYPE "predsimplify"
32#include "llvm/Transforms/Scalar.h"
33#include "llvm/Constants.h"
Nick Lewycky802fe272006-10-22 19:53:27 +000034#include "llvm/DerivedTypes.h"
Nick Lewycky05450ae2006-08-28 22:44:55 +000035#include "llvm/Instructions.h"
36#include "llvm/Pass.h"
37#include "llvm/ADT/Statistic.h"
38#include "llvm/ADT/STLExtras.h"
39#include "llvm/Analysis/Dominators.h"
40#include "llvm/Support/CFG.h"
41#include "llvm/Support/Debug.h"
Nick Lewycky078ff412006-10-12 02:02:44 +000042#include "llvm/Support/InstVisitor.h"
Nick Lewycky05450ae2006-08-28 22:44:55 +000043#include <iostream>
Nick Lewyckye63bf952006-10-25 23:48:24 +000044#include <list>
Nick Lewycky05450ae2006-08-28 22:44:55 +000045using namespace llvm;
46
Nick Lewyckydc08cd52006-09-10 02:27:07 +000047typedef DominatorTree::Node DTNodeType;
48
Nick Lewycky05450ae2006-08-28 22:44:55 +000049namespace {
50 Statistic<>
51 NumVarsReplaced("predsimplify", "Number of argument substitutions");
52 Statistic<>
Nick Lewycky3947a762006-08-30 02:46:48 +000053 NumInstruction("predsimplify", "Number of instructions removed");
Nick Lewycky05450ae2006-08-28 22:44:55 +000054
Nick Lewycky406fc0c2006-09-20 17:04:01 +000055 class PropertySet;
Nick Lewycky05450ae2006-08-28 22:44:55 +000056
Nick Lewyckydc08cd52006-09-10 02:27:07 +000057 /// Similar to EquivalenceClasses, this stores the set of equivalent
Nick Lewycky406fc0c2006-09-20 17:04:01 +000058 /// types. Beyond EquivalenceClasses, it allows us to specify which
59 /// element will act as leader.
60 template<typename ElemTy>
Nick Lewyckydc08cd52006-09-10 02:27:07 +000061 class VISIBILITY_HIDDEN Synonyms {
62 std::map<ElemTy, unsigned> mapping;
63 std::vector<ElemTy> leaders;
Nick Lewycky406fc0c2006-09-20 17:04:01 +000064 PropertySet *PS;
Nick Lewyckydc08cd52006-09-10 02:27:07 +000065
66 public:
67 typedef unsigned iterator;
68 typedef const unsigned const_iterator;
69
Nick Lewycky406fc0c2006-09-20 17:04:01 +000070 Synonyms(PropertySet *PS) : PS(PS) {}
71
Nick Lewyckydc08cd52006-09-10 02:27:07 +000072 // Inspection
73
74 bool empty() const {
75 return leaders.empty();
76 }
77
Nick Lewyckye63bf952006-10-25 23:48:24 +000078 iterator findLeader(ElemTy &e) {
Nick Lewyckydc08cd52006-09-10 02:27:07 +000079 typename std::map<ElemTy, unsigned>::iterator MI = mapping.find(e);
80 if (MI == mapping.end()) return 0;
81
82 return MI->second;
83 }
84
Nick Lewyckye63bf952006-10-25 23:48:24 +000085 const_iterator findLeader(ElemTy &e) const {
Nick Lewyckydc08cd52006-09-10 02:27:07 +000086 typename std::map<ElemTy, unsigned>::const_iterator MI =
87 mapping.find(e);
88 if (MI == mapping.end()) return 0;
89
90 return MI->second;
91 }
92
93 ElemTy &getLeader(iterator I) {
Nick Lewycky025f4c02006-09-18 21:09:35 +000094 assert(I && I <= leaders.size() && "Illegal leader to get.");
Nick Lewyckydc08cd52006-09-10 02:27:07 +000095 return leaders[I-1];
96 }
97
98 const ElemTy &getLeader(const_iterator I) const {
Nick Lewycky025f4c02006-09-18 21:09:35 +000099 assert(I && I <= leaders.size() && "Illegal leaders to get.");
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000100 return leaders[I-1];
101 }
102
103#ifdef DEBUG
104 void debug(std::ostream &os) const {
105 for (unsigned i = 1, e = leaders.size()+1; i != e; ++i) {
Nick Lewycky668a1d02006-09-13 19:32:53 +0000106 os << i << ". " << *getLeader(i) << ": [";
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000107 for (std::map<Value *, unsigned>::const_iterator
108 I = mapping.begin(), E = mapping.end(); I != E; ++I) {
109 if ((*I).second == i && (*I).first != leaders[i-1]) {
110 os << *(*I).first << " ";
Nick Lewycky977be252006-09-13 19:24:01 +0000111 }
112 }
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000113 os << "]\n";
114 }
115 }
116#endif
117
118 // Mutators
119
Nick Lewyckye63bf952006-10-25 23:48:24 +0000120 void remove(ElemTy &e) {
121 ElemTy E = e; // The parameter to erase must not be a reference to
122 mapping.erase(E); // an element contained in the map.
123 }
124
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000125 /// Combine two sets referring to the same element, inserting the
126 /// elements as needed. Returns a valid iterator iff two already
127 /// existing disjoint synonym sets were combined. The iterator
Nick Lewycky406fc0c2006-09-20 17:04:01 +0000128 /// points to the no longer existing element.
129 iterator unionSets(ElemTy E1, ElemTy E2);
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000130
131 /// Returns an iterator pointing to the synonym set containing
132 /// element e. If none exists, a new one is created and returned.
Nick Lewyckye63bf952006-10-25 23:48:24 +0000133 iterator findOrInsert(ElemTy &e) {
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000134 iterator I = findLeader(e);
135 if (I) return I;
136
137 leaders.push_back(e);
138 I = leaders.size();
139 mapping[e] = I;
140 return I;
141 }
142 };
143
Nick Lewycky05450ae2006-08-28 22:44:55 +0000144 /// Represents the set of equivalent Value*s and provides insertion
145 /// and fast lookup. Also stores the set of inequality relationships.
146 class PropertySet {
Nick Lewycky8f389d82006-09-23 15:13:08 +0000147 /// Returns true if V1 is a better choice than V2.
Nick Lewycky406fc0c2006-09-20 17:04:01 +0000148 bool compare(Value *V1, Value *V2) const {
149 if (isa<Constant>(V1)) {
150 if (!isa<Constant>(V2)) {
151 return true;
152 }
153 } else if (isa<Argument>(V1)) {
154 if (!isa<Constant>(V2) && !isa<Argument>(V2)) {
155 return true;
156 }
157 }
158 if (Instruction *I1 = dyn_cast<Instruction>(V1)) {
159 if (Instruction *I2 = dyn_cast<Instruction>(V2)) {
160 BasicBlock *BB1 = I1->getParent(),
161 *BB2 = I2->getParent();
162 if (BB1 == BB2) {
163 for (BasicBlock::const_iterator I = BB1->begin(), E = BB1->end();
164 I != E; ++I) {
165 if (&*I == I1) return true;
166 if (&*I == I2) return false;
167 }
168 assert(0 && "Instructions not found in parent BasicBlock?");
169 } else
170 return DT->getNode(BB1)->properlyDominates(DT->getNode(BB2));
171 }
172 }
173 return false;
174 }
175
Nick Lewycky05450ae2006-08-28 22:44:55 +0000176 struct Property;
177 public:
Nick Lewycky406fc0c2006-09-20 17:04:01 +0000178 /// Choose the canonical Value in a synonym set.
179 /// Leaves the more canonical choice in V1.
180 void order(Value *&V1, Value *&V2) const {
181 if (compare(V2, V1)) std::swap(V1, V2);
182 }
183
184 PropertySet(DominatorTree *DT) : union_find(this), DT(DT) {}
185
Nick Lewycky078ff412006-10-12 02:02:44 +0000186 Synonyms<Value *> union_find;
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000187
Nick Lewycky05450ae2006-08-28 22:44:55 +0000188 typedef std::vector<Property>::iterator PropertyIterator;
189 typedef std::vector<Property>::const_iterator ConstPropertyIterator;
Nick Lewycky406fc0c2006-09-20 17:04:01 +0000190 typedef Synonyms<Value *>::iterator SynonymIterator;
Nick Lewycky05450ae2006-08-28 22:44:55 +0000191
192 enum Ops {
193 EQ,
194 NE
195 };
196
197 Value *canonicalize(Value *V) const {
198 Value *C = lookup(V);
199 return C ? C : V;
200 }
201
202 Value *lookup(Value *V) const {
Nick Lewycky406fc0c2006-09-20 17:04:01 +0000203 SynonymIterator SI = union_find.findLeader(V);
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000204 if (!SI) return NULL;
205 return union_find.getLeader(SI);
Nick Lewycky05450ae2006-08-28 22:44:55 +0000206 }
207
208 bool empty() const {
Nick Lewycky3947a762006-08-30 02:46:48 +0000209 return union_find.empty();
Nick Lewycky05450ae2006-08-28 22:44:55 +0000210 }
211
Nick Lewyckye63bf952006-10-25 23:48:24 +0000212 void remove(Value *V) {
213 SynonymIterator I = union_find.findLeader(V);
214 if (!I) return;
215
216 union_find.remove(V);
217
218 for (PropertyIterator PI = Properties.begin(), PE = Properties.end();
219 PI != PE;) {
220 Property &P = *PI++;
221 if (P.I1 == I || P.I2 == I) Properties.erase(PI);
222 }
223 }
224
Nick Lewycky05450ae2006-08-28 22:44:55 +0000225 void addEqual(Value *V1, Value *V2) {
Nick Lewyckya3a68bd2006-09-02 19:40:38 +0000226 // If %x = 0. and %y = -0., seteq %x, %y is true, but
227 // copysign(%x) is not the same as copysign(%y).
Nick Lewycky977be252006-09-13 19:24:01 +0000228 if (V1->getType()->isFloatingPoint()) return;
Nick Lewyckya3a68bd2006-09-02 19:40:38 +0000229
Nick Lewycky05450ae2006-08-28 22:44:55 +0000230 order(V1, V2);
231 if (isa<Constant>(V2)) return; // refuse to set false == true.
232
Nick Lewyckye63bf952006-10-25 23:48:24 +0000233 if (union_find.findLeader(V1) &&
234 union_find.findLeader(V1) == union_find.findLeader(V2))
235 return; // no-op
236
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000237 SynonymIterator deleted = union_find.unionSets(V1, V2);
238 if (deleted) {
239 SynonymIterator replacement = union_find.findLeader(V1);
240 // Move Properties
241 for (PropertyIterator I = Properties.begin(), E = Properties.end();
242 I != E; ++I) {
243 if (I->I1 == deleted) I->I1 = replacement;
244 else if (I->I1 > deleted) --I->I1;
245 if (I->I2 == deleted) I->I2 = replacement;
246 else if (I->I2 > deleted) --I->I2;
247 }
248 }
Nick Lewycky05450ae2006-08-28 22:44:55 +0000249 addImpliedProperties(EQ, V1, V2);
250 }
251
252 void addNotEqual(Value *V1, Value *V2) {
Nick Lewyckya3a68bd2006-09-02 19:40:38 +0000253 // If %x = NAN then seteq %x, %x is false.
Nick Lewycky977be252006-09-13 19:24:01 +0000254 if (V1->getType()->isFloatingPoint()) return;
255
256 // For example, %x = setne int 0, 0 causes "0 != 0".
257 if (isa<Constant>(V1) && isa<Constant>(V2)) return;
Nick Lewyckya3a68bd2006-09-02 19:40:38 +0000258
Nick Lewycky6e39c7e2006-08-31 00:39:16 +0000259 if (findProperty(NE, V1, V2) != Properties.end())
Nick Lewyckye63bf952006-10-25 23:48:24 +0000260 return; // no-op.
Nick Lewycky05450ae2006-08-28 22:44:55 +0000261
262 // Add the property.
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000263 SynonymIterator I1 = union_find.findOrInsert(V1),
264 I2 = union_find.findOrInsert(V2);
Nick Lewycky977be252006-09-13 19:24:01 +0000265
266 // Technically this means that the block is unreachable.
267 if (I1 == I2) return;
268
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000269 Properties.push_back(Property(NE, I1, I2));
Nick Lewycky05450ae2006-08-28 22:44:55 +0000270 addImpliedProperties(NE, V1, V2);
271 }
272
273 PropertyIterator findProperty(Ops Opcode, Value *V1, Value *V2) {
274 assert(Opcode != EQ && "Can't findProperty on EQ."
275 "Use the lookup method instead.");
276
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000277 SynonymIterator I1 = union_find.findLeader(V1),
278 I2 = union_find.findLeader(V2);
279 if (!I1 || !I2) return Properties.end();
Nick Lewycky05450ae2006-08-28 22:44:55 +0000280
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000281 return
282 find(Properties.begin(), Properties.end(), Property(Opcode, I1, I2));
Nick Lewycky05450ae2006-08-28 22:44:55 +0000283 }
284
285 ConstPropertyIterator
286 findProperty(Ops Opcode, Value *V1, Value *V2) const {
287 assert(Opcode != EQ && "Can't findProperty on EQ."
288 "Use the lookup method instead.");
289
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000290 SynonymIterator I1 = union_find.findLeader(V1),
291 I2 = union_find.findLeader(V2);
292 if (!I1 || !I2) return Properties.end();
Nick Lewycky05450ae2006-08-28 22:44:55 +0000293
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000294 return
295 find(Properties.begin(), Properties.end(), Property(Opcode, I1, I2));
Nick Lewycky05450ae2006-08-28 22:44:55 +0000296 }
297
298 private:
299 // Represents Head OP [Tail1, Tail2, ...]
300 // For example: %x != %a, %x != %b.
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000301 struct VISIBILITY_HIDDEN Property {
Nick Lewycky406fc0c2006-09-20 17:04:01 +0000302 typedef SynonymIterator Iter;
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000303
304 Property(Ops opcode, Iter i1, Iter i2)
305 : Opcode(opcode), I1(i1), I2(i2)
Nick Lewyckya3a68bd2006-09-02 19:40:38 +0000306 { assert(opcode != EQ && "Equality belongs in the synonym set, "
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000307 "not a property."); }
308
309 bool operator==(const Property &P) const {
310 return (Opcode == P.Opcode) &&
311 ((I1 == P.I1 && I2 == P.I2) ||
312 (I1 == P.I2 && I2 == P.I1));
313 }
Nick Lewycky05450ae2006-08-28 22:44:55 +0000314
Nick Lewycky05450ae2006-08-28 22:44:55 +0000315 Ops Opcode;
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000316 Iter I1, I2;
Nick Lewycky05450ae2006-08-28 22:44:55 +0000317 };
318
Nick Lewycky05450ae2006-08-28 22:44:55 +0000319 void add(Ops Opcode, Value *V1, Value *V2, bool invert) {
320 switch (Opcode) {
321 case EQ:
322 if (invert) addNotEqual(V1, V2);
323 else addEqual(V1, V2);
324 break;
325 case NE:
326 if (invert) addEqual(V1, V2);
327 else addNotEqual(V1, V2);
328 break;
329 default:
330 assert(0 && "Unknown property opcode.");
331 }
332 }
333
Nick Lewyckye63bf952006-10-25 23:48:24 +0000334 void addToResolve(Value *V, std::list<Value *> &WorkList) {
335 if (!isa<Constant>(V) && !isa<BasicBlock>(V)) {
336 for (Value::use_iterator UI = V->use_begin(), UE = V->use_end();
337 UI != UE; ++UI) {
338 if (!isa<Constant>(*UI) && !isa<BasicBlock>(*UI)) {
339 WorkList.push_back(*UI);
340 }
341 }
342 }
343 }
344
345 void resolve(std::list<Value *> &WorkList) {
346 if (WorkList.empty()) return;
347
348 Value *V = WorkList.front();
349 WorkList.pop_front();
350
351 if (empty()) return;
352
353 Instruction *I = dyn_cast<Instruction>(V);
354 if (!I) return;
355
356 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
357 Value *lhs = canonicalize(BO->getOperand(0)),
358 *rhs = canonicalize(BO->getOperand(1));
359
360 ConstantIntegral *CI1 = dyn_cast<ConstantIntegral>(lhs),
361 *CI2 = dyn_cast<ConstantIntegral>(rhs);
362
363 if (CI1 && CI2) {
364 addToResolve(BO, WorkList);
365 addEqual(BO, ConstantExpr::get(BO->getOpcode(), CI1, CI2));
366 } else if (SetCondInst *SCI = dyn_cast<SetCondInst>(BO)) {
367 PropertySet::ConstPropertyIterator NE =
368 findProperty(PropertySet::NE, lhs, rhs);
369
370 if (NE != Properties.end()) {
371 switch (SCI->getOpcode()) {
372 case Instruction::SetEQ:
373 addToResolve(SCI, WorkList);
374 addEqual(SCI, ConstantBool::getFalse());
375 break;
376 case Instruction::SetNE:
377 addToResolve(SCI, WorkList);
378 addEqual(SCI, ConstantBool::getTrue());
379 break;
380 case Instruction::SetLE:
381 case Instruction::SetGE:
382 case Instruction::SetLT:
383 case Instruction::SetGT:
384 break;
385 default:
386 assert(0 && "Unknown opcode in SetCondInst.");
387 break;
388 }
389 }
390 }
391 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
392 Value *Condition = canonicalize(SI->getCondition());
393 if (ConstantBool *CB = dyn_cast<ConstantBool>(Condition)) {
394 addToResolve(SI, WorkList);
395 addEqual(SI, CB->getValue() ? SI->getTrueValue() : SI->getFalseValue());
396 }
397 }
398 if (!WorkList.empty()) resolve(WorkList);
399 }
400
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000401 // Finds the properties implied by an equivalence and adds them too.
Nick Lewycky05450ae2006-08-28 22:44:55 +0000402 // Example: ("seteq %a, %b", true, EQ) --> (%a, %b, EQ)
403 // ("seteq %a, %b", false, EQ) --> (%a, %b, NE)
404 void addImpliedProperties(Ops Opcode, Value *V1, Value *V2) {
405 order(V1, V2);
406
407 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V2)) {
408 switch (BO->getOpcode()) {
409 case Instruction::SetEQ:
Chris Lattner47811b72006-09-28 23:35:22 +0000410 if (ConstantBool *V1CB = dyn_cast<ConstantBool>(V1))
411 add(Opcode, BO->getOperand(0), BO->getOperand(1),!V1CB->getValue());
Nick Lewycky05450ae2006-08-28 22:44:55 +0000412 break;
413 case Instruction::SetNE:
Chris Lattner47811b72006-09-28 23:35:22 +0000414 if (ConstantBool *V1CB = dyn_cast<ConstantBool>(V1))
415 add(Opcode, BO->getOperand(0), BO->getOperand(1), V1CB->getValue());
Nick Lewycky05450ae2006-08-28 22:44:55 +0000416 break;
417 case Instruction::SetLT:
418 case Instruction::SetGT:
Chris Lattner47811b72006-09-28 23:35:22 +0000419 if (V1 == ConstantBool::getTrue())
Nick Lewycky05450ae2006-08-28 22:44:55 +0000420 add(Opcode, BO->getOperand(0), BO->getOperand(1), true);
421 break;
422 case Instruction::SetLE:
423 case Instruction::SetGE:
Chris Lattner47811b72006-09-28 23:35:22 +0000424 if (V1 == ConstantBool::getFalse())
Nick Lewycky05450ae2006-08-28 22:44:55 +0000425 add(Opcode, BO->getOperand(0), BO->getOperand(1), true);
426 break;
Nick Lewyckye63bf952006-10-25 23:48:24 +0000427 case Instruction::And: {
428 // "and int %a, %b" EQ 0xff then %a EQ 0xff and %b EQ 0xff
429 // "and bool %a, %b" EQ true then %a EQ true and %b EQ true
430 // "and bool %a, %b" NE false then %a EQ true and %b EQ true
431 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V1)) {
432 if (Opcode == EQ && CI->isAllOnesValue()) {
433 addEqual(CI, BO->getOperand(0));
434 addEqual(CI, BO->getOperand(1));
435 } else if (Opcode == NE && CI == ConstantBool::getFalse()) {
436 addEqual(ConstantBool::getTrue(), BO->getOperand(0));
437 addEqual(ConstantBool::getTrue(), BO->getOperand(1));
438 }
Nick Lewycky05450ae2006-08-28 22:44:55 +0000439 }
Nick Lewyckye63bf952006-10-25 23:48:24 +0000440 } break;
441 case Instruction::Or: {
442 // "or int %a, %b" EQ 0 then %a EQ 0 and %b EQ 0
443 // "or bool %a, %b" EQ false then %a EQ false and %b EQ false
444 // "or bool %a, %b" NE true then %a EQ false and %b EQ false
445 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V1)) {
446 if (Opcode == EQ && CI->isNullValue()) {
447 addEqual(CI, BO->getOperand(0));
448 addEqual(CI, BO->getOperand(1));
449 } else if (Opcode == NE && CI == ConstantBool::getTrue()) {
450 addEqual(ConstantBool::getFalse(), BO->getOperand(0));
451 addEqual(ConstantBool::getFalse(), BO->getOperand(1));
452 }
Nick Lewycky05450ae2006-08-28 22:44:55 +0000453 }
Nick Lewyckye63bf952006-10-25 23:48:24 +0000454 } break;
455 case Instruction::Xor: {
456 // "xor bool true, %a" EQ true then %a = false
457 // "xor bool true, %a" EQ false then %a = true
458 // "xor bool false, %a" EQ true then %a = true
459 // "xor bool false, %a" EQ false then %a = false
460 // 1. Repeat all of the above, with "NE false" in place of
461 // "EQ true" and "NE true" in place of "EQ false".
462 // "xor int %c, %a" EQ %c then %a = 0
463 // "xor int %c, %a" NE %c then %a != 0
464 // 2. Repeat all of the above, with the operands swapped.
465
466 Value *LHS = BO->getOperand(0), *RHS = BO->getOperand(1);
467 if (!isa<Constant>(LHS)) std::swap(LHS, RHS);
468
469 if (ConstantBool *CB = dyn_cast<ConstantBool>(V1)) {
470 if (ConstantBool *A = dyn_cast<ConstantBool>(LHS)) {
471 addEqual(RHS, ConstantBool::get(A->getValue() ^ CB->getValue()
472 ^ Opcode==NE));
473 }
Nick Lewycky05450ae2006-08-28 22:44:55 +0000474 }
Nick Lewyckye63bf952006-10-25 23:48:24 +0000475 else if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V1)) {
476 if (ConstantIntegral *A = dyn_cast<ConstantIntegral>(LHS)) {
477 if (A == CI)
478 add(Opcode, RHS, Constant::getNullValue(A->getType()), false);
479 }
Chris Lattneref2aa192006-10-24 00:36:21 +0000480 }
Nick Lewyckye63bf952006-10-25 23:48:24 +0000481 } break;
Nick Lewycky05450ae2006-08-28 22:44:55 +0000482 default:
483 break;
484 }
Nick Lewyckya3a68bd2006-09-02 19:40:38 +0000485 } else if (SelectInst *SI = dyn_cast<SelectInst>(V2)) {
Chris Lattner47811b72006-09-28 23:35:22 +0000486 ConstantBool *True = ConstantBool::get(Opcode==EQ),
487 *False = ConstantBool::get(Opcode!=EQ);
Nick Lewyckya3a68bd2006-09-02 19:40:38 +0000488
489 if (V1 == SI->getTrueValue())
490 addEqual(SI->getCondition(), True);
491 else if (V1 == SI->getFalseValue())
492 addEqual(SI->getCondition(), False);
Nick Lewycky05450ae2006-08-28 22:44:55 +0000493 }
Nick Lewyckye63bf952006-10-25 23:48:24 +0000494
495 std::list<Value *> WorkList;
496 addToResolve(V1, WorkList);
497 addToResolve(V2, WorkList);
498 resolve(WorkList);
Nick Lewycky05450ae2006-08-28 22:44:55 +0000499 }
500
Nick Lewycky406fc0c2006-09-20 17:04:01 +0000501 DominatorTree *DT;
Nick Lewycky05450ae2006-08-28 22:44:55 +0000502 public:
Nick Lewyckya3a68bd2006-09-02 19:40:38 +0000503#ifdef DEBUG
Nick Lewycky05450ae2006-08-28 22:44:55 +0000504 void debug(std::ostream &os) const {
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000505 static const char *OpcodeTable[] = { "EQ", "NE" };
506
507 union_find.debug(os);
508 for (std::vector<Property>::const_iterator I = Properties.begin(),
509 E = Properties.end(); I != E; ++I) {
510 os << (*I).I1 << " " << OpcodeTable[(*I).Opcode] << " "
511 << (*I).I2 << "\n";
Nick Lewycky6e39c7e2006-08-31 00:39:16 +0000512 }
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000513 os << "\n";
Nick Lewycky05450ae2006-08-28 22:44:55 +0000514 }
Nick Lewyckya3a68bd2006-09-02 19:40:38 +0000515#endif
Nick Lewycky05450ae2006-08-28 22:44:55 +0000516
517 std::vector<Property> Properties;
518 };
519
520 /// PredicateSimplifier - This class is a simplifier that replaces
521 /// one equivalent variable with another. It also tracks what
522 /// can't be equal and will solve setcc instructions when possible.
Nick Lewyckye63bf952006-10-25 23:48:24 +0000523 class PredicateSimplifier : public FunctionPass {
Nick Lewycky05450ae2006-08-28 22:44:55 +0000524 public:
525 bool runOnFunction(Function &F);
526 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
527
528 private:
Nick Lewycky078ff412006-10-12 02:02:44 +0000529 /// Forwards - Adds new properties into PropertySet and uses them to
530 /// simplify instructions. Because new properties sometimes apply to
531 /// a transition from one BasicBlock to another, this will use the
532 /// PredicateSimplifier::proceedToSuccessor(s) interface to enter the
533 /// basic block with the new PropertySet.
534 class Forwards : public InstVisitor<Forwards> {
535 friend class InstVisitor<Forwards>;
536 PredicateSimplifier *PS;
537 public:
538 PropertySet &KP;
539
540 Forwards(PredicateSimplifier *PS, PropertySet &KP) : PS(PS), KP(KP) {}
541
542 // Tries to simplify each Instruction and add new properties to
543 // the PropertySet. Returns true if it erase the instruction.
544 //void visitInstruction(Instruction *I);
545
546 void visitTerminatorInst(TerminatorInst &TI);
547 void visitBranchInst(BranchInst &BI);
548 void visitSwitchInst(SwitchInst &SI);
549
Nick Lewycky802fe272006-10-22 19:53:27 +0000550 void visitAllocaInst(AllocaInst &AI);
Nick Lewycky078ff412006-10-12 02:02:44 +0000551 void visitLoadInst(LoadInst &LI);
552 void visitStoreInst(StoreInst &SI);
553 void visitBinaryOperator(BinaryOperator &BO);
554 };
Nick Lewycky05450ae2006-08-28 22:44:55 +0000555
556 // Used by terminator instructions to proceed from the current basic
557 // block to the next. Verifies that "current" dominates "next",
558 // then calls visitBasicBlock.
Nick Lewycky025f4c02006-09-18 21:09:35 +0000559 void proceedToSuccessors(PropertySet &CurrentPS, BasicBlock *Current);
Nick Lewycky078ff412006-10-12 02:02:44 +0000560 void proceedToSuccessor(PropertySet &Properties, BasicBlock *Next);
Nick Lewycky05450ae2006-08-28 22:44:55 +0000561
562 // Visits each instruction in the basic block.
Nick Lewycky025f4c02006-09-18 21:09:35 +0000563 void visitBasicBlock(BasicBlock *Block, PropertySet &KnownProperties);
Nick Lewycky05450ae2006-08-28 22:44:55 +0000564
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000565 // Tries to simplify each Instruction and add new properties to
Nick Lewycky078ff412006-10-12 02:02:44 +0000566 // the PropertySet.
Nick Lewycky025f4c02006-09-18 21:09:35 +0000567 void visitInstruction(Instruction *I, PropertySet &);
Nick Lewycky05450ae2006-08-28 22:44:55 +0000568
569 DominatorTree *DT;
570 bool modified;
571 };
572
573 RegisterPass<PredicateSimplifier> X("predsimplify",
574 "Predicate Simplifier");
Nick Lewycky406fc0c2006-09-20 17:04:01 +0000575
576 template <typename ElemTy>
577 typename Synonyms<ElemTy>::iterator
578 Synonyms<ElemTy>::unionSets(ElemTy E1, ElemTy E2) {
579 PS->order(E1, E2);
580
581 iterator I1 = findLeader(E1),
582 I2 = findLeader(E2);
583
584 if (!I1 && !I2) { // neither entry is in yet
585 leaders.push_back(E1);
586 I1 = leaders.size();
587 mapping[E1] = I1;
588 mapping[E2] = I1;
589 return 0;
590 }
591
592 if (!I1 && I2) {
593 mapping[E1] = I2;
594 std::swap(getLeader(I2), E1);
595 return 0;
596 }
597
598 if (I1 && !I2) {
599 mapping[E2] = I1;
600 return 0;
601 }
602
603 if (I1 == I2) return 0;
604
605 // This is the case where we have two sets, [%a1, %a2, %a3] and
606 // [%p1, %p2, %p3] and someone says that %a2 == %p3. We need to
607 // combine the two synsets.
608
609 if (I1 > I2) --I1;
610
611 for (std::map<Value *, unsigned>::iterator I = mapping.begin(),
612 E = mapping.end(); I != E; ++I) {
613 if (I->second == I2) I->second = I1;
614 else if (I->second > I2) --I->second;
615 }
616
617 leaders.erase(leaders.begin() + I2 - 1);
618
619 return I2;
620 }
Nick Lewycky05450ae2006-08-28 22:44:55 +0000621}
622
623FunctionPass *llvm::createPredicateSimplifierPass() {
624 return new PredicateSimplifier();
625}
626
627bool PredicateSimplifier::runOnFunction(Function &F) {
628 DT = &getAnalysis<DominatorTree>();
629
630 modified = false;
Nick Lewycky406fc0c2006-09-20 17:04:01 +0000631 PropertySet KnownProperties(DT);
Nick Lewycky025f4c02006-09-18 21:09:35 +0000632 visitBasicBlock(DT->getRootNode()->getBlock(), KnownProperties);
Nick Lewycky05450ae2006-08-28 22:44:55 +0000633 return modified;
634}
635
636void PredicateSimplifier::getAnalysisUsage(AnalysisUsage &AU) const {
Nick Lewycky5c8c5d92006-10-03 14:52:23 +0000637 AU.addRequiredID(BreakCriticalEdgesID);
Nick Lewycky05450ae2006-08-28 22:44:55 +0000638 AU.addRequired<DominatorTree>();
Nick Lewycky025f4c02006-09-18 21:09:35 +0000639 AU.setPreservesCFG();
Nick Lewycky5c8c5d92006-10-03 14:52:23 +0000640 AU.addPreservedID(BreakCriticalEdgesID);
Nick Lewycky05450ae2006-08-28 22:44:55 +0000641}
642
Nick Lewycky025f4c02006-09-18 21:09:35 +0000643void PredicateSimplifier::visitBasicBlock(BasicBlock *BB,
Nick Lewycky05450ae2006-08-28 22:44:55 +0000644 PropertySet &KnownProperties) {
Nick Lewyckycf2112a2006-09-13 18:55:37 +0000645 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Nick Lewycky025f4c02006-09-18 21:09:35 +0000646 visitInstruction(I++, KnownProperties);
Nick Lewycky05450ae2006-08-28 22:44:55 +0000647 }
648}
649
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000650void PredicateSimplifier::visitInstruction(Instruction *I,
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000651 PropertySet &KnownProperties) {
Nick Lewyckydc08cd52006-09-10 02:27:07 +0000652 // Try to replace the whole instruction.
Nick Lewyckye63bf952006-10-25 23:48:24 +0000653 Value *V = KnownProperties.canonicalize(I);
Nick Lewyckya3a68bd2006-09-02 19:40:38 +0000654 if (V != I) {
655 modified = true;
656 ++NumInstruction;
Nick Lewycky406fc0c2006-09-20 17:04:01 +0000657 DEBUG(std::cerr << "Removing " << *I);
Nick Lewyckye63bf952006-10-25 23:48:24 +0000658 KnownProperties.remove(I);
Nick Lewyckya3a68bd2006-09-02 19:40:38 +0000659 I->replaceAllUsesWith(V);
Nick Lewyckycf2112a2006-09-13 18:55:37 +0000660 I->eraseFromParent();
Nick Lewyckya3a68bd2006-09-02 19:40:38 +0000661 return;
662 }
663
664 // Try to substitute operands.
665 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Nick Lewycky05450ae2006-08-28 22:44:55 +0000666 Value *Oper = I->getOperand(i);
Nick Lewyckye63bf952006-10-25 23:48:24 +0000667 Value *V = KnownProperties.canonicalize(Oper);
Nick Lewycky05450ae2006-08-28 22:44:55 +0000668 if (V != Oper) {
669 modified = true;
670 ++NumVarsReplaced;
Nick Lewycky8f389d82006-09-23 15:13:08 +0000671 DEBUG(std::cerr << "Resolving " << *I);
Nick Lewycky05450ae2006-08-28 22:44:55 +0000672 I->setOperand(i, V);
673 DEBUG(std::cerr << "into " << *I);
674 }
675 }
676
Nick Lewycky078ff412006-10-12 02:02:44 +0000677 Forwards visit(this, KnownProperties);
678 visit.visit(*I);
Nick Lewycky05450ae2006-08-28 22:44:55 +0000679}
680
Nick Lewycky025f4c02006-09-18 21:09:35 +0000681void PredicateSimplifier::proceedToSuccessors(PropertySet &KP,
682 BasicBlock *BBCurrent) {
683 DTNodeType *Current = DT->getNode(BBCurrent);
684 for (DTNodeType::iterator I = Current->begin(), E = Current->end();
685 I != E; ++I) {
686 PropertySet Copy(KP);
687 visitBasicBlock((*I)->getBlock(), Copy);
688 }
Nick Lewycky05450ae2006-08-28 22:44:55 +0000689}
690
Nick Lewycky078ff412006-10-12 02:02:44 +0000691void PredicateSimplifier::proceedToSuccessor(PropertySet &KP, BasicBlock *BB) {
692 visitBasicBlock(BB, KP);
Nick Lewycky05450ae2006-08-28 22:44:55 +0000693}
694
Nick Lewycky078ff412006-10-12 02:02:44 +0000695void PredicateSimplifier::Forwards::visitTerminatorInst(TerminatorInst &TI) {
696 PS->proceedToSuccessors(KP, TI.getParent());
697}
Nick Lewycky025f4c02006-09-18 21:09:35 +0000698
Nick Lewycky078ff412006-10-12 02:02:44 +0000699void PredicateSimplifier::Forwards::visitBranchInst(BranchInst &BI) {
700 BasicBlock *BB = BI.getParent();
701
702 if (BI.isUnconditional()) {
703 PS->proceedToSuccessors(KP, BB);
Nick Lewycky05450ae2006-08-28 22:44:55 +0000704 return;
705 }
706
Nick Lewycky078ff412006-10-12 02:02:44 +0000707 Value *Condition = BI.getCondition();
Nick Lewycky05450ae2006-08-28 22:44:55 +0000708
Nick Lewycky078ff412006-10-12 02:02:44 +0000709 BasicBlock *TrueDest = BI.getSuccessor(0),
710 *FalseDest = BI.getSuccessor(1);
Nick Lewycky3947a762006-08-30 02:46:48 +0000711
Nick Lewyckyf9380992006-10-03 17:36:01 +0000712 if (isa<ConstantBool>(Condition) || TrueDest == FalseDest) {
Nick Lewycky078ff412006-10-12 02:02:44 +0000713 PS->proceedToSuccessors(KP, BB);
Nick Lewycky3947a762006-08-30 02:46:48 +0000714 return;
715 }
716
Nick Lewycky078ff412006-10-12 02:02:44 +0000717 DTNodeType *Node = PS->DT->getNode(BB);
Nick Lewycky025f4c02006-09-18 21:09:35 +0000718 for (DTNodeType::iterator I = Node->begin(), E = Node->end(); I != E; ++I) {
Nick Lewyckyf9380992006-10-03 17:36:01 +0000719 BasicBlock *Dest = (*I)->getBlock();
720 PropertySet DestProperties(KP);
Nick Lewycky05450ae2006-08-28 22:44:55 +0000721
Nick Lewyckyf9380992006-10-03 17:36:01 +0000722 if (Dest == TrueDest)
723 DestProperties.addEqual(ConstantBool::getTrue(), Condition);
724 else if (Dest == FalseDest)
725 DestProperties.addEqual(ConstantBool::getFalse(), Condition);
Nick Lewycky025f4c02006-09-18 21:09:35 +0000726
Nick Lewycky078ff412006-10-12 02:02:44 +0000727 PS->proceedToSuccessor(DestProperties, Dest);
Nick Lewycky025f4c02006-09-18 21:09:35 +0000728 }
Nick Lewycky05450ae2006-08-28 22:44:55 +0000729}
730
Nick Lewycky078ff412006-10-12 02:02:44 +0000731void PredicateSimplifier::Forwards::visitSwitchInst(SwitchInst &SI) {
732 Value *Condition = SI.getCondition();
Nick Lewycky05450ae2006-08-28 22:44:55 +0000733
734 // Set the EQProperty in each of the cases BBs,
735 // and the NEProperties in the default BB.
736 PropertySet DefaultProperties(KP);
737
Nick Lewycky078ff412006-10-12 02:02:44 +0000738 DTNodeType *Node = PS->DT->getNode(SI.getParent());
Nick Lewycky025f4c02006-09-18 21:09:35 +0000739 for (DTNodeType::iterator I = Node->begin(), E = Node->end(); I != E; ++I) {
740 BasicBlock *BB = (*I)->getBlock();
Nick Lewycky05450ae2006-08-28 22:44:55 +0000741
Nick Lewyckya73a6542006-10-03 15:19:11 +0000742 PropertySet BBProperties(KP);
Nick Lewycky078ff412006-10-12 02:02:44 +0000743 if (BB == SI.getDefaultDest()) {
744 for (unsigned i = 1, e = SI.getNumCases(); i < e; ++i)
745 if (SI.getSuccessor(i) != BB)
746 BBProperties.addNotEqual(Condition, SI.getCaseValue(i));
747 } else if (ConstantInt *CI = SI.findCaseDest(BB)) {
Nick Lewyckya73a6542006-10-03 15:19:11 +0000748 BBProperties.addEqual(Condition, CI);
749 }
Nick Lewycky078ff412006-10-12 02:02:44 +0000750 PS->proceedToSuccessor(BBProperties, BB);
Nick Lewycky05450ae2006-08-28 22:44:55 +0000751 }
Nick Lewycky05450ae2006-08-28 22:44:55 +0000752}
753
Nick Lewycky802fe272006-10-22 19:53:27 +0000754void PredicateSimplifier::Forwards::visitAllocaInst(AllocaInst &AI) {
755 KP.addNotEqual(Constant::getNullValue(AI.getType()), &AI);
756}
757
Nick Lewycky078ff412006-10-12 02:02:44 +0000758void PredicateSimplifier::Forwards::visitLoadInst(LoadInst &LI) {
759 Value *Ptr = LI.getPointerOperand();
Nick Lewycky05450ae2006-08-28 22:44:55 +0000760 KP.addNotEqual(Constant::getNullValue(Ptr->getType()), Ptr);
761}
762
Nick Lewycky078ff412006-10-12 02:02:44 +0000763void PredicateSimplifier::Forwards::visitStoreInst(StoreInst &SI) {
764 Value *Ptr = SI.getPointerOperand();
Nick Lewycky05450ae2006-08-28 22:44:55 +0000765 KP.addNotEqual(Constant::getNullValue(Ptr->getType()), Ptr);
766}
767
Nick Lewycky078ff412006-10-12 02:02:44 +0000768void PredicateSimplifier::Forwards::visitBinaryOperator(BinaryOperator &BO) {
769 Instruction::BinaryOps ops = BO.getOpcode();
Nick Lewycky05450ae2006-08-28 22:44:55 +0000770
Nick Lewycky3947a762006-08-30 02:46:48 +0000771 switch (ops) {
772 case Instruction::Div:
773 case Instruction::Rem: {
Nick Lewycky078ff412006-10-12 02:02:44 +0000774 Value *Divisor = BO.getOperand(1);
Nick Lewycky3947a762006-08-30 02:46:48 +0000775 KP.addNotEqual(Constant::getNullValue(Divisor->getType()), Divisor);
776 break;
777 }
778 default:
779 break;
780 }
Nick Lewycky05450ae2006-08-28 22:44:55 +0000781}