1 //===- CorrelatedValuePropagation.cpp - Propagate CFG-derived info --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Correlated Value Propagation pass.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "correlated-value-propagation"
15 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/Analysis/InstructionSimplify.h"
18 #include "llvm/Analysis/LazyValueInfo.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/Pass.h"
23 #include "llvm/Support/CFG.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Transforms/Utils/Local.h"
29 STATISTIC(NumPhis, "Number of phis propagated");
30 STATISTIC(NumSelects, "Number of selects propagated");
31 STATISTIC(NumMemAccess, "Number of memory access targets propagated");
32 STATISTIC(NumCmps, "Number of comparisons propagated");
33 STATISTIC(NumDeadCases, "Number of switch cases removed");
36 class CorrelatedValuePropagation : public FunctionPass {
39 bool processSelect(SelectInst *SI);
40 bool processPHI(PHINode *P);
41 bool processMemAccess(Instruction *I);
42 bool processCmp(CmpInst *C);
43 bool processSwitch(SwitchInst *SI);
47 CorrelatedValuePropagation(): FunctionPass(ID) {
48 initializeCorrelatedValuePropagationPass(*PassRegistry::getPassRegistry());
51 bool runOnFunction(Function &F);
53 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
54 AU.addRequired<LazyValueInfo>();
59 char CorrelatedValuePropagation::ID = 0;
60 INITIALIZE_PASS_BEGIN(CorrelatedValuePropagation, "correlated-propagation",
61 "Value Propagation", false, false)
62 INITIALIZE_PASS_DEPENDENCY(LazyValueInfo)
63 INITIALIZE_PASS_END(CorrelatedValuePropagation, "correlated-propagation",
64 "Value Propagation", false, false)
66 // Public interface to the Value Propagation pass
67 Pass *llvm::createCorrelatedValuePropagationPass() {
68 return new CorrelatedValuePropagation();
71 bool CorrelatedValuePropagation::processSelect(SelectInst *S) {
72 if (S->getType()->isVectorTy()) return false;
73 if (isa<Constant>(S->getOperand(0))) return false;
75 Constant *C = LVI->getConstant(S->getOperand(0), S->getParent());
78 ConstantInt *CI = dyn_cast<ConstantInt>(C);
79 if (!CI) return false;
81 Value *ReplaceWith = S->getOperand(1);
82 Value *Other = S->getOperand(2);
83 if (!CI->isOne()) std::swap(ReplaceWith, Other);
84 if (ReplaceWith == S) ReplaceWith = UndefValue::get(S->getType());
86 S->replaceAllUsesWith(ReplaceWith);
94 bool CorrelatedValuePropagation::processPHI(PHINode *P) {
97 BasicBlock *BB = P->getParent();
98 for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) {
99 Value *Incoming = P->getIncomingValue(i);
100 if (isa<Constant>(Incoming)) continue;
102 Value *V = LVI->getConstantOnEdge(Incoming, P->getIncomingBlock(i), BB);
104 // Look if the incoming value is a select with a constant but LVI tells us
105 // that the incoming value can never be that constant. In that case replace
106 // the incoming value with the other value of the select. This often allows
107 // us to remove the select later.
109 SelectInst *SI = dyn_cast<SelectInst>(Incoming);
112 Constant *C = dyn_cast<Constant>(SI->getFalseValue());
115 if (LVI->getPredicateOnEdge(ICmpInst::ICMP_EQ, SI, C,
116 P->getIncomingBlock(i), BB) !=
117 LazyValueInfo::False)
120 DEBUG(dbgs() << "CVP: Threading PHI over " << *SI << '\n');
121 V = SI->getTrueValue();
124 P->setIncomingValue(i, V);
128 if (Value *V = SimplifyInstruction(P)) {
129 P->replaceAllUsesWith(V);
130 P->eraseFromParent();
140 bool CorrelatedValuePropagation::processMemAccess(Instruction *I) {
142 if (LoadInst *L = dyn_cast<LoadInst>(I))
143 Pointer = L->getPointerOperand();
145 Pointer = cast<StoreInst>(I)->getPointerOperand();
147 if (isa<Constant>(Pointer)) return false;
149 Constant *C = LVI->getConstant(Pointer, I->getParent());
150 if (!C) return false;
153 I->replaceUsesOfWith(Pointer, C);
157 /// processCmp - If the value of this comparison could be determined locally,
158 /// constant propagation would already have figured it out. Instead, walk
159 /// the predecessors and statically evaluate the comparison based on information
160 /// available on that edge. If a given static evaluation is true on ALL
161 /// incoming edges, then it's true universally and we can simplify the compare.
162 bool CorrelatedValuePropagation::processCmp(CmpInst *C) {
163 Value *Op0 = C->getOperand(0);
164 if (isa<Instruction>(Op0) &&
165 cast<Instruction>(Op0)->getParent() == C->getParent())
168 Constant *Op1 = dyn_cast<Constant>(C->getOperand(1));
169 if (!Op1) return false;
171 pred_iterator PI = pred_begin(C->getParent()), PE = pred_end(C->getParent());
172 if (PI == PE) return false;
174 LazyValueInfo::Tristate Result = LVI->getPredicateOnEdge(C->getPredicate(),
175 C->getOperand(0), Op1, *PI, C->getParent());
176 if (Result == LazyValueInfo::Unknown) return false;
180 LazyValueInfo::Tristate Res = LVI->getPredicateOnEdge(C->getPredicate(),
181 C->getOperand(0), Op1, *PI, C->getParent());
182 if (Res != Result) return false;
188 if (Result == LazyValueInfo::True)
189 C->replaceAllUsesWith(ConstantInt::getTrue(C->getContext()));
191 C->replaceAllUsesWith(ConstantInt::getFalse(C->getContext()));
193 C->eraseFromParent();
198 /// processSwitch - Simplify a switch instruction by removing cases which can
199 /// never fire. If the uselessness of a case could be determined locally then
200 /// constant propagation would already have figured it out. Instead, walk the
201 /// predecessors and statically evaluate cases based on information available
202 /// on that edge. Cases that cannot fire no matter what the incoming edge can
203 /// safely be removed. If a case fires on every incoming edge then the entire
204 /// switch can be removed and replaced with a branch to the case destination.
205 bool CorrelatedValuePropagation::processSwitch(SwitchInst *SI) {
206 Value *Cond = SI->getCondition();
207 BasicBlock *BB = SI->getParent();
209 // If the condition was defined in same block as the switch then LazyValueInfo
210 // currently won't say anything useful about it, though in theory it could.
211 if (isa<Instruction>(Cond) && cast<Instruction>(Cond)->getParent() == BB)
214 // If the switch is unreachable then trying to improve it is a waste of time.
215 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
216 if (PB == PE) return false;
218 // Analyse each switch case in turn. This is done in reverse order so that
219 // removing a case doesn't cause trouble for the iteration.
220 bool Changed = false;
221 for (SwitchInst::CaseIt CI = SI->case_end(), CE = SI->case_begin(); CI-- != CE;
223 ConstantInt *Case = CI.getCaseValue();
225 // Check to see if the switch condition is equal to/not equal to the case
226 // value on every incoming edge, equal/not equal being the same each time.
227 LazyValueInfo::Tristate State = LazyValueInfo::Unknown;
228 for (pred_iterator PI = PB; PI != PE; ++PI) {
229 // Is the switch condition equal to the case value?
230 LazyValueInfo::Tristate Value = LVI->getPredicateOnEdge(CmpInst::ICMP_EQ,
231 Cond, Case, *PI, BB);
232 // Give up on this case if nothing is known.
233 if (Value == LazyValueInfo::Unknown) {
234 State = LazyValueInfo::Unknown;
238 // If this was the first edge to be visited, record that all other edges
239 // need to give the same result.
245 // If this case is known to fire for some edges and known not to fire for
246 // others then there is nothing we can do - give up.
247 if (Value != State) {
248 State = LazyValueInfo::Unknown;
253 if (State == LazyValueInfo::False) {
254 // This case never fires - remove it.
255 CI.getCaseSuccessor()->removePredecessor(BB);
256 SI->removeCase(CI); // Does not invalidate the iterator.
258 // The condition can be modified by removePredecessor's PHI simplification
260 Cond = SI->getCondition();
264 } else if (State == LazyValueInfo::True) {
265 // This case always fires. Arrange for the switch to be turned into an
266 // unconditional branch by replacing the switch condition with the case
268 SI->setCondition(Case);
269 NumDeadCases += SI->getNumCases();
276 // If the switch has been simplified to the point where it can be replaced
277 // by a branch then do so now.
278 ConstantFoldTerminator(BB);
283 bool CorrelatedValuePropagation::runOnFunction(Function &F) {
284 LVI = &getAnalysis<LazyValueInfo>();
286 bool FnChanged = false;
288 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
289 bool BBChanged = false;
290 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
291 Instruction *II = BI++;
292 switch (II->getOpcode()) {
293 case Instruction::Select:
294 BBChanged |= processSelect(cast<SelectInst>(II));
296 case Instruction::PHI:
297 BBChanged |= processPHI(cast<PHINode>(II));
299 case Instruction::ICmp:
300 case Instruction::FCmp:
301 BBChanged |= processCmp(cast<CmpInst>(II));
303 case Instruction::Load:
304 case Instruction::Store:
305 BBChanged |= processMemAccess(II);
310 Instruction *Term = FI->getTerminator();
311 switch (Term->getOpcode()) {
312 case Instruction::Switch:
313 BBChanged |= processSwitch(cast<SwitchInst>(Term));
317 FnChanged |= BBChanged;