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 #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"
30 #define DEBUG_TYPE "correlated-value-propagation"
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");
39 class CorrelatedValuePropagation : public FunctionPass {
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 bool processCallSite(CallSite CS);
51 CorrelatedValuePropagation(): FunctionPass(ID) {
52 initializeCorrelatedValuePropagationPass(*PassRegistry::getPassRegistry());
55 bool runOnFunction(Function &F) override;
57 void getAnalysisUsage(AnalysisUsage &AU) const override {
58 AU.addRequired<LazyValueInfo>();
59 AU.addPreserved<GlobalsAAWrapperPass>();
64 char CorrelatedValuePropagation::ID = 0;
65 INITIALIZE_PASS_BEGIN(CorrelatedValuePropagation, "correlated-propagation",
66 "Value Propagation", false, false)
67 INITIALIZE_PASS_DEPENDENCY(LazyValueInfo)
68 INITIALIZE_PASS_END(CorrelatedValuePropagation, "correlated-propagation",
69 "Value Propagation", false, false)
71 // Public interface to the Value Propagation pass
72 Pass *llvm::createCorrelatedValuePropagationPass() {
73 return new CorrelatedValuePropagation();
76 bool CorrelatedValuePropagation::processSelect(SelectInst *S) {
77 if (S->getType()->isVectorTy()) return false;
78 if (isa<Constant>(S->getOperand(0))) return false;
80 Constant *C = LVI->getConstant(S->getOperand(0), S->getParent(), S);
83 ConstantInt *CI = dyn_cast<ConstantInt>(C);
84 if (!CI) return false;
86 Value *ReplaceWith = S->getOperand(1);
87 Value *Other = S->getOperand(2);
88 if (!CI->isOne()) std::swap(ReplaceWith, Other);
89 if (ReplaceWith == S) ReplaceWith = UndefValue::get(S->getType());
91 S->replaceAllUsesWith(ReplaceWith);
99 bool CorrelatedValuePropagation::processPHI(PHINode *P) {
100 bool Changed = false;
102 BasicBlock *BB = P->getParent();
103 for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) {
104 Value *Incoming = P->getIncomingValue(i);
105 if (isa<Constant>(Incoming)) continue;
107 Value *V = LVI->getConstantOnEdge(Incoming, P->getIncomingBlock(i), BB, P);
109 // Look if the incoming value is a select with a scalar condition for which
110 // LVI can tells us the value. In that case replace the incoming value with
111 // the appropriate value of the select. This often allows us to remove the
114 SelectInst *SI = dyn_cast<SelectInst>(Incoming);
117 Value *Condition = SI->getCondition();
118 if (!Condition->getType()->isVectorTy()) {
119 if (Constant *C = LVI->getConstantOnEdge(
120 Condition, P->getIncomingBlock(i), BB, P)) {
121 if (C->isOneValue()) {
122 V = SI->getTrueValue();
123 } else if (C->isZeroValue()) {
124 V = SI->getFalseValue();
126 // Once LVI learns to handle vector types, we could also add support
127 // for vector type constants that are not all zeroes or all ones.
131 // Look if the select has a constant but LVI tells us that the incoming
132 // value can never be that constant. In that case replace the incoming
133 // value with the other value of the select. This often allows us to
134 // remove the select later.
136 Constant *C = dyn_cast<Constant>(SI->getFalseValue());
139 if (LVI->getPredicateOnEdge(ICmpInst::ICMP_EQ, SI, C,
140 P->getIncomingBlock(i), BB, P) !=
141 LazyValueInfo::False)
143 V = SI->getTrueValue();
146 DEBUG(dbgs() << "CVP: Threading PHI over " << *SI << '\n');
149 P->setIncomingValue(i, V);
153 // FIXME: Provide TLI, DT, AT to SimplifyInstruction.
154 const DataLayout &DL = BB->getModule()->getDataLayout();
155 if (Value *V = SimplifyInstruction(P, DL)) {
156 P->replaceAllUsesWith(V);
157 P->eraseFromParent();
167 bool CorrelatedValuePropagation::processMemAccess(Instruction *I) {
168 Value *Pointer = nullptr;
169 if (LoadInst *L = dyn_cast<LoadInst>(I))
170 Pointer = L->getPointerOperand();
172 Pointer = cast<StoreInst>(I)->getPointerOperand();
174 if (isa<Constant>(Pointer)) return false;
176 Constant *C = LVI->getConstant(Pointer, I->getParent(), I);
177 if (!C) return false;
180 I->replaceUsesOfWith(Pointer, C);
184 /// processCmp - See if LazyValueInfo's ability to exploit edge conditions,
185 /// or range information is sufficient to prove this comparison. Even for
186 /// local conditions, this can sometimes prove conditions instcombine can't by
187 /// exploiting range information.
188 bool CorrelatedValuePropagation::processCmp(CmpInst *C) {
189 Value *Op0 = C->getOperand(0);
190 Constant *Op1 = dyn_cast<Constant>(C->getOperand(1));
191 if (!Op1) return false;
193 LazyValueInfo::Tristate Result =
194 LVI->getPredicateAt(C->getPredicate(), Op0, Op1, C);
195 if (Result == LazyValueInfo::Unknown) return false;
198 if (Result == LazyValueInfo::True)
199 C->replaceAllUsesWith(ConstantInt::getTrue(C->getContext()));
201 C->replaceAllUsesWith(ConstantInt::getFalse(C->getContext()));
202 C->eraseFromParent();
207 /// processSwitch - Simplify a switch instruction by removing cases which can
208 /// never fire. If the uselessness of a case could be determined locally then
209 /// constant propagation would already have figured it out. Instead, walk the
210 /// predecessors and statically evaluate cases based on information available
211 /// on that edge. Cases that cannot fire no matter what the incoming edge can
212 /// safely be removed. If a case fires on every incoming edge then the entire
213 /// switch can be removed and replaced with a branch to the case destination.
214 bool CorrelatedValuePropagation::processSwitch(SwitchInst *SI) {
215 Value *Cond = SI->getCondition();
216 BasicBlock *BB = SI->getParent();
218 // If the condition was defined in same block as the switch then LazyValueInfo
219 // currently won't say anything useful about it, though in theory it could.
220 if (isa<Instruction>(Cond) && cast<Instruction>(Cond)->getParent() == BB)
223 // If the switch is unreachable then trying to improve it is a waste of time.
224 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
225 if (PB == PE) return false;
227 // Analyse each switch case in turn. This is done in reverse order so that
228 // removing a case doesn't cause trouble for the iteration.
229 bool Changed = false;
230 for (SwitchInst::CaseIt CI = SI->case_end(), CE = SI->case_begin(); CI-- != CE;
232 ConstantInt *Case = CI.getCaseValue();
234 // Check to see if the switch condition is equal to/not equal to the case
235 // value on every incoming edge, equal/not equal being the same each time.
236 LazyValueInfo::Tristate State = LazyValueInfo::Unknown;
237 for (pred_iterator PI = PB; PI != PE; ++PI) {
238 // Is the switch condition equal to the case value?
239 LazyValueInfo::Tristate Value = LVI->getPredicateOnEdge(CmpInst::ICMP_EQ,
242 // Give up on this case if nothing is known.
243 if (Value == LazyValueInfo::Unknown) {
244 State = LazyValueInfo::Unknown;
248 // If this was the first edge to be visited, record that all other edges
249 // need to give the same result.
255 // If this case is known to fire for some edges and known not to fire for
256 // others then there is nothing we can do - give up.
257 if (Value != State) {
258 State = LazyValueInfo::Unknown;
263 if (State == LazyValueInfo::False) {
264 // This case never fires - remove it.
265 CI.getCaseSuccessor()->removePredecessor(BB);
266 SI->removeCase(CI); // Does not invalidate the iterator.
268 // The condition can be modified by removePredecessor's PHI simplification
270 Cond = SI->getCondition();
274 } else if (State == LazyValueInfo::True) {
275 // This case always fires. Arrange for the switch to be turned into an
276 // unconditional branch by replacing the switch condition with the case
278 SI->setCondition(Case);
279 NumDeadCases += SI->getNumCases();
286 // If the switch has been simplified to the point where it can be replaced
287 // by a branch then do so now.
288 ConstantFoldTerminator(BB);
293 /// processCallSite - Infer nonnull attributes for the arguments at the
294 /// specified callsite.
295 bool CorrelatedValuePropagation::processCallSite(CallSite CS) {
296 bool Changed = false;
299 for (Value *V : CS.args()) {
300 PointerType *Type = dyn_cast<PointerType>(V->getType());
302 if (Type && !CS.paramHasAttr(ArgNo + 1, Attribute::NonNull) &&
303 LVI->getPredicateAt(ICmpInst::ICMP_EQ, V,
304 ConstantPointerNull::get(Type),
305 CS.getInstruction()) == LazyValueInfo::False) {
306 AttributeSet AS = CS.getAttributes();
307 AS = AS.addAttribute(CS.getInstruction()->getContext(), ArgNo + 1,
309 CS.setAttributes(AS);
314 assert(ArgNo == CS.arg_size() && "sanity check");
319 bool CorrelatedValuePropagation::runOnFunction(Function &F) {
320 if (skipOptnoneFunction(F))
323 LVI = &getAnalysis<LazyValueInfo>();
325 bool FnChanged = false;
327 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
328 bool BBChanged = false;
329 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
330 Instruction *II = &*BI++;
331 switch (II->getOpcode()) {
332 case Instruction::Select:
333 BBChanged |= processSelect(cast<SelectInst>(II));
335 case Instruction::PHI:
336 BBChanged |= processPHI(cast<PHINode>(II));
338 case Instruction::ICmp:
339 case Instruction::FCmp:
340 BBChanged |= processCmp(cast<CmpInst>(II));
342 case Instruction::Load:
343 case Instruction::Store:
344 BBChanged |= processMemAccess(II);
346 case Instruction::Call:
347 case Instruction::Invoke:
348 BBChanged |= processCallSite(CallSite(II));
353 Instruction *Term = FI->getTerminator();
354 switch (Term->getOpcode()) {
355 case Instruction::Switch:
356 BBChanged |= processSwitch(cast<SwitchInst>(Term));
360 FnChanged |= BBChanged;