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