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(NumReturns, "Number of return values propagated");
37 STATISTIC(NumDeadCases, "Number of switch cases removed");
40 class CorrelatedValuePropagation : public FunctionPass {
43 bool processSelect(SelectInst *SI);
44 bool processPHI(PHINode *P);
45 bool processMemAccess(Instruction *I);
46 bool processCmp(CmpInst *C);
47 bool processSwitch(SwitchInst *SI);
48 bool processCallSite(CallSite CS);
50 /// Return a constant value for V usable at At and everything it
51 /// dominates. If no such Constant can be found, return nullptr.
52 Constant *getConstantAt(Value *V, Instruction *At);
56 CorrelatedValuePropagation(): FunctionPass(ID) {
57 initializeCorrelatedValuePropagationPass(*PassRegistry::getPassRegistry());
60 bool runOnFunction(Function &F) override;
62 void getAnalysisUsage(AnalysisUsage &AU) const override {
63 AU.addRequired<LazyValueInfo>();
64 AU.addPreserved<GlobalsAAWrapperPass>();
69 char CorrelatedValuePropagation::ID = 0;
70 INITIALIZE_PASS_BEGIN(CorrelatedValuePropagation, "correlated-propagation",
71 "Value Propagation", false, false)
72 INITIALIZE_PASS_DEPENDENCY(LazyValueInfo)
73 INITIALIZE_PASS_END(CorrelatedValuePropagation, "correlated-propagation",
74 "Value Propagation", false, false)
76 // Public interface to the Value Propagation pass
77 Pass *llvm::createCorrelatedValuePropagationPass() {
78 return new CorrelatedValuePropagation();
81 bool CorrelatedValuePropagation::processSelect(SelectInst *S) {
82 if (S->getType()->isVectorTy()) return false;
83 if (isa<Constant>(S->getOperand(0))) return false;
85 Constant *C = LVI->getConstant(S->getOperand(0), S->getParent(), S);
88 ConstantInt *CI = dyn_cast<ConstantInt>(C);
89 if (!CI) return false;
91 Value *ReplaceWith = S->getOperand(1);
92 Value *Other = S->getOperand(2);
93 if (!CI->isOne()) std::swap(ReplaceWith, Other);
94 if (ReplaceWith == S) ReplaceWith = UndefValue::get(S->getType());
96 S->replaceAllUsesWith(ReplaceWith);
104 bool CorrelatedValuePropagation::processPHI(PHINode *P) {
105 bool Changed = false;
107 BasicBlock *BB = P->getParent();
108 for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) {
109 Value *Incoming = P->getIncomingValue(i);
110 if (isa<Constant>(Incoming)) continue;
112 Value *V = LVI->getConstantOnEdge(Incoming, P->getIncomingBlock(i), BB, P);
114 // Look if the incoming value is a select with a scalar condition for which
115 // LVI can tells us the value. In that case replace the incoming value with
116 // the appropriate value of the select. This often allows us to remove the
119 SelectInst *SI = dyn_cast<SelectInst>(Incoming);
122 Value *Condition = SI->getCondition();
123 if (!Condition->getType()->isVectorTy()) {
124 if (Constant *C = LVI->getConstantOnEdge(
125 Condition, P->getIncomingBlock(i), BB, P)) {
126 if (C->isOneValue()) {
127 V = SI->getTrueValue();
128 } else if (C->isZeroValue()) {
129 V = SI->getFalseValue();
131 // Once LVI learns to handle vector types, we could also add support
132 // for vector type constants that are not all zeroes or all ones.
136 // Look if the select has a constant but LVI tells us that the incoming
137 // value can never be that constant. In that case replace the incoming
138 // value with the other value of the select. This often allows us to
139 // remove the select later.
141 Constant *C = dyn_cast<Constant>(SI->getFalseValue());
144 if (LVI->getPredicateOnEdge(ICmpInst::ICMP_EQ, SI, C,
145 P->getIncomingBlock(i), BB, P) !=
146 LazyValueInfo::False)
148 V = SI->getTrueValue();
151 DEBUG(dbgs() << "CVP: Threading PHI over " << *SI << '\n');
154 P->setIncomingValue(i, V);
158 // FIXME: Provide TLI, DT, AT to SimplifyInstruction.
159 const DataLayout &DL = BB->getModule()->getDataLayout();
160 if (Value *V = SimplifyInstruction(P, DL)) {
161 P->replaceAllUsesWith(V);
162 P->eraseFromParent();
172 bool CorrelatedValuePropagation::processMemAccess(Instruction *I) {
173 Value *Pointer = nullptr;
174 if (LoadInst *L = dyn_cast<LoadInst>(I))
175 Pointer = L->getPointerOperand();
177 Pointer = cast<StoreInst>(I)->getPointerOperand();
179 if (isa<Constant>(Pointer)) return false;
181 Constant *C = LVI->getConstant(Pointer, I->getParent(), I);
182 if (!C) return false;
185 I->replaceUsesOfWith(Pointer, C);
189 /// processCmp - See if LazyValueInfo's ability to exploit edge conditions,
190 /// or range information is sufficient to prove this comparison. Even for
191 /// local conditions, this can sometimes prove conditions instcombine can't by
192 /// exploiting range information.
193 bool CorrelatedValuePropagation::processCmp(CmpInst *C) {
194 Value *Op0 = C->getOperand(0);
195 Constant *Op1 = dyn_cast<Constant>(C->getOperand(1));
196 if (!Op1) return false;
198 // As a policy choice, we choose not to waste compile time on anything where
199 // the comparison is testing local values. While LVI can sometimes reason
200 // about such cases, it's not its primary purpose. We do make sure to do
201 // the block local query for uses from terminator instructions, but that's
202 // handled in the code for each terminator.
203 auto *I = dyn_cast<Instruction>(Op0);
204 if (I && I->getParent() == C->getParent())
207 LazyValueInfo::Tristate Result =
208 LVI->getPredicateAt(C->getPredicate(), Op0, Op1, C);
209 if (Result == LazyValueInfo::Unknown) return false;
212 if (Result == LazyValueInfo::True)
213 C->replaceAllUsesWith(ConstantInt::getTrue(C->getContext()));
215 C->replaceAllUsesWith(ConstantInt::getFalse(C->getContext()));
216 C->eraseFromParent();
221 /// processSwitch - Simplify a switch instruction by removing cases which can
222 /// never fire. If the uselessness of a case could be determined locally then
223 /// constant propagation would already have figured it out. Instead, walk the
224 /// predecessors and statically evaluate cases based on information available
225 /// on that edge. Cases that cannot fire no matter what the incoming edge can
226 /// safely be removed. If a case fires on every incoming edge then the entire
227 /// switch can be removed and replaced with a branch to the case destination.
228 bool CorrelatedValuePropagation::processSwitch(SwitchInst *SI) {
229 Value *Cond = SI->getCondition();
230 BasicBlock *BB = SI->getParent();
232 // If the condition was defined in same block as the switch then LazyValueInfo
233 // currently won't say anything useful about it, though in theory it could.
234 if (isa<Instruction>(Cond) && cast<Instruction>(Cond)->getParent() == BB)
237 // If the switch is unreachable then trying to improve it is a waste of time.
238 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
239 if (PB == PE) return false;
241 // Analyse each switch case in turn. This is done in reverse order so that
242 // removing a case doesn't cause trouble for the iteration.
243 bool Changed = false;
244 for (SwitchInst::CaseIt CI = SI->case_end(), CE = SI->case_begin(); CI-- != CE;
246 ConstantInt *Case = CI.getCaseValue();
248 // Check to see if the switch condition is equal to/not equal to the case
249 // value on every incoming edge, equal/not equal being the same each time.
250 LazyValueInfo::Tristate State = LazyValueInfo::Unknown;
251 for (pred_iterator PI = PB; PI != PE; ++PI) {
252 // Is the switch condition equal to the case value?
253 LazyValueInfo::Tristate Value = LVI->getPredicateOnEdge(CmpInst::ICMP_EQ,
256 // Give up on this case if nothing is known.
257 if (Value == LazyValueInfo::Unknown) {
258 State = LazyValueInfo::Unknown;
262 // If this was the first edge to be visited, record that all other edges
263 // need to give the same result.
269 // If this case is known to fire for some edges and known not to fire for
270 // others then there is nothing we can do - give up.
271 if (Value != State) {
272 State = LazyValueInfo::Unknown;
277 if (State == LazyValueInfo::False) {
278 // This case never fires - remove it.
279 CI.getCaseSuccessor()->removePredecessor(BB);
280 SI->removeCase(CI); // Does not invalidate the iterator.
282 // The condition can be modified by removePredecessor's PHI simplification
284 Cond = SI->getCondition();
288 } else if (State == LazyValueInfo::True) {
289 // This case always fires. Arrange for the switch to be turned into an
290 // unconditional branch by replacing the switch condition with the case
292 SI->setCondition(Case);
293 NumDeadCases += SI->getNumCases();
300 // If the switch has been simplified to the point where it can be replaced
301 // by a branch then do so now.
302 ConstantFoldTerminator(BB);
307 /// processCallSite - Infer nonnull attributes for the arguments at the
308 /// specified callsite.
309 bool CorrelatedValuePropagation::processCallSite(CallSite CS) {
310 bool Changed = false;
313 for (Value *V : CS.args()) {
314 PointerType *Type = dyn_cast<PointerType>(V->getType());
316 if (Type && !CS.paramHasAttr(ArgNo + 1, Attribute::NonNull) &&
317 LVI->getPredicateAt(ICmpInst::ICMP_EQ, V,
318 ConstantPointerNull::get(Type),
319 CS.getInstruction()) == LazyValueInfo::False) {
320 AttributeSet AS = CS.getAttributes();
321 AS = AS.addAttribute(CS.getInstruction()->getContext(), ArgNo + 1,
323 CS.setAttributes(AS);
328 assert(ArgNo == CS.arg_size() && "sanity check");
333 Constant *CorrelatedValuePropagation::getConstantAt(Value *V, Instruction *At) {
334 if (Constant *C = LVI->getConstant(V, At->getParent(), At))
337 // TODO: The following really should be sunk inside LVI's core algorithm, or
338 // at least the outer shims around such.
339 auto *C = dyn_cast<CmpInst>(V);
340 if (!C) return nullptr;
342 Value *Op0 = C->getOperand(0);
343 Constant *Op1 = dyn_cast<Constant>(C->getOperand(1));
344 if (!Op1) return nullptr;
346 LazyValueInfo::Tristate Result =
347 LVI->getPredicateAt(C->getPredicate(), Op0, Op1, At);
348 if (Result == LazyValueInfo::Unknown)
351 return (Result == LazyValueInfo::True) ?
352 ConstantInt::getTrue(C->getContext()) :
353 ConstantInt::getFalse(C->getContext());
356 bool CorrelatedValuePropagation::runOnFunction(Function &F) {
357 if (skipOptnoneFunction(F))
360 LVI = &getAnalysis<LazyValueInfo>();
362 bool FnChanged = false;
364 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
365 bool BBChanged = false;
366 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
367 Instruction *II = &*BI++;
368 switch (II->getOpcode()) {
369 case Instruction::Select:
370 BBChanged |= processSelect(cast<SelectInst>(II));
372 case Instruction::PHI:
373 BBChanged |= processPHI(cast<PHINode>(II));
375 case Instruction::ICmp:
376 case Instruction::FCmp:
377 BBChanged |= processCmp(cast<CmpInst>(II));
379 case Instruction::Load:
380 case Instruction::Store:
381 BBChanged |= processMemAccess(II);
383 case Instruction::Call:
384 case Instruction::Invoke:
385 BBChanged |= processCallSite(CallSite(II));
390 Instruction *Term = FI->getTerminator();
391 switch (Term->getOpcode()) {
392 case Instruction::Switch:
393 BBChanged |= processSwitch(cast<SwitchInst>(Term));
395 case Instruction::Ret: {
396 auto *RI = cast<ReturnInst>(Term);
397 // Try to determine the return value if we can. This is mainly here to
398 // simplify the writing of unit tests, but also helps to enable IPO by
399 // constant folding the return values of callees.
400 auto *RetVal = RI->getReturnValue();
401 if (!RetVal) break; // handle "ret void"
402 if (isa<Constant>(RetVal)) break; // nothing to do
403 if (auto *C = getConstantAt(RetVal, RI)) {
405 RI->replaceUsesOfWith(RetVal, C);
411 FnChanged |= BBChanged;