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/Constants.h"
17 #include "llvm/Function.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Pass.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/Analysis/LazyValueInfo.h"
22 #include "llvm/Support/CFG.h"
23 #include "llvm/Transforms/Utils/Local.h"
24 #include "llvm/ADT/Statistic.h"
27 STATISTIC(NumPhis, "Number of phis propagated");
28 STATISTIC(NumSelects, "Number of selects propagated");
29 STATISTIC(NumMemAccess, "Number of memory access targets propagated");
30 STATISTIC(NumCmps, "Number of comparisons propagated");
33 class CorrelatedValuePropagation : public FunctionPass {
36 bool processSelect(SelectInst *SI);
37 bool processPHI(PHINode *P);
38 bool processMemAccess(Instruction *I);
39 bool processCmp(CmpInst *C);
40 bool processSwitch(SwitchInst *SI);
44 CorrelatedValuePropagation(): FunctionPass(ID) {
45 initializeCorrelatedValuePropagationPass(*PassRegistry::getPassRegistry());
48 bool runOnFunction(Function &F);
50 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
51 AU.addRequired<LazyValueInfo>();
56 char CorrelatedValuePropagation::ID = 0;
57 INITIALIZE_PASS_BEGIN(CorrelatedValuePropagation, "correlated-propagation",
58 "Value Propagation", false, false)
59 INITIALIZE_PASS_DEPENDENCY(LazyValueInfo)
60 INITIALIZE_PASS_END(CorrelatedValuePropagation, "correlated-propagation",
61 "Value Propagation", false, false)
63 // Public interface to the Value Propagation pass
64 Pass *llvm::createCorrelatedValuePropagationPass() {
65 return new CorrelatedValuePropagation();
68 bool CorrelatedValuePropagation::processSelect(SelectInst *S) {
69 if (S->getType()->isVectorTy()) return false;
70 if (isa<Constant>(S->getOperand(0))) return false;
72 Constant *C = LVI->getConstant(S->getOperand(0), S->getParent());
75 ConstantInt *CI = dyn_cast<ConstantInt>(C);
76 if (!CI) return false;
78 Value *ReplaceWith = S->getOperand(1);
79 Value *Other = S->getOperand(2);
80 if (!CI->isOne()) std::swap(ReplaceWith, Other);
81 if (ReplaceWith == S) ReplaceWith = UndefValue::get(S->getType());
83 S->replaceAllUsesWith(ReplaceWith);
91 bool CorrelatedValuePropagation::processPHI(PHINode *P) {
94 BasicBlock *BB = P->getParent();
95 for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) {
96 Value *Incoming = P->getIncomingValue(i);
97 if (isa<Constant>(Incoming)) continue;
99 Constant *C = LVI->getConstantOnEdge(P->getIncomingValue(i),
100 P->getIncomingBlock(i),
104 P->setIncomingValue(i, C);
108 if (Value *V = SimplifyInstruction(P)) {
109 P->replaceAllUsesWith(V);
110 P->eraseFromParent();
119 bool CorrelatedValuePropagation::processMemAccess(Instruction *I) {
121 if (LoadInst *L = dyn_cast<LoadInst>(I))
122 Pointer = L->getPointerOperand();
124 Pointer = cast<StoreInst>(I)->getPointerOperand();
126 if (isa<Constant>(Pointer)) return false;
128 Constant *C = LVI->getConstant(Pointer, I->getParent());
129 if (!C) return false;
132 I->replaceUsesOfWith(Pointer, C);
136 /// processCmp - If the value of this comparison could be determined locally,
137 /// constant propagation would already have figured it out. Instead, walk
138 /// the predecessors and statically evaluate the comparison based on information
139 /// available on that edge. If a given static evaluation is true on ALL
140 /// incoming edges, then it's true universally and we can simplify the compare.
141 bool CorrelatedValuePropagation::processCmp(CmpInst *C) {
142 Value *Op0 = C->getOperand(0);
143 if (isa<Instruction>(Op0) &&
144 cast<Instruction>(Op0)->getParent() == C->getParent())
147 Constant *Op1 = dyn_cast<Constant>(C->getOperand(1));
148 if (!Op1) return false;
150 pred_iterator PI = pred_begin(C->getParent()), PE = pred_end(C->getParent());
151 if (PI == PE) return false;
153 LazyValueInfo::Tristate Result = LVI->getPredicateOnEdge(C->getPredicate(),
154 C->getOperand(0), Op1, *PI, C->getParent());
155 if (Result == LazyValueInfo::Unknown) return false;
159 LazyValueInfo::Tristate Res = LVI->getPredicateOnEdge(C->getPredicate(),
160 C->getOperand(0), Op1, *PI, C->getParent());
161 if (Res != Result) return false;
167 if (Result == LazyValueInfo::True)
168 C->replaceAllUsesWith(ConstantInt::getTrue(C->getContext()));
170 C->replaceAllUsesWith(ConstantInt::getFalse(C->getContext()));
172 C->eraseFromParent();
177 /// processSwitch - Simplify a switch instruction by removing cases which can
178 /// never fire. If the uselessness of a case could be determined locally then
179 /// constant propagation would already have figured it out. Instead, walk the
180 /// predecessors and statically evaluate cases based on information available
181 /// on that edge. Cases that cannot fire no matter what the incoming edge can
182 /// safely be removed. If a case fires on every incoming edge then the entire
183 /// switch can be removed and replaced with a branch to the case destination.
184 bool CorrelatedValuePropagation::processSwitch(SwitchInst *SI) {
185 Value *Cond = SI->getCondition();
186 BasicBlock *BB = SI->getParent();
188 // If the condition was defined in same block as the switch then LazyValueInfo
189 // currently won't say anything useful about it, though in theory it could.
190 if (isa<Instruction>(Cond) && cast<Instruction>(Cond)->getParent() == BB)
193 // If the switch is unreachable then trying to improve it is a waste of time.
194 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
195 if (PB == PE) return false;
197 // Analyse each switch case in turn. This is done in reverse order so that
198 // removing a case doesn't cause trouble for the iteration.
199 bool Changed = false;
200 for (SwitchInst::CaseIt CI = SI->caseEnd(), CE = SI->caseBegin(); CI-- != CE;
202 ConstantInt *Case = CI.getCaseValue();
204 // Check to see if the switch condition is equal to/not equal to the case
205 // value on every incoming edge, equal/not equal being the same each time.
206 LazyValueInfo::Tristate State = LazyValueInfo::Unknown;
207 for (pred_iterator PI = PB; PI != PE; ++PI) {
208 // Is the switch condition equal to the case value?
209 LazyValueInfo::Tristate Value = LVI->getPredicateOnEdge(CmpInst::ICMP_EQ,
210 Cond, Case, *PI, BB);
211 // Give up on this case if nothing is known.
212 if (Value == LazyValueInfo::Unknown) {
213 State = LazyValueInfo::Unknown;
217 // If this was the first edge to be visited, record that all other edges
218 // need to give the same result.
224 // If this case is known to fire for some edges and known not to fire for
225 // others then there is nothing we can do - give up.
226 if (Value != State) {
227 State = LazyValueInfo::Unknown;
232 if (State == LazyValueInfo::False) {
233 // This case never fires - remove it.
234 CI.getCaseSuccessor()->removePredecessor(BB);
235 SI->removeCase(CI); // Does not invalidate the iterator.
237 } else if (State == LazyValueInfo::True) {
238 // This case always fires. Arrange for the switch to be turned into an
239 // unconditional branch by replacing the switch condition with the case
241 SI->setCondition(Case);
248 // If the switch has been simplified to the point where it can be replaced
249 // by a branch then do so now.
250 ConstantFoldTerminator(BB);
255 bool CorrelatedValuePropagation::runOnFunction(Function &F) {
256 LVI = &getAnalysis<LazyValueInfo>();
258 bool FnChanged = false;
260 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
261 bool BBChanged = false;
262 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
263 Instruction *II = BI++;
264 switch (II->getOpcode()) {
265 case Instruction::Select:
266 BBChanged |= processSelect(cast<SelectInst>(II));
268 case Instruction::PHI:
269 BBChanged |= processPHI(cast<PHINode>(II));
271 case Instruction::ICmp:
272 case Instruction::FCmp:
273 BBChanged |= processCmp(cast<CmpInst>(II));
275 case Instruction::Load:
276 case Instruction::Store:
277 BBChanged |= processMemAccess(II);
282 Instruction *Term = FI->getTerminator();
283 switch (Term->getOpcode()) {
284 case Instruction::Switch:
285 BBChanged |= processSwitch(cast<SwitchInst>(Term));
289 FnChanged |= BBChanged;