bae8a92cdd02cf45fd0b774db897f744c160bfdf
[oota-llvm.git] / lib / Transforms / Scalar / CorrelatedValuePropagation.cpp
1 //===- CorrelatedValuePropagation.cpp - Propagate CFG-derived info --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Correlated Value Propagation pass.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "correlated-value-propagation"
15 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/Function.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Pass.h"
19 #include "llvm/Analysis/LazyValueInfo.h"
20 #include "llvm/Support/CFG.h"
21 #include "llvm/Transforms/Utils/Local.h"
22 #include "llvm/ADT/DepthFirstIterator.h"
23 #include "llvm/ADT/Statistic.h"
24 using namespace llvm;
25
26 STATISTIC(NumPhis,      "Number of phis propagated");
27 STATISTIC(NumSelects,   "Number of selects propagated");
28 STATISTIC(NumMemAccess, "Number of memory access targets propagated");
29 STATISTIC(NumCmps,      "Number of comparisons propagated");
30
31 namespace {
32   class CorrelatedValuePropagation : public FunctionPass {
33     LazyValueInfo *LVI;
34     
35     bool processSelect(SelectInst *SI);
36     bool processPHI(PHINode *P);
37     bool processMemAccess(Instruction *I);
38     bool processCmp(CmpInst *C);
39     
40   public:
41     static char ID;
42     CorrelatedValuePropagation(): FunctionPass(ID) { }
43     
44     bool runOnFunction(Function &F);
45     
46     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
47       AU.addRequired<LazyValueInfo>();
48     }
49   };
50 }
51
52 char CorrelatedValuePropagation::ID = 0;
53 INITIALIZE_PASS_BEGIN(CorrelatedValuePropagation, "correlated-propagation",
54                 "Value Propagation", false, false)
55 INITIALIZE_PASS_DEPENDENCY(LazyValueInfo)
56 INITIALIZE_PASS_END(CorrelatedValuePropagation, "correlated-propagation",
57                 "Value Propagation", false, false)
58
59 // Public interface to the Value Propagation pass
60 Pass *llvm::createCorrelatedValuePropagationPass() {
61   return new CorrelatedValuePropagation();
62 }
63
64 bool CorrelatedValuePropagation::processSelect(SelectInst *S) {
65   if (S->getType()->isVectorTy()) return false;
66   if (isa<Constant>(S->getOperand(0))) return false;
67   
68   Constant *C = LVI->getConstant(S->getOperand(0), S->getParent());
69   if (!C) return false;
70   
71   ConstantInt *CI = dyn_cast<ConstantInt>(C);
72   if (!CI) return false;
73   
74   S->replaceAllUsesWith(S->getOperand(CI->isOne() ? 1 : 2));
75   S->eraseFromParent();
76
77   ++NumSelects;
78   
79   return true;
80 }
81
82 bool CorrelatedValuePropagation::processPHI(PHINode *P) {
83   bool Changed = false;
84   
85   BasicBlock *BB = P->getParent();
86   for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) {
87     Value *Incoming = P->getIncomingValue(i);
88     if (isa<Constant>(Incoming)) continue;
89     
90     Constant *C = LVI->getConstantOnEdge(P->getIncomingValue(i),
91                                          P->getIncomingBlock(i),
92                                          BB);
93     if (!C) continue;
94     
95     P->setIncomingValue(i, C);
96     Changed = true;
97   }
98   
99   if (Value *ConstVal = P->hasConstantValue()) {
100     P->replaceAllUsesWith(ConstVal);
101     P->eraseFromParent();
102     Changed = true;
103   }
104   
105   ++NumPhis;
106   
107   return Changed;
108 }
109
110 bool CorrelatedValuePropagation::processMemAccess(Instruction *I) {
111   Value *Pointer = 0;
112   if (LoadInst *L = dyn_cast<LoadInst>(I))
113     Pointer = L->getPointerOperand();
114   else
115     Pointer = cast<StoreInst>(I)->getPointerOperand();
116   
117   if (isa<Constant>(Pointer)) return false;
118   
119   Constant *C = LVI->getConstant(Pointer, I->getParent());
120   if (!C) return false;
121   
122   ++NumMemAccess;
123   I->replaceUsesOfWith(Pointer, C);
124   return true;
125 }
126
127 /// processCmp - If the value of this comparison could be determined locally,
128 /// constant propagation would already have figured it out.  Instead, walk
129 /// the predecessors and statically evaluate the comparison based on information
130 /// available on that edge.  If a given static evaluation is true on ALL
131 /// incoming edges, then it's true universally and we can simplify the compare.
132 bool CorrelatedValuePropagation::processCmp(CmpInst *C) {
133   Value *Op0 = C->getOperand(0);
134   if (isa<Instruction>(Op0) &&
135       cast<Instruction>(Op0)->getParent() == C->getParent())
136     return false;
137   
138   Constant *Op1 = dyn_cast<Constant>(C->getOperand(1));
139   if (!Op1) return false;
140   
141   pred_iterator PI = pred_begin(C->getParent()), PE = pred_end(C->getParent());
142   if (PI == PE) return false;
143   
144   LazyValueInfo::Tristate Result = LVI->getPredicateOnEdge(C->getPredicate(), 
145                                     C->getOperand(0), Op1, *PI, C->getParent());
146   if (Result == LazyValueInfo::Unknown) return false;
147
148   ++PI;
149   while (PI != PE) {
150     LazyValueInfo::Tristate Res = LVI->getPredicateOnEdge(C->getPredicate(), 
151                                     C->getOperand(0), Op1, *PI, C->getParent());
152     if (Res != Result) return false;
153     ++PI;
154   }
155   
156   ++NumCmps;
157   
158   if (Result == LazyValueInfo::True)
159     C->replaceAllUsesWith(ConstantInt::getTrue(C->getContext()));
160   else
161     C->replaceAllUsesWith(ConstantInt::getFalse(C->getContext()));
162   
163   C->eraseFromParent();
164
165   return true;
166 }
167
168 bool CorrelatedValuePropagation::runOnFunction(Function &F) {
169   LVI = &getAnalysis<LazyValueInfo>();
170   
171   bool FnChanged = false;
172   
173   // Perform a depth-first walk of the CFG so that we don't waste time
174   // optimizing unreachable blocks.
175   for (df_iterator<BasicBlock*> FI = df_begin(&F.getEntryBlock()),
176        FE = df_end(&F.getEntryBlock()); FI != FE; ++FI) {
177     bool BBChanged = false;
178     for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
179       Instruction *II = BI++;
180       switch (II->getOpcode()) {
181       case Instruction::Select:
182         BBChanged |= processSelect(cast<SelectInst>(II));
183         break;
184       case Instruction::PHI:
185         BBChanged |= processPHI(cast<PHINode>(II));
186         break;
187       case Instruction::ICmp:
188       case Instruction::FCmp:
189         BBChanged |= processCmp(cast<CmpInst>(II));
190         break;
191       case Instruction::Load:
192       case Instruction::Store:
193         BBChanged |= processMemAccess(II);
194         break;
195       }
196     }
197     
198     // Propagating correlated values might leave cruft around.
199     // Try to clean it up before we continue.
200     if (BBChanged)
201       SimplifyInstructionsInBlock(*FI);
202     
203     FnChanged |= BBChanged;
204   }
205   
206   return FnChanged;
207 }