Reformat.
[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 #include "llvm/Transforms/Scalar.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
17 #include "llvm/Analysis/LazyValueInfo.h"
18 #include "llvm/IR/CFG.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Transforms/Utils/Local.h"
27 using namespace llvm;
28
29 #define DEBUG_TYPE "correlated-value-propagation"
30
31 STATISTIC(NumPhis,      "Number of phis propagated");
32 STATISTIC(NumSelects,   "Number of selects propagated");
33 STATISTIC(NumMemAccess, "Number of memory access targets propagated");
34 STATISTIC(NumCmps,      "Number of comparisons propagated");
35 STATISTIC(NumDeadCases, "Number of switch cases removed");
36
37 namespace {
38   class CorrelatedValuePropagation : public FunctionPass {
39     LazyValueInfo *LVI;
40
41     bool processSelect(SelectInst *SI);
42     bool processPHI(PHINode *P);
43     bool processMemAccess(Instruction *I);
44     bool processCmp(CmpInst *C);
45     bool processSwitch(SwitchInst *SI);
46
47   public:
48     static char ID;
49     CorrelatedValuePropagation(): FunctionPass(ID) {
50      initializeCorrelatedValuePropagationPass(*PassRegistry::getPassRegistry());
51     }
52
53     bool runOnFunction(Function &F) override;
54
55     void getAnalysisUsage(AnalysisUsage &AU) const override {
56       AU.addRequired<LazyValueInfo>();
57     }
58   };
59 }
60
61 char CorrelatedValuePropagation::ID = 0;
62 INITIALIZE_PASS_BEGIN(CorrelatedValuePropagation, "correlated-propagation",
63                 "Value Propagation", false, false)
64 INITIALIZE_PASS_DEPENDENCY(LazyValueInfo)
65 INITIALIZE_PASS_END(CorrelatedValuePropagation, "correlated-propagation",
66                 "Value Propagation", false, false)
67
68 // Public interface to the Value Propagation pass
69 Pass *llvm::createCorrelatedValuePropagationPass() {
70   return new CorrelatedValuePropagation();
71 }
72
73 bool CorrelatedValuePropagation::processSelect(SelectInst *S) {
74   if (S->getType()->isVectorTy()) return false;
75   if (isa<Constant>(S->getOperand(0))) return false;
76
77   Constant *C = LVI->getConstant(S->getOperand(0), S->getParent(), S);
78   if (!C) return false;
79
80   ConstantInt *CI = dyn_cast<ConstantInt>(C);
81   if (!CI) return false;
82
83   Value *ReplaceWith = S->getOperand(1);
84   Value *Other = S->getOperand(2);
85   if (!CI->isOne()) std::swap(ReplaceWith, Other);
86   if (ReplaceWith == S) ReplaceWith = UndefValue::get(S->getType());
87
88   S->replaceAllUsesWith(ReplaceWith);
89   S->eraseFromParent();
90
91   ++NumSelects;
92
93   return true;
94 }
95
96 bool CorrelatedValuePropagation::processPHI(PHINode *P) {
97   bool Changed = false;
98
99   BasicBlock *BB = P->getParent();
100   for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) {
101     Value *Incoming = P->getIncomingValue(i);
102     if (isa<Constant>(Incoming)) continue;
103
104     Value *V = LVI->getConstantOnEdge(Incoming, P->getIncomingBlock(i), BB, P);
105
106     // Look if the incoming value is a select with a scalar condition for which
107     // LVI can tells us the value. In that case replace the incoming value with
108     // the appropriate value of the select. This often allows us to remove the
109     // select later.
110     if (!V) {
111       SelectInst *SI = dyn_cast<SelectInst>(Incoming);
112       if (!SI) continue;
113
114       Value *Condition = SI->getCondition();
115       if (!Condition->getType()->isVectorTy()) {
116         if (Constant *C = LVI->getConstantOnEdge(Condition, P->getIncomingBlock(i), BB, P)) {
117           if (C == ConstantInt::getTrue(Condition->getType())) {
118             V = SI->getTrueValue();
119           } else {
120             V = SI->getFalseValue();
121           }
122           // Once LVI learns to handle vector types, we could also add support
123           // for vector type constants that are not all zeroes or all ones.
124         }
125       }
126
127       // Look if the select has a constant but LVI tells us that the incoming
128       // value can never be that constant. In that case replace the incoming
129       // value with the other value of the select. This often allows us to
130       // remove the select later.
131       if (!V) {
132         Constant *C = dyn_cast<Constant>(SI->getFalseValue());
133         if (!C) continue;
134
135         if (LVI->getPredicateOnEdge(ICmpInst::ICMP_EQ, SI, C,
136               P->getIncomingBlock(i), BB, P) !=
137             LazyValueInfo::False)
138           continue;
139         V = SI->getTrueValue();
140       }
141
142       DEBUG(dbgs() << "CVP: Threading PHI over " << *SI << '\n');
143     }
144
145     P->setIncomingValue(i, V);
146     Changed = true;
147   }
148
149   // FIXME: Provide TLI, DT, AT to SimplifyInstruction.
150   const DataLayout &DL = BB->getModule()->getDataLayout();
151   if (Value *V = SimplifyInstruction(P, DL)) {
152     P->replaceAllUsesWith(V);
153     P->eraseFromParent();
154     Changed = true;
155   }
156
157   if (Changed)
158     ++NumPhis;
159
160   return Changed;
161 }
162
163 bool CorrelatedValuePropagation::processMemAccess(Instruction *I) {
164   Value *Pointer = nullptr;
165   if (LoadInst *L = dyn_cast<LoadInst>(I))
166     Pointer = L->getPointerOperand();
167   else
168     Pointer = cast<StoreInst>(I)->getPointerOperand();
169
170   if (isa<Constant>(Pointer)) return false;
171
172   Constant *C = LVI->getConstant(Pointer, I->getParent(), I);
173   if (!C) return false;
174
175   ++NumMemAccess;
176   I->replaceUsesOfWith(Pointer, C);
177   return true;
178 }
179
180 /// processCmp - If the value of this comparison could be determined locally,
181 /// constant propagation would already have figured it out.  Instead, walk
182 /// the predecessors and statically evaluate the comparison based on information
183 /// available on that edge.  If a given static evaluation is true on ALL
184 /// incoming edges, then it's true universally and we can simplify the compare.
185 bool CorrelatedValuePropagation::processCmp(CmpInst *C) {
186   Value *Op0 = C->getOperand(0);
187   if (isa<Instruction>(Op0) &&
188       cast<Instruction>(Op0)->getParent() == C->getParent())
189     return false;
190
191   Constant *Op1 = dyn_cast<Constant>(C->getOperand(1));
192   if (!Op1) return false;
193
194   pred_iterator PI = pred_begin(C->getParent()), PE = pred_end(C->getParent());
195   if (PI == PE) return false;
196
197   LazyValueInfo::Tristate Result = LVI->getPredicateOnEdge(C->getPredicate(),
198                                     C->getOperand(0), Op1, *PI,
199                                     C->getParent(), C);
200   if (Result == LazyValueInfo::Unknown) return false;
201
202   ++PI;
203   while (PI != PE) {
204     LazyValueInfo::Tristate Res = LVI->getPredicateOnEdge(C->getPredicate(),
205                                     C->getOperand(0), Op1, *PI,
206                                     C->getParent(), C);
207     if (Res != Result) return false;
208     ++PI;
209   }
210
211   ++NumCmps;
212
213   if (Result == LazyValueInfo::True)
214     C->replaceAllUsesWith(ConstantInt::getTrue(C->getContext()));
215   else
216     C->replaceAllUsesWith(ConstantInt::getFalse(C->getContext()));
217
218   C->eraseFromParent();
219
220   return true;
221 }
222
223 /// processSwitch - Simplify a switch instruction by removing cases which can
224 /// never fire.  If the uselessness of a case could be determined locally then
225 /// constant propagation would already have figured it out.  Instead, walk the
226 /// predecessors and statically evaluate cases based on information available
227 /// on that edge.  Cases that cannot fire no matter what the incoming edge can
228 /// safely be removed.  If a case fires on every incoming edge then the entire
229 /// switch can be removed and replaced with a branch to the case destination.
230 bool CorrelatedValuePropagation::processSwitch(SwitchInst *SI) {
231   Value *Cond = SI->getCondition();
232   BasicBlock *BB = SI->getParent();
233
234   // If the condition was defined in same block as the switch then LazyValueInfo
235   // currently won't say anything useful about it, though in theory it could.
236   if (isa<Instruction>(Cond) && cast<Instruction>(Cond)->getParent() == BB)
237     return false;
238
239   // If the switch is unreachable then trying to improve it is a waste of time.
240   pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
241   if (PB == PE) return false;
242
243   // Analyse each switch case in turn.  This is done in reverse order so that
244   // removing a case doesn't cause trouble for the iteration.
245   bool Changed = false;
246   for (SwitchInst::CaseIt CI = SI->case_end(), CE = SI->case_begin(); CI-- != CE;
247        ) {
248     ConstantInt *Case = CI.getCaseValue();
249
250     // Check to see if the switch condition is equal to/not equal to the case
251     // value on every incoming edge, equal/not equal being the same each time.
252     LazyValueInfo::Tristate State = LazyValueInfo::Unknown;
253     for (pred_iterator PI = PB; PI != PE; ++PI) {
254       // Is the switch condition equal to the case value?
255       LazyValueInfo::Tristate Value = LVI->getPredicateOnEdge(CmpInst::ICMP_EQ,
256                                                               Cond, Case, *PI,
257                                                               BB, SI);
258       // Give up on this case if nothing is known.
259       if (Value == LazyValueInfo::Unknown) {
260         State = LazyValueInfo::Unknown;
261         break;
262       }
263
264       // If this was the first edge to be visited, record that all other edges
265       // need to give the same result.
266       if (PI == PB) {
267         State = Value;
268         continue;
269       }
270
271       // If this case is known to fire for some edges and known not to fire for
272       // others then there is nothing we can do - give up.
273       if (Value != State) {
274         State = LazyValueInfo::Unknown;
275         break;
276       }
277     }
278
279     if (State == LazyValueInfo::False) {
280       // This case never fires - remove it.
281       CI.getCaseSuccessor()->removePredecessor(BB);
282       SI->removeCase(CI); // Does not invalidate the iterator.
283
284       // The condition can be modified by removePredecessor's PHI simplification
285       // logic.
286       Cond = SI->getCondition();
287
288       ++NumDeadCases;
289       Changed = true;
290     } else if (State == LazyValueInfo::True) {
291       // This case always fires.  Arrange for the switch to be turned into an
292       // unconditional branch by replacing the switch condition with the case
293       // value.
294       SI->setCondition(Case);
295       NumDeadCases += SI->getNumCases();
296       Changed = true;
297       break;
298     }
299   }
300
301   if (Changed)
302     // If the switch has been simplified to the point where it can be replaced
303     // by a branch then do so now.
304     ConstantFoldTerminator(BB);
305
306   return Changed;
307 }
308
309 bool CorrelatedValuePropagation::runOnFunction(Function &F) {
310   if (skipOptnoneFunction(F))
311     return false;
312
313   LVI = &getAnalysis<LazyValueInfo>();
314
315   bool FnChanged = false;
316
317   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
318     bool BBChanged = false;
319     for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
320       Instruction *II = BI++;
321       switch (II->getOpcode()) {
322       case Instruction::Select:
323         BBChanged |= processSelect(cast<SelectInst>(II));
324         break;
325       case Instruction::PHI:
326         BBChanged |= processPHI(cast<PHINode>(II));
327         break;
328       case Instruction::ICmp:
329       case Instruction::FCmp:
330         BBChanged |= processCmp(cast<CmpInst>(II));
331         break;
332       case Instruction::Load:
333       case Instruction::Store:
334         BBChanged |= processMemAccess(II);
335         break;
336       }
337     }
338
339     Instruction *Term = FI->getTerminator();
340     switch (Term->getOpcode()) {
341     case Instruction::Switch:
342       BBChanged |= processSwitch(cast<SwitchInst>(Term));
343       break;
344     }
345
346     FnChanged |= BBChanged;
347   }
348
349   return FnChanged;
350 }