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"
28using namespace llvm;
29
30#define DEBUG_TYPE "correlated-value-propagation"
31
32STATISTIC(NumPhis,      "Number of phis propagated");
33STATISTIC(NumSelects,   "Number of selects propagated");
34STATISTIC(NumMemAccess, "Number of memory access targets propagated");
35STATISTIC(NumCmps,      "Number of comparisons propagated");
36STATISTIC(NumReturns,   "Number of return values propagated");
37STATISTIC(NumDeadCases, "Number of switch cases removed");
38
39namespace {
40  class CorrelatedValuePropagation : public FunctionPass {
41    LazyValueInfo *LVI;
42
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);
49
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);
53
54  public:
55    static char ID;
56    CorrelatedValuePropagation(): FunctionPass(ID) {
57     initializeCorrelatedValuePropagationPass(*PassRegistry::getPassRegistry());
58    }
59
60    bool runOnFunction(Function &F) override;
61
62    void getAnalysisUsage(AnalysisUsage &AU) const override {
63      AU.addRequired<LazyValueInfo>();
64      AU.addPreserved<GlobalsAAWrapperPass>();
65    }
66  };
67}
68
69char CorrelatedValuePropagation::ID = 0;
70INITIALIZE_PASS_BEGIN(CorrelatedValuePropagation, "correlated-propagation",
71                "Value Propagation", false, false)
72INITIALIZE_PASS_DEPENDENCY(LazyValueInfo)
73INITIALIZE_PASS_END(CorrelatedValuePropagation, "correlated-propagation",
74                "Value Propagation", false, false)
75
76// Public interface to the Value Propagation pass
77Pass *llvm::createCorrelatedValuePropagationPass() {
78  return new CorrelatedValuePropagation();
79}
80
81bool CorrelatedValuePropagation::processSelect(SelectInst *S) {
82  if (S->getType()->isVectorTy()) return false;
83  if (isa<Constant>(S->getOperand(0))) return false;
84
85  Constant *C = LVI->getConstant(S->getOperand(0), S->getParent(), S);
86  if (!C) return false;
87
88  ConstantInt *CI = dyn_cast<ConstantInt>(C);
89  if (!CI) return false;
90
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());
95
96  S->replaceAllUsesWith(ReplaceWith);
97  S->eraseFromParent();
98
99  ++NumSelects;
100
101  return true;
102}
103
104bool CorrelatedValuePropagation::processPHI(PHINode *P) {
105  bool Changed = false;
106
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;
111
112    Value *V = LVI->getConstantOnEdge(Incoming, P->getIncomingBlock(i), BB, P);
113
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
117    // select later.
118    if (!V) {
119      SelectInst *SI = dyn_cast<SelectInst>(Incoming);
120      if (!SI) continue;
121
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();
130          }
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.
133        }
134      }
135
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.
140      if (!V) {
141        Constant *C = dyn_cast<Constant>(SI->getFalseValue());
142        if (!C) continue;
143
144        if (LVI->getPredicateOnEdge(ICmpInst::ICMP_EQ, SI, C,
145              P->getIncomingBlock(i), BB, P) !=
146            LazyValueInfo::False)
147          continue;
148        V = SI->getTrueValue();
149      }
150
151      DEBUG(dbgs() << "CVP: Threading PHI over " << *SI << '\n');
152    }
153
154    P->setIncomingValue(i, V);
155    Changed = true;
156  }
157
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();
163    Changed = true;
164  }
165
166  if (Changed)
167    ++NumPhis;
168
169  return Changed;
170}
171
172bool CorrelatedValuePropagation::processMemAccess(Instruction *I) {
173  Value *Pointer = nullptr;
174  if (LoadInst *L = dyn_cast<LoadInst>(I))
175    Pointer = L->getPointerOperand();
176  else
177    Pointer = cast<StoreInst>(I)->getPointerOperand();
178
179  if (isa<Constant>(Pointer)) return false;
180
181  Constant *C = LVI->getConstant(Pointer, I->getParent(), I);
182  if (!C) return false;
183
184  ++NumMemAccess;
185  I->replaceUsesOfWith(Pointer, C);
186  return true;
187}
188
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.
193bool CorrelatedValuePropagation::processCmp(CmpInst *C) {
194  Value *Op0 = C->getOperand(0);
195  Constant *Op1 = dyn_cast<Constant>(C->getOperand(1));
196  if (!Op1) return false;
197
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())
205    return false;
206
207  LazyValueInfo::Tristate Result =
208    LVI->getPredicateAt(C->getPredicate(), Op0, Op1, C);
209  if (Result == LazyValueInfo::Unknown) return false;
210
211  ++NumCmps;
212  if (Result == LazyValueInfo::True)
213    C->replaceAllUsesWith(ConstantInt::getTrue(C->getContext()));
214  else
215    C->replaceAllUsesWith(ConstantInt::getFalse(C->getContext()));
216  C->eraseFromParent();
217
218  return true;
219}
220
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.
228bool CorrelatedValuePropagation::processSwitch(SwitchInst *SI) {
229  Value *Cond = SI->getCondition();
230  BasicBlock *BB = SI->getParent();
231
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)
235    return false;
236
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;
240
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;
245       ) {
246    ConstantInt *Case = CI.getCaseValue();
247
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,
254                                                              Cond, Case, *PI,
255                                                              BB, SI);
256      // Give up on this case if nothing is known.
257      if (Value == LazyValueInfo::Unknown) {
258        State = LazyValueInfo::Unknown;
259        break;
260      }
261
262      // If this was the first edge to be visited, record that all other edges
263      // need to give the same result.
264      if (PI == PB) {
265        State = Value;
266        continue;
267      }
268
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;
273        break;
274      }
275    }
276
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.
281
282      // The condition can be modified by removePredecessor's PHI simplification
283      // logic.
284      Cond = SI->getCondition();
285
286      ++NumDeadCases;
287      Changed = true;
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
291      // value.
292      SI->setCondition(Case);
293      NumDeadCases += SI->getNumCases();
294      Changed = true;
295      break;
296    }
297  }
298
299  if (Changed)
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);
303
304  return Changed;
305}
306
307/// processCallSite - Infer nonnull attributes for the arguments at the
308/// specified callsite.
309bool CorrelatedValuePropagation::processCallSite(CallSite CS) {
310  SmallVector<unsigned, 4> Indices;
311  unsigned ArgNo = 0;
312
313  for (Value *V : CS.args()) {
314    PointerType *Type = dyn_cast<PointerType>(V->getType());
315
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      Indices.push_back(ArgNo + 1);
321    ArgNo++;
322  }
323
324  assert(ArgNo == CS.arg_size() && "sanity check");
325
326  if (Indices.empty())
327    return false;
328
329  AttributeSet AS = CS.getAttributes();
330  LLVMContext &Ctx = CS.getInstruction()->getContext();
331  AS = AS.addAttribute(Ctx, Indices, Attribute::get(Ctx, Attribute::NonNull));
332  CS.setAttributes(AS);
333
334  return true;
335}
336
337Constant *CorrelatedValuePropagation::getConstantAt(Value *V, Instruction *At) {
338  if (Constant *C = LVI->getConstant(V, At->getParent(), At))
339    return C;
340
341  // TODO: The following really should be sunk inside LVI's core algorithm, or
342  // at least the outer shims around such.
343  auto *C = dyn_cast<CmpInst>(V);
344  if (!C) return nullptr;
345
346  Value *Op0 = C->getOperand(0);
347  Constant *Op1 = dyn_cast<Constant>(C->getOperand(1));
348  if (!Op1) return nullptr;
349
350  LazyValueInfo::Tristate Result =
351    LVI->getPredicateAt(C->getPredicate(), Op0, Op1, At);
352  if (Result == LazyValueInfo::Unknown)
353    return nullptr;
354
355  return (Result == LazyValueInfo::True) ?
356    ConstantInt::getTrue(C->getContext()) :
357    ConstantInt::getFalse(C->getContext());
358}
359
360bool CorrelatedValuePropagation::runOnFunction(Function &F) {
361  if (skipOptnoneFunction(F))
362    return false;
363
364  LVI = &getAnalysis<LazyValueInfo>();
365
366  bool FnChanged = false;
367
368  for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
369    bool BBChanged = false;
370    for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
371      Instruction *II = &*BI++;
372      switch (II->getOpcode()) {
373      case Instruction::Select:
374        BBChanged |= processSelect(cast<SelectInst>(II));
375        break;
376      case Instruction::PHI:
377        BBChanged |= processPHI(cast<PHINode>(II));
378        break;
379      case Instruction::ICmp:
380      case Instruction::FCmp:
381        BBChanged |= processCmp(cast<CmpInst>(II));
382        break;
383      case Instruction::Load:
384      case Instruction::Store:
385        BBChanged |= processMemAccess(II);
386        break;
387      case Instruction::Call:
388      case Instruction::Invoke:
389        BBChanged |= processCallSite(CallSite(II));
390        break;
391      }
392    }
393
394    Instruction *Term = FI->getTerminator();
395    switch (Term->getOpcode()) {
396    case Instruction::Switch:
397      BBChanged |= processSwitch(cast<SwitchInst>(Term));
398      break;
399    case Instruction::Ret: {
400      auto *RI = cast<ReturnInst>(Term);
401      // Try to determine the return value if we can.  This is mainly here to
402      // simplify the writing of unit tests, but also helps to enable IPO by
403      // constant folding the return values of callees.
404      auto *RetVal = RI->getReturnValue();
405      if (!RetVal) break; // handle "ret void"
406      if (isa<Constant>(RetVal)) break; // nothing to do
407      if (auto *C = getConstantAt(RetVal, RI)) {
408        ++NumReturns;
409        RI->replaceUsesOfWith(RetVal, C);
410        BBChanged = true;
411      }
412    }
413    };
414
415    FnChanged |= BBChanged;
416  }
417
418  return FnChanged;
419}
420