• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements sparse conditional constant propagation and merging:
10 //
11 // Specifically, this:
12 //   * Assumes values are constant unless proven otherwise
13 //   * Assumes BasicBlocks are dead unless proven otherwise
14 //   * Proves values to be constant, and replaces them with constants
15 //   * Proves conditional branches to be unconditional
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/Transforms/Scalar/SCCP.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/DenseSet.h"
23 #include "llvm/ADT/MapVector.h"
24 #include "llvm/ADT/PointerIntPair.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/Analysis/ConstantFolding.h"
30 #include "llvm/Analysis/GlobalsModRef.h"
31 #include "llvm/Analysis/TargetLibraryInfo.h"
32 #include "llvm/Analysis/ValueLattice.h"
33 #include "llvm/Analysis/ValueLatticeUtils.h"
34 #include "llvm/IR/BasicBlock.h"
35 #include "llvm/IR/CallSite.h"
36 #include "llvm/IR/Constant.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/DataLayout.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalVariable.h"
42 #include "llvm/IR/InstVisitor.h"
43 #include "llvm/IR/InstrTypes.h"
44 #include "llvm/IR/Instruction.h"
45 #include "llvm/IR/Instructions.h"
46 #include "llvm/IR/Module.h"
47 #include "llvm/IR/PassManager.h"
48 #include "llvm/IR/Type.h"
49 #include "llvm/IR/User.h"
50 #include "llvm/IR/Value.h"
51 #include "llvm/InitializePasses.h"
52 #include "llvm/Pass.h"
53 #include "llvm/Support/Casting.h"
54 #include "llvm/Support/Debug.h"
55 #include "llvm/Support/ErrorHandling.h"
56 #include "llvm/Support/raw_ostream.h"
57 #include "llvm/Transforms/Scalar.h"
58 #include "llvm/Transforms/Utils/Local.h"
59 #include "llvm/Transforms/Utils/PredicateInfo.h"
60 #include <cassert>
61 #include <utility>
62 #include <vector>
63 
64 using namespace llvm;
65 
66 #define DEBUG_TYPE "sccp"
67 
68 STATISTIC(NumInstRemoved, "Number of instructions removed");
69 STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
70 
71 STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
72 STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
73 STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
74 
75 namespace {
76 
77 /// LatticeVal class - This class represents the different lattice values that
78 /// an LLVM value may occupy.  It is a simple class with value semantics.
79 ///
80 class LatticeVal {
81   enum LatticeValueTy {
82     /// unknown - This LLVM Value has no known value yet.
83     unknown,
84 
85     /// constant - This LLVM Value has a specific constant value.
86     constant,
87 
88     /// forcedconstant - This LLVM Value was thought to be undef until
89     /// ResolvedUndefsIn.  This is treated just like 'constant', but if merged
90     /// with another (different) constant, it goes to overdefined, instead of
91     /// asserting.
92     forcedconstant,
93 
94     /// overdefined - This instruction is not known to be constant, and we know
95     /// it has a value.
96     overdefined
97   };
98 
99   /// Val: This stores the current lattice value along with the Constant* for
100   /// the constant if this is a 'constant' or 'forcedconstant' value.
101   PointerIntPair<Constant *, 2, LatticeValueTy> Val;
102 
getLatticeValue() const103   LatticeValueTy getLatticeValue() const {
104     return Val.getInt();
105   }
106 
107 public:
LatticeVal()108   LatticeVal() : Val(nullptr, unknown) {}
109 
isUnknown() const110   bool isUnknown() const { return getLatticeValue() == unknown; }
111 
isConstant() const112   bool isConstant() const {
113     return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
114   }
115 
isOverdefined() const116   bool isOverdefined() const { return getLatticeValue() == overdefined; }
117 
getConstant() const118   Constant *getConstant() const {
119     assert(isConstant() && "Cannot get the constant of a non-constant!");
120     return Val.getPointer();
121   }
122 
123   /// markOverdefined - Return true if this is a change in status.
markOverdefined()124   bool markOverdefined() {
125     if (isOverdefined())
126       return false;
127 
128     Val.setInt(overdefined);
129     return true;
130   }
131 
132   /// markConstant - Return true if this is a change in status.
markConstant(Constant * V)133   bool markConstant(Constant *V) {
134     if (getLatticeValue() == constant) { // Constant but not forcedconstant.
135       assert(getConstant() == V && "Marking constant with different value");
136       return false;
137     }
138 
139     if (isUnknown()) {
140       Val.setInt(constant);
141       assert(V && "Marking constant with NULL");
142       Val.setPointer(V);
143     } else {
144       assert(getLatticeValue() == forcedconstant &&
145              "Cannot move from overdefined to constant!");
146       // Stay at forcedconstant if the constant is the same.
147       if (V == getConstant()) return false;
148 
149       // Otherwise, we go to overdefined.  Assumptions made based on the
150       // forced value are possibly wrong.  Assuming this is another constant
151       // could expose a contradiction.
152       Val.setInt(overdefined);
153     }
154     return true;
155   }
156 
157   /// getConstantInt - If this is a constant with a ConstantInt value, return it
158   /// otherwise return null.
getConstantInt() const159   ConstantInt *getConstantInt() const {
160     if (isConstant())
161       return dyn_cast<ConstantInt>(getConstant());
162     return nullptr;
163   }
164 
165   /// getBlockAddress - If this is a constant with a BlockAddress value, return
166   /// it, otherwise return null.
getBlockAddress() const167   BlockAddress *getBlockAddress() const {
168     if (isConstant())
169       return dyn_cast<BlockAddress>(getConstant());
170     return nullptr;
171   }
172 
markForcedConstant(Constant * V)173   void markForcedConstant(Constant *V) {
174     assert(isUnknown() && "Can't force a defined value!");
175     Val.setInt(forcedconstant);
176     Val.setPointer(V);
177   }
178 
toValueLattice() const179   ValueLatticeElement toValueLattice() const {
180     if (isOverdefined())
181       return ValueLatticeElement::getOverdefined();
182     if (isConstant())
183       return ValueLatticeElement::get(getConstant());
184     return ValueLatticeElement();
185   }
186 };
187 
188 //===----------------------------------------------------------------------===//
189 //
190 /// SCCPSolver - This class is a general purpose solver for Sparse Conditional
191 /// Constant Propagation.
192 ///
193 class SCCPSolver : public InstVisitor<SCCPSolver> {
194   const DataLayout &DL;
195   std::function<const TargetLibraryInfo &(Function &)> GetTLI;
196   SmallPtrSet<BasicBlock *, 8> BBExecutable; // The BBs that are executable.
197   DenseMap<Value *, LatticeVal> ValueState;  // The state each value is in.
198   // The state each parameter is in.
199   DenseMap<Value *, ValueLatticeElement> ParamState;
200 
201   /// StructValueState - This maintains ValueState for values that have
202   /// StructType, for example for formal arguments, calls, insertelement, etc.
203   DenseMap<std::pair<Value *, unsigned>, LatticeVal> StructValueState;
204 
205   /// GlobalValue - If we are tracking any values for the contents of a global
206   /// variable, we keep a mapping from the constant accessor to the element of
207   /// the global, to the currently known value.  If the value becomes
208   /// overdefined, it's entry is simply removed from this map.
209   DenseMap<GlobalVariable *, LatticeVal> TrackedGlobals;
210 
211   /// TrackedRetVals - If we are tracking arguments into and the return
212   /// value out of a function, it will have an entry in this map, indicating
213   /// what the known return value for the function is.
214   MapVector<Function *, LatticeVal> TrackedRetVals;
215 
216   /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
217   /// that return multiple values.
218   MapVector<std::pair<Function *, unsigned>, LatticeVal> TrackedMultipleRetVals;
219 
220   /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
221   /// represented here for efficient lookup.
222   SmallPtrSet<Function *, 16> MRVFunctionsTracked;
223 
224   /// MustTailFunctions - Each function here is a callee of non-removable
225   /// musttail call site.
226   SmallPtrSet<Function *, 16> MustTailCallees;
227 
228   /// TrackingIncomingArguments - This is the set of functions for whose
229   /// arguments we make optimistic assumptions about and try to prove as
230   /// constants.
231   SmallPtrSet<Function *, 16> TrackingIncomingArguments;
232 
233   /// The reason for two worklists is that overdefined is the lowest state
234   /// on the lattice, and moving things to overdefined as fast as possible
235   /// makes SCCP converge much faster.
236   ///
237   /// By having a separate worklist, we accomplish this because everything
238   /// possibly overdefined will become overdefined at the soonest possible
239   /// point.
240   SmallVector<Value *, 64> OverdefinedInstWorkList;
241   SmallVector<Value *, 64> InstWorkList;
242 
243   // The BasicBlock work list
244   SmallVector<BasicBlock *, 64>  BBWorkList;
245 
246   /// KnownFeasibleEdges - Entries in this set are edges which have already had
247   /// PHI nodes retriggered.
248   using Edge = std::pair<BasicBlock *, BasicBlock *>;
249   DenseSet<Edge> KnownFeasibleEdges;
250 
251   DenseMap<Function *, AnalysisResultsForFn> AnalysisResults;
252   DenseMap<Value *, SmallPtrSet<User *, 2>> AdditionalUsers;
253 
254 public:
addAnalysis(Function & F,AnalysisResultsForFn A)255   void addAnalysis(Function &F, AnalysisResultsForFn A) {
256     AnalysisResults.insert({&F, std::move(A)});
257   }
258 
getPredicateInfoFor(Instruction * I)259   const PredicateBase *getPredicateInfoFor(Instruction *I) {
260     auto A = AnalysisResults.find(I->getParent()->getParent());
261     if (A == AnalysisResults.end())
262       return nullptr;
263     return A->second.PredInfo->getPredicateInfoFor(I);
264   }
265 
getDTU(Function & F)266   DomTreeUpdater getDTU(Function &F) {
267     auto A = AnalysisResults.find(&F);
268     assert(A != AnalysisResults.end() && "Need analysis results for function.");
269     return {A->second.DT, A->second.PDT, DomTreeUpdater::UpdateStrategy::Lazy};
270   }
271 
SCCPSolver(const DataLayout & DL,std::function<const TargetLibraryInfo & (Function &)> GetTLI)272   SCCPSolver(const DataLayout &DL,
273              std::function<const TargetLibraryInfo &(Function &)> GetTLI)
274       : DL(DL), GetTLI(std::move(GetTLI)) {}
275 
276   /// MarkBlockExecutable - This method can be used by clients to mark all of
277   /// the blocks that are known to be intrinsically live in the processed unit.
278   ///
279   /// This returns true if the block was not considered live before.
MarkBlockExecutable(BasicBlock * BB)280   bool MarkBlockExecutable(BasicBlock *BB) {
281     if (!BBExecutable.insert(BB).second)
282       return false;
283     LLVM_DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << '\n');
284     BBWorkList.push_back(BB);  // Add the block to the work list!
285     return true;
286   }
287 
288   /// TrackValueOfGlobalVariable - Clients can use this method to
289   /// inform the SCCPSolver that it should track loads and stores to the
290   /// specified global variable if it can.  This is only legal to call if
291   /// performing Interprocedural SCCP.
TrackValueOfGlobalVariable(GlobalVariable * GV)292   void TrackValueOfGlobalVariable(GlobalVariable *GV) {
293     // We only track the contents of scalar globals.
294     if (GV->getValueType()->isSingleValueType()) {
295       LatticeVal &IV = TrackedGlobals[GV];
296       if (!isa<UndefValue>(GV->getInitializer()))
297         IV.markConstant(GV->getInitializer());
298     }
299   }
300 
301   /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
302   /// and out of the specified function (which cannot have its address taken),
303   /// this method must be called.
AddTrackedFunction(Function * F)304   void AddTrackedFunction(Function *F) {
305     // Add an entry, F -> undef.
306     if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
307       MRVFunctionsTracked.insert(F);
308       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
309         TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
310                                                      LatticeVal()));
311     } else
312       TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
313   }
314 
315   /// AddMustTailCallee - If the SCCP solver finds that this function is called
316   /// from non-removable musttail call site.
AddMustTailCallee(Function * F)317   void AddMustTailCallee(Function *F) {
318     MustTailCallees.insert(F);
319   }
320 
321   /// Returns true if the given function is called from non-removable musttail
322   /// call site.
isMustTailCallee(Function * F)323   bool isMustTailCallee(Function *F) {
324     return MustTailCallees.count(F);
325   }
326 
AddArgumentTrackedFunction(Function * F)327   void AddArgumentTrackedFunction(Function *F) {
328     TrackingIncomingArguments.insert(F);
329   }
330 
331   /// Returns true if the given function is in the solver's set of
332   /// argument-tracked functions.
isArgumentTrackedFunction(Function * F)333   bool isArgumentTrackedFunction(Function *F) {
334     return TrackingIncomingArguments.count(F);
335   }
336 
337   /// Solve - Solve for constants and executable blocks.
338   void Solve();
339 
340   /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
341   /// that branches on undef values cannot reach any of their successors.
342   /// However, this is not a safe assumption.  After we solve dataflow, this
343   /// method should be use to handle this.  If this returns true, the solver
344   /// should be rerun.
345   bool ResolvedUndefsIn(Function &F);
346 
isBlockExecutable(BasicBlock * BB) const347   bool isBlockExecutable(BasicBlock *BB) const {
348     return BBExecutable.count(BB);
349   }
350 
351   // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
352   // block to the 'To' basic block is currently feasible.
353   bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
354 
getStructLatticeValueFor(Value * V) const355   std::vector<LatticeVal> getStructLatticeValueFor(Value *V) const {
356     std::vector<LatticeVal> StructValues;
357     auto *STy = dyn_cast<StructType>(V->getType());
358     assert(STy && "getStructLatticeValueFor() can be called only on structs");
359     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
360       auto I = StructValueState.find(std::make_pair(V, i));
361       assert(I != StructValueState.end() && "Value not in valuemap!");
362       StructValues.push_back(I->second);
363     }
364     return StructValues;
365   }
366 
getLatticeValueFor(Value * V) const367   const LatticeVal &getLatticeValueFor(Value *V) const {
368     assert(!V->getType()->isStructTy() &&
369            "Should use getStructLatticeValueFor");
370     DenseMap<Value *, LatticeVal>::const_iterator I = ValueState.find(V);
371     assert(I != ValueState.end() &&
372            "V not found in ValueState nor Paramstate map!");
373     return I->second;
374   }
375 
376   /// getTrackedRetVals - Get the inferred return value map.
getTrackedRetVals()377   const MapVector<Function*, LatticeVal> &getTrackedRetVals() {
378     return TrackedRetVals;
379   }
380 
381   /// getTrackedGlobals - Get and return the set of inferred initializers for
382   /// global variables.
getTrackedGlobals()383   const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
384     return TrackedGlobals;
385   }
386 
387   /// getMRVFunctionsTracked - Get the set of functions which return multiple
388   /// values tracked by the pass.
getMRVFunctionsTracked()389   const SmallPtrSet<Function *, 16> getMRVFunctionsTracked() {
390     return MRVFunctionsTracked;
391   }
392 
393   /// getMustTailCallees - Get the set of functions which are called
394   /// from non-removable musttail call sites.
getMustTailCallees()395   const SmallPtrSet<Function *, 16> getMustTailCallees() {
396     return MustTailCallees;
397   }
398 
399   /// markOverdefined - Mark the specified value overdefined.  This
400   /// works with both scalars and structs.
markOverdefined(Value * V)401   void markOverdefined(Value *V) {
402     if (auto *STy = dyn_cast<StructType>(V->getType()))
403       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
404         markOverdefined(getStructValueState(V, i), V);
405     else
406       markOverdefined(ValueState[V], V);
407   }
408 
409   // isStructLatticeConstant - Return true if all the lattice values
410   // corresponding to elements of the structure are not overdefined,
411   // false otherwise.
isStructLatticeConstant(Function * F,StructType * STy)412   bool isStructLatticeConstant(Function *F, StructType *STy) {
413     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
414       const auto &It = TrackedMultipleRetVals.find(std::make_pair(F, i));
415       assert(It != TrackedMultipleRetVals.end());
416       LatticeVal LV = It->second;
417       if (LV.isOverdefined())
418         return false;
419     }
420     return true;
421   }
422 
423 private:
424   // pushToWorkList - Helper for markConstant/markForcedConstant/markOverdefined
pushToWorkList(LatticeVal & IV,Value * V)425   void pushToWorkList(LatticeVal &IV, Value *V) {
426     if (IV.isOverdefined())
427       return OverdefinedInstWorkList.push_back(V);
428     InstWorkList.push_back(V);
429   }
430 
431   // markConstant - Make a value be marked as "constant".  If the value
432   // is not already a constant, add it to the instruction work list so that
433   // the users of the instruction are updated later.
markConstant(LatticeVal & IV,Value * V,Constant * C)434   bool markConstant(LatticeVal &IV, Value *V, Constant *C) {
435     if (!IV.markConstant(C)) return false;
436     LLVM_DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
437     pushToWorkList(IV, V);
438     return true;
439   }
440 
markConstant(Value * V,Constant * C)441   bool markConstant(Value *V, Constant *C) {
442     assert(!V->getType()->isStructTy() && "structs should use mergeInValue");
443     return markConstant(ValueState[V], V, C);
444   }
445 
markForcedConstant(Value * V,Constant * C)446   void markForcedConstant(Value *V, Constant *C) {
447     assert(!V->getType()->isStructTy() && "structs should use mergeInValue");
448     LatticeVal &IV = ValueState[V];
449     IV.markForcedConstant(C);
450     LLVM_DEBUG(dbgs() << "markForcedConstant: " << *C << ": " << *V << '\n');
451     pushToWorkList(IV, V);
452   }
453 
454   // markOverdefined - Make a value be marked as "overdefined". If the
455   // value is not already overdefined, add it to the overdefined instruction
456   // work list so that the users of the instruction are updated later.
markOverdefined(LatticeVal & IV,Value * V)457   bool markOverdefined(LatticeVal &IV, Value *V) {
458     if (!IV.markOverdefined()) return false;
459 
460     LLVM_DEBUG(dbgs() << "markOverdefined: ";
461                if (auto *F = dyn_cast<Function>(V)) dbgs()
462                << "Function '" << F->getName() << "'\n";
463                else dbgs() << *V << '\n');
464     // Only instructions go on the work list
465     pushToWorkList(IV, V);
466     return true;
467   }
468 
mergeInValue(LatticeVal & IV,Value * V,LatticeVal MergeWithV)469   bool mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
470     if (IV.isOverdefined() || MergeWithV.isUnknown())
471       return false; // Noop.
472     if (MergeWithV.isOverdefined())
473       return markOverdefined(IV, V);
474     if (IV.isUnknown())
475       return markConstant(IV, V, MergeWithV.getConstant());
476     if (IV.getConstant() != MergeWithV.getConstant())
477       return markOverdefined(IV, V);
478     return false;
479   }
480 
mergeInValue(Value * V,LatticeVal MergeWithV)481   bool mergeInValue(Value *V, LatticeVal MergeWithV) {
482     assert(!V->getType()->isStructTy() &&
483            "non-structs should use markConstant");
484     return mergeInValue(ValueState[V], V, MergeWithV);
485   }
486 
487   /// getValueState - Return the LatticeVal object that corresponds to the
488   /// value.  This function handles the case when the value hasn't been seen yet
489   /// by properly seeding constants etc.
getValueState(Value * V)490   LatticeVal &getValueState(Value *V) {
491     assert(!V->getType()->isStructTy() && "Should use getStructValueState");
492 
493     std::pair<DenseMap<Value*, LatticeVal>::iterator, bool> I =
494       ValueState.insert(std::make_pair(V, LatticeVal()));
495     LatticeVal &LV = I.first->second;
496 
497     if (!I.second)
498       return LV;  // Common case, already in the map.
499 
500     if (auto *C = dyn_cast<Constant>(V)) {
501       // Undef values remain unknown.
502       if (!isa<UndefValue>(V))
503         LV.markConstant(C);          // Constants are constant
504     }
505 
506     // All others are underdefined by default.
507     return LV;
508   }
509 
getParamState(Value * V)510   ValueLatticeElement &getParamState(Value *V) {
511     assert(!V->getType()->isStructTy() && "Should use getStructValueState");
512 
513     std::pair<DenseMap<Value*, ValueLatticeElement>::iterator, bool>
514         PI = ParamState.insert(std::make_pair(V, ValueLatticeElement()));
515     ValueLatticeElement &LV = PI.first->second;
516     if (PI.second)
517       LV = getValueState(V).toValueLattice();
518 
519     return LV;
520   }
521 
522   /// getStructValueState - Return the LatticeVal object that corresponds to the
523   /// value/field pair.  This function handles the case when the value hasn't
524   /// been seen yet by properly seeding constants etc.
getStructValueState(Value * V,unsigned i)525   LatticeVal &getStructValueState(Value *V, unsigned i) {
526     assert(V->getType()->isStructTy() && "Should use getValueState");
527     assert(i < cast<StructType>(V->getType())->getNumElements() &&
528            "Invalid element #");
529 
530     std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator,
531               bool> I = StructValueState.insert(
532                         std::make_pair(std::make_pair(V, i), LatticeVal()));
533     LatticeVal &LV = I.first->second;
534 
535     if (!I.second)
536       return LV;  // Common case, already in the map.
537 
538     if (auto *C = dyn_cast<Constant>(V)) {
539       Constant *Elt = C->getAggregateElement(i);
540 
541       if (!Elt)
542         LV.markOverdefined();      // Unknown sort of constant.
543       else if (isa<UndefValue>(Elt))
544         ; // Undef values remain unknown.
545       else
546         LV.markConstant(Elt);      // Constants are constant.
547     }
548 
549     // All others are underdefined by default.
550     return LV;
551   }
552 
553   /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
554   /// work list if it is not already executable.
markEdgeExecutable(BasicBlock * Source,BasicBlock * Dest)555   bool markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
556     if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
557       return false;  // This edge is already known to be executable!
558 
559     if (!MarkBlockExecutable(Dest)) {
560       // If the destination is already executable, we just made an *edge*
561       // feasible that wasn't before.  Revisit the PHI nodes in the block
562       // because they have potentially new operands.
563       LLVM_DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
564                         << " -> " << Dest->getName() << '\n');
565 
566       for (PHINode &PN : Dest->phis())
567         visitPHINode(PN);
568     }
569     return true;
570   }
571 
572   // getFeasibleSuccessors - Return a vector of booleans to indicate which
573   // successors are reachable from a given terminator instruction.
574   void getFeasibleSuccessors(Instruction &TI, SmallVectorImpl<bool> &Succs);
575 
576   // OperandChangedState - This method is invoked on all of the users of an
577   // instruction that was just changed state somehow.  Based on this
578   // information, we need to update the specified user of this instruction.
OperandChangedState(Instruction * I)579   void OperandChangedState(Instruction *I) {
580     if (BBExecutable.count(I->getParent()))   // Inst is executable?
581       visit(*I);
582   }
583 
584   // Add U as additional user of V.
addAdditionalUser(Value * V,User * U)585   void addAdditionalUser(Value *V, User *U) {
586     auto Iter = AdditionalUsers.insert({V, {}});
587     Iter.first->second.insert(U);
588   }
589 
590   // Mark I's users as changed, including AdditionalUsers.
markUsersAsChanged(Value * I)591   void markUsersAsChanged(Value *I) {
592     for (User *U : I->users())
593       if (auto *UI = dyn_cast<Instruction>(U))
594         OperandChangedState(UI);
595 
596     auto Iter = AdditionalUsers.find(I);
597     if (Iter != AdditionalUsers.end()) {
598       for (User *U : Iter->second)
599         if (auto *UI = dyn_cast<Instruction>(U))
600           OperandChangedState(UI);
601     }
602   }
603 
604 private:
605   friend class InstVisitor<SCCPSolver>;
606 
607   // visit implementations - Something changed in this instruction.  Either an
608   // operand made a transition, or the instruction is newly executable.  Change
609   // the value type of I to reflect these changes if appropriate.
610   void visitPHINode(PHINode &I);
611 
612   // Terminators
613 
614   void visitReturnInst(ReturnInst &I);
615   void visitTerminator(Instruction &TI);
616 
617   void visitCastInst(CastInst &I);
618   void visitSelectInst(SelectInst &I);
619   void visitUnaryOperator(Instruction &I);
620   void visitBinaryOperator(Instruction &I);
621   void visitCmpInst(CmpInst &I);
622   void visitExtractValueInst(ExtractValueInst &EVI);
623   void visitInsertValueInst(InsertValueInst &IVI);
624 
visitCatchSwitchInst(CatchSwitchInst & CPI)625   void visitCatchSwitchInst(CatchSwitchInst &CPI) {
626     markOverdefined(&CPI);
627     visitTerminator(CPI);
628   }
629 
630   // Instructions that cannot be folded away.
631 
632   void visitStoreInst     (StoreInst &I);
633   void visitLoadInst      (LoadInst &I);
634   void visitGetElementPtrInst(GetElementPtrInst &I);
635 
visitCallInst(CallInst & I)636   void visitCallInst      (CallInst &I) {
637     visitCallSite(&I);
638   }
639 
visitInvokeInst(InvokeInst & II)640   void visitInvokeInst    (InvokeInst &II) {
641     visitCallSite(&II);
642     visitTerminator(II);
643   }
644 
visitCallBrInst(CallBrInst & CBI)645   void visitCallBrInst    (CallBrInst &CBI) {
646     visitCallSite(&CBI);
647     visitTerminator(CBI);
648   }
649 
650   void visitCallSite      (CallSite CS);
visitResumeInst(ResumeInst & I)651   void visitResumeInst    (ResumeInst &I) { /*returns void*/ }
visitUnreachableInst(UnreachableInst & I)652   void visitUnreachableInst(UnreachableInst &I) { /*returns void*/ }
visitFenceInst(FenceInst & I)653   void visitFenceInst     (FenceInst &I) { /*returns void*/ }
654 
visitInstruction(Instruction & I)655   void visitInstruction(Instruction &I) {
656     // All the instructions we don't do any special handling for just
657     // go to overdefined.
658     LLVM_DEBUG(dbgs() << "SCCP: Don't know how to handle: " << I << '\n');
659     markOverdefined(&I);
660   }
661 };
662 
663 } // end anonymous namespace
664 
665 // getFeasibleSuccessors - Return a vector of booleans to indicate which
666 // successors are reachable from a given terminator instruction.
getFeasibleSuccessors(Instruction & TI,SmallVectorImpl<bool> & Succs)667 void SCCPSolver::getFeasibleSuccessors(Instruction &TI,
668                                        SmallVectorImpl<bool> &Succs) {
669   Succs.resize(TI.getNumSuccessors());
670   if (auto *BI = dyn_cast<BranchInst>(&TI)) {
671     if (BI->isUnconditional()) {
672       Succs[0] = true;
673       return;
674     }
675 
676     LatticeVal BCValue = getValueState(BI->getCondition());
677     ConstantInt *CI = BCValue.getConstantInt();
678     if (!CI) {
679       // Overdefined condition variables, and branches on unfoldable constant
680       // conditions, mean the branch could go either way.
681       if (!BCValue.isUnknown())
682         Succs[0] = Succs[1] = true;
683       return;
684     }
685 
686     // Constant condition variables mean the branch can only go a single way.
687     Succs[CI->isZero()] = true;
688     return;
689   }
690 
691   // Unwinding instructions successors are always executable.
692   if (TI.isExceptionalTerminator()) {
693     Succs.assign(TI.getNumSuccessors(), true);
694     return;
695   }
696 
697   if (auto *SI = dyn_cast<SwitchInst>(&TI)) {
698     if (!SI->getNumCases()) {
699       Succs[0] = true;
700       return;
701     }
702     LatticeVal SCValue = getValueState(SI->getCondition());
703     ConstantInt *CI = SCValue.getConstantInt();
704 
705     if (!CI) {   // Overdefined or unknown condition?
706       // All destinations are executable!
707       if (!SCValue.isUnknown())
708         Succs.assign(TI.getNumSuccessors(), true);
709       return;
710     }
711 
712     Succs[SI->findCaseValue(CI)->getSuccessorIndex()] = true;
713     return;
714   }
715 
716   // In case of indirect branch and its address is a blockaddress, we mark
717   // the target as executable.
718   if (auto *IBR = dyn_cast<IndirectBrInst>(&TI)) {
719     // Casts are folded by visitCastInst.
720     LatticeVal IBRValue = getValueState(IBR->getAddress());
721     BlockAddress *Addr = IBRValue.getBlockAddress();
722     if (!Addr) {   // Overdefined or unknown condition?
723       // All destinations are executable!
724       if (!IBRValue.isUnknown())
725         Succs.assign(TI.getNumSuccessors(), true);
726       return;
727     }
728 
729     BasicBlock* T = Addr->getBasicBlock();
730     assert(Addr->getFunction() == T->getParent() &&
731            "Block address of a different function ?");
732     for (unsigned i = 0; i < IBR->getNumSuccessors(); ++i) {
733       // This is the target.
734       if (IBR->getDestination(i) == T) {
735         Succs[i] = true;
736         return;
737       }
738     }
739 
740     // If we didn't find our destination in the IBR successor list, then we
741     // have undefined behavior. Its ok to assume no successor is executable.
742     return;
743   }
744 
745   // In case of callbr, we pessimistically assume that all successors are
746   // feasible.
747   if (isa<CallBrInst>(&TI)) {
748     Succs.assign(TI.getNumSuccessors(), true);
749     return;
750   }
751 
752   LLVM_DEBUG(dbgs() << "Unknown terminator instruction: " << TI << '\n');
753   llvm_unreachable("SCCP: Don't know how to handle this terminator!");
754 }
755 
756 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
757 // block to the 'To' basic block is currently feasible.
isEdgeFeasible(BasicBlock * From,BasicBlock * To)758 bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
759   // Check if we've called markEdgeExecutable on the edge yet. (We could
760   // be more aggressive and try to consider edges which haven't been marked
761   // yet, but there isn't any need.)
762   return KnownFeasibleEdges.count(Edge(From, To));
763 }
764 
765 // visit Implementations - Something changed in this instruction, either an
766 // operand made a transition, or the instruction is newly executable.  Change
767 // the value type of I to reflect these changes if appropriate.  This method
768 // makes sure to do the following actions:
769 //
770 // 1. If a phi node merges two constants in, and has conflicting value coming
771 //    from different branches, or if the PHI node merges in an overdefined
772 //    value, then the PHI node becomes overdefined.
773 // 2. If a phi node merges only constants in, and they all agree on value, the
774 //    PHI node becomes a constant value equal to that.
775 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
776 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
777 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
778 // 6. If a conditional branch has a value that is constant, make the selected
779 //    destination executable
780 // 7. If a conditional branch has a value that is overdefined, make all
781 //    successors executable.
visitPHINode(PHINode & PN)782 void SCCPSolver::visitPHINode(PHINode &PN) {
783   // If this PN returns a struct, just mark the result overdefined.
784   // TODO: We could do a lot better than this if code actually uses this.
785   if (PN.getType()->isStructTy())
786     return (void)markOverdefined(&PN);
787 
788   if (getValueState(&PN).isOverdefined())
789     return;  // Quick exit
790 
791   // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
792   // and slow us down a lot.  Just mark them overdefined.
793   if (PN.getNumIncomingValues() > 64)
794     return (void)markOverdefined(&PN);
795 
796   // Look at all of the executable operands of the PHI node.  If any of them
797   // are overdefined, the PHI becomes overdefined as well.  If they are all
798   // constant, and they agree with each other, the PHI becomes the identical
799   // constant.  If they are constant and don't agree, the PHI is overdefined.
800   // If there are no executable operands, the PHI remains unknown.
801   Constant *OperandVal = nullptr;
802   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
803     LatticeVal IV = getValueState(PN.getIncomingValue(i));
804     if (IV.isUnknown()) continue;  // Doesn't influence PHI node.
805 
806     if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
807       continue;
808 
809     if (IV.isOverdefined())    // PHI node becomes overdefined!
810       return (void)markOverdefined(&PN);
811 
812     if (!OperandVal) {   // Grab the first value.
813       OperandVal = IV.getConstant();
814       continue;
815     }
816 
817     // There is already a reachable operand.  If we conflict with it,
818     // then the PHI node becomes overdefined.  If we agree with it, we
819     // can continue on.
820 
821     // Check to see if there are two different constants merging, if so, the PHI
822     // node is overdefined.
823     if (IV.getConstant() != OperandVal)
824       return (void)markOverdefined(&PN);
825   }
826 
827   // If we exited the loop, this means that the PHI node only has constant
828   // arguments that agree with each other(and OperandVal is the constant) or
829   // OperandVal is null because there are no defined incoming arguments.  If
830   // this is the case, the PHI remains unknown.
831   if (OperandVal)
832     markConstant(&PN, OperandVal);      // Acquire operand value
833 }
834 
visitReturnInst(ReturnInst & I)835 void SCCPSolver::visitReturnInst(ReturnInst &I) {
836   if (I.getNumOperands() == 0) return;  // ret void
837 
838   Function *F = I.getParent()->getParent();
839   Value *ResultOp = I.getOperand(0);
840 
841   // If we are tracking the return value of this function, merge it in.
842   if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
843     MapVector<Function*, LatticeVal>::iterator TFRVI =
844       TrackedRetVals.find(F);
845     if (TFRVI != TrackedRetVals.end()) {
846       mergeInValue(TFRVI->second, F, getValueState(ResultOp));
847       return;
848     }
849   }
850 
851   // Handle functions that return multiple values.
852   if (!TrackedMultipleRetVals.empty()) {
853     if (auto *STy = dyn_cast<StructType>(ResultOp->getType()))
854       if (MRVFunctionsTracked.count(F))
855         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
856           mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
857                        getStructValueState(ResultOp, i));
858   }
859 }
860 
visitTerminator(Instruction & TI)861 void SCCPSolver::visitTerminator(Instruction &TI) {
862   SmallVector<bool, 16> SuccFeasible;
863   getFeasibleSuccessors(TI, SuccFeasible);
864 
865   BasicBlock *BB = TI.getParent();
866 
867   // Mark all feasible successors executable.
868   for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
869     if (SuccFeasible[i])
870       markEdgeExecutable(BB, TI.getSuccessor(i));
871 }
872 
visitCastInst(CastInst & I)873 void SCCPSolver::visitCastInst(CastInst &I) {
874   LatticeVal OpSt = getValueState(I.getOperand(0));
875   if (OpSt.isOverdefined())          // Inherit overdefinedness of operand
876     markOverdefined(&I);
877   else if (OpSt.isConstant()) {
878     // Fold the constant as we build.
879     Constant *C = ConstantFoldCastOperand(I.getOpcode(), OpSt.getConstant(),
880                                           I.getType(), DL);
881     if (isa<UndefValue>(C))
882       return;
883     // Propagate constant value
884     markConstant(&I, C);
885   }
886 }
887 
visitExtractValueInst(ExtractValueInst & EVI)888 void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
889   // If this returns a struct, mark all elements over defined, we don't track
890   // structs in structs.
891   if (EVI.getType()->isStructTy())
892     return (void)markOverdefined(&EVI);
893 
894   // If this is extracting from more than one level of struct, we don't know.
895   if (EVI.getNumIndices() != 1)
896     return (void)markOverdefined(&EVI);
897 
898   Value *AggVal = EVI.getAggregateOperand();
899   if (AggVal->getType()->isStructTy()) {
900     unsigned i = *EVI.idx_begin();
901     LatticeVal EltVal = getStructValueState(AggVal, i);
902     mergeInValue(getValueState(&EVI), &EVI, EltVal);
903   } else {
904     // Otherwise, must be extracting from an array.
905     return (void)markOverdefined(&EVI);
906   }
907 }
908 
visitInsertValueInst(InsertValueInst & IVI)909 void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
910   auto *STy = dyn_cast<StructType>(IVI.getType());
911   if (!STy)
912     return (void)markOverdefined(&IVI);
913 
914   // If this has more than one index, we can't handle it, drive all results to
915   // undef.
916   if (IVI.getNumIndices() != 1)
917     return (void)markOverdefined(&IVI);
918 
919   Value *Aggr = IVI.getAggregateOperand();
920   unsigned Idx = *IVI.idx_begin();
921 
922   // Compute the result based on what we're inserting.
923   for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
924     // This passes through all values that aren't the inserted element.
925     if (i != Idx) {
926       LatticeVal EltVal = getStructValueState(Aggr, i);
927       mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
928       continue;
929     }
930 
931     Value *Val = IVI.getInsertedValueOperand();
932     if (Val->getType()->isStructTy())
933       // We don't track structs in structs.
934       markOverdefined(getStructValueState(&IVI, i), &IVI);
935     else {
936       LatticeVal InVal = getValueState(Val);
937       mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
938     }
939   }
940 }
941 
visitSelectInst(SelectInst & I)942 void SCCPSolver::visitSelectInst(SelectInst &I) {
943   // If this select returns a struct, just mark the result overdefined.
944   // TODO: We could do a lot better than this if code actually uses this.
945   if (I.getType()->isStructTy())
946     return (void)markOverdefined(&I);
947 
948   LatticeVal CondValue = getValueState(I.getCondition());
949   if (CondValue.isUnknown())
950     return;
951 
952   if (ConstantInt *CondCB = CondValue.getConstantInt()) {
953     Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
954     mergeInValue(&I, getValueState(OpVal));
955     return;
956   }
957 
958   // Otherwise, the condition is overdefined or a constant we can't evaluate.
959   // See if we can produce something better than overdefined based on the T/F
960   // value.
961   LatticeVal TVal = getValueState(I.getTrueValue());
962   LatticeVal FVal = getValueState(I.getFalseValue());
963 
964   // select ?, C, C -> C.
965   if (TVal.isConstant() && FVal.isConstant() &&
966       TVal.getConstant() == FVal.getConstant())
967     return (void)markConstant(&I, FVal.getConstant());
968 
969   if (TVal.isUnknown())   // select ?, undef, X -> X.
970     return (void)mergeInValue(&I, FVal);
971   if (FVal.isUnknown())   // select ?, X, undef -> X.
972     return (void)mergeInValue(&I, TVal);
973   markOverdefined(&I);
974 }
975 
976 // Handle Unary Operators.
visitUnaryOperator(Instruction & I)977 void SCCPSolver::visitUnaryOperator(Instruction &I) {
978   LatticeVal V0State = getValueState(I.getOperand(0));
979 
980   LatticeVal &IV = ValueState[&I];
981   if (IV.isOverdefined()) return;
982 
983   if (V0State.isConstant()) {
984     Constant *C = ConstantExpr::get(I.getOpcode(), V0State.getConstant());
985 
986     // op Y -> undef.
987     if (isa<UndefValue>(C))
988       return;
989     return (void)markConstant(IV, &I, C);
990   }
991 
992   // If something is undef, wait for it to resolve.
993   if (!V0State.isOverdefined())
994     return;
995 
996   markOverdefined(&I);
997 }
998 
999 // Handle Binary Operators.
visitBinaryOperator(Instruction & I)1000 void SCCPSolver::visitBinaryOperator(Instruction &I) {
1001   LatticeVal V1State = getValueState(I.getOperand(0));
1002   LatticeVal V2State = getValueState(I.getOperand(1));
1003 
1004   LatticeVal &IV = ValueState[&I];
1005   if (IV.isOverdefined()) return;
1006 
1007   if (V1State.isConstant() && V2State.isConstant()) {
1008     Constant *C = ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
1009                                     V2State.getConstant());
1010     // X op Y -> undef.
1011     if (isa<UndefValue>(C))
1012       return;
1013     return (void)markConstant(IV, &I, C);
1014   }
1015 
1016   // If something is undef, wait for it to resolve.
1017   if (!V1State.isOverdefined() && !V2State.isOverdefined())
1018     return;
1019 
1020   // Otherwise, one of our operands is overdefined.  Try to produce something
1021   // better than overdefined with some tricks.
1022   // If this is 0 / Y, it doesn't matter that the second operand is
1023   // overdefined, and we can replace it with zero.
1024   if (I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction::SDiv)
1025     if (V1State.isConstant() && V1State.getConstant()->isNullValue())
1026       return (void)markConstant(IV, &I, V1State.getConstant());
1027 
1028   // If this is:
1029   // -> AND/MUL with 0
1030   // -> OR with -1
1031   // it doesn't matter that the other operand is overdefined.
1032   if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Mul ||
1033       I.getOpcode() == Instruction::Or) {
1034     LatticeVal *NonOverdefVal = nullptr;
1035     if (!V1State.isOverdefined())
1036       NonOverdefVal = &V1State;
1037     else if (!V2State.isOverdefined())
1038       NonOverdefVal = &V2State;
1039 
1040     if (NonOverdefVal) {
1041       if (NonOverdefVal->isUnknown())
1042         return;
1043 
1044       if (I.getOpcode() == Instruction::And ||
1045           I.getOpcode() == Instruction::Mul) {
1046         // X and 0 = 0
1047         // X * 0 = 0
1048         if (NonOverdefVal->getConstant()->isNullValue())
1049           return (void)markConstant(IV, &I, NonOverdefVal->getConstant());
1050       } else {
1051         // X or -1 = -1
1052         if (ConstantInt *CI = NonOverdefVal->getConstantInt())
1053           if (CI->isMinusOne())
1054             return (void)markConstant(IV, &I, NonOverdefVal->getConstant());
1055       }
1056     }
1057   }
1058 
1059   markOverdefined(&I);
1060 }
1061 
1062 // Handle ICmpInst instruction.
visitCmpInst(CmpInst & I)1063 void SCCPSolver::visitCmpInst(CmpInst &I) {
1064   // Do not cache this lookup, getValueState calls later in the function might
1065   // invalidate the reference.
1066   if (ValueState[&I].isOverdefined()) return;
1067 
1068   Value *Op1 = I.getOperand(0);
1069   Value *Op2 = I.getOperand(1);
1070 
1071   // For parameters, use ParamState which includes constant range info if
1072   // available.
1073   auto V1Param = ParamState.find(Op1);
1074   ValueLatticeElement V1State = (V1Param != ParamState.end())
1075                                     ? V1Param->second
1076                                     : getValueState(Op1).toValueLattice();
1077 
1078   auto V2Param = ParamState.find(Op2);
1079   ValueLatticeElement V2State = V2Param != ParamState.end()
1080                                     ? V2Param->second
1081                                     : getValueState(Op2).toValueLattice();
1082 
1083   Constant *C = V1State.getCompare(I.getPredicate(), I.getType(), V2State);
1084   if (C) {
1085     if (isa<UndefValue>(C))
1086       return;
1087     LatticeVal CV;
1088     CV.markConstant(C);
1089     mergeInValue(&I, CV);
1090     return;
1091   }
1092 
1093   // If operands are still unknown, wait for it to resolve.
1094   if (!V1State.isOverdefined() && !V2State.isOverdefined() &&
1095       !ValueState[&I].isConstant())
1096     return;
1097 
1098   markOverdefined(&I);
1099 }
1100 
1101 // Handle getelementptr instructions.  If all operands are constants then we
1102 // can turn this into a getelementptr ConstantExpr.
visitGetElementPtrInst(GetElementPtrInst & I)1103 void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
1104   if (ValueState[&I].isOverdefined()) return;
1105 
1106   SmallVector<Constant*, 8> Operands;
1107   Operands.reserve(I.getNumOperands());
1108 
1109   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1110     LatticeVal State = getValueState(I.getOperand(i));
1111     if (State.isUnknown())
1112       return;  // Operands are not resolved yet.
1113 
1114     if (State.isOverdefined())
1115       return (void)markOverdefined(&I);
1116 
1117     assert(State.isConstant() && "Unknown state!");
1118     Operands.push_back(State.getConstant());
1119   }
1120 
1121   Constant *Ptr = Operands[0];
1122   auto Indices = makeArrayRef(Operands.begin() + 1, Operands.end());
1123   Constant *C =
1124       ConstantExpr::getGetElementPtr(I.getSourceElementType(), Ptr, Indices);
1125   if (isa<UndefValue>(C))
1126       return;
1127   markConstant(&I, C);
1128 }
1129 
visitStoreInst(StoreInst & SI)1130 void SCCPSolver::visitStoreInst(StoreInst &SI) {
1131   // If this store is of a struct, ignore it.
1132   if (SI.getOperand(0)->getType()->isStructTy())
1133     return;
1134 
1135   if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1136     return;
1137 
1138   GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1139   DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
1140   if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1141 
1142   // Get the value we are storing into the global, then merge it.
1143   mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
1144   if (I->second.isOverdefined())
1145     TrackedGlobals.erase(I);      // No need to keep tracking this!
1146 }
1147 
1148 // Handle load instructions.  If the operand is a constant pointer to a constant
1149 // global, we can replace the load with the loaded constant value!
visitLoadInst(LoadInst & I)1150 void SCCPSolver::visitLoadInst(LoadInst &I) {
1151   // If this load is of a struct, just mark the result overdefined.
1152   if (I.getType()->isStructTy())
1153     return (void)markOverdefined(&I);
1154 
1155   LatticeVal PtrVal = getValueState(I.getOperand(0));
1156   if (PtrVal.isUnknown()) return;   // The pointer is not resolved yet!
1157 
1158   LatticeVal &IV = ValueState[&I];
1159   if (IV.isOverdefined()) return;
1160 
1161   if (!PtrVal.isConstant() || I.isVolatile())
1162     return (void)markOverdefined(IV, &I);
1163 
1164   Constant *Ptr = PtrVal.getConstant();
1165 
1166   // load null is undefined.
1167   if (isa<ConstantPointerNull>(Ptr)) {
1168     if (NullPointerIsDefined(I.getFunction(), I.getPointerAddressSpace()))
1169       return (void)markOverdefined(IV, &I);
1170     else
1171       return;
1172   }
1173 
1174   // Transform load (constant global) into the value loaded.
1175   if (auto *GV = dyn_cast<GlobalVariable>(Ptr)) {
1176     if (!TrackedGlobals.empty()) {
1177       // If we are tracking this global, merge in the known value for it.
1178       DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1179         TrackedGlobals.find(GV);
1180       if (It != TrackedGlobals.end()) {
1181         mergeInValue(IV, &I, It->second);
1182         return;
1183       }
1184     }
1185   }
1186 
1187   // Transform load from a constant into a constant if possible.
1188   if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, I.getType(), DL)) {
1189     if (isa<UndefValue>(C))
1190       return;
1191     return (void)markConstant(IV, &I, C);
1192   }
1193 
1194   // Otherwise we cannot say for certain what value this load will produce.
1195   // Bail out.
1196   markOverdefined(IV, &I);
1197 }
1198 
visitCallSite(CallSite CS)1199 void SCCPSolver::visitCallSite(CallSite CS) {
1200   Function *F = CS.getCalledFunction();
1201   Instruction *I = CS.getInstruction();
1202 
1203   if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1204     if (II->getIntrinsicID() == Intrinsic::ssa_copy) {
1205       if (ValueState[I].isOverdefined())
1206         return;
1207 
1208       auto *PI = getPredicateInfoFor(I);
1209       if (!PI)
1210         return;
1211 
1212       Value *CopyOf = I->getOperand(0);
1213       auto *PBranch = dyn_cast<PredicateBranch>(PI);
1214       if (!PBranch) {
1215         mergeInValue(ValueState[I], I, getValueState(CopyOf));
1216         return;
1217       }
1218 
1219       Value *Cond = PBranch->Condition;
1220 
1221       // Everything below relies on the condition being a comparison.
1222       auto *Cmp = dyn_cast<CmpInst>(Cond);
1223       if (!Cmp) {
1224         mergeInValue(ValueState[I], I, getValueState(CopyOf));
1225         return;
1226       }
1227 
1228       Value *CmpOp0 = Cmp->getOperand(0);
1229       Value *CmpOp1 = Cmp->getOperand(1);
1230       if (CopyOf != CmpOp0 && CopyOf != CmpOp1) {
1231         mergeInValue(ValueState[I], I, getValueState(CopyOf));
1232         return;
1233       }
1234 
1235       if (CmpOp0 != CopyOf)
1236         std::swap(CmpOp0, CmpOp1);
1237 
1238       LatticeVal OriginalVal = getValueState(CopyOf);
1239       LatticeVal EqVal = getValueState(CmpOp1);
1240       LatticeVal &IV = ValueState[I];
1241       if (PBranch->TrueEdge && Cmp->getPredicate() == CmpInst::ICMP_EQ) {
1242         addAdditionalUser(CmpOp1, I);
1243         if (OriginalVal.isConstant())
1244           mergeInValue(IV, I, OriginalVal);
1245         else
1246           mergeInValue(IV, I, EqVal);
1247         return;
1248       }
1249       if (!PBranch->TrueEdge && Cmp->getPredicate() == CmpInst::ICMP_NE) {
1250         addAdditionalUser(CmpOp1, I);
1251         if (OriginalVal.isConstant())
1252           mergeInValue(IV, I, OriginalVal);
1253         else
1254           mergeInValue(IV, I, EqVal);
1255         return;
1256       }
1257 
1258       return (void)mergeInValue(IV, I, getValueState(CopyOf));
1259     }
1260   }
1261 
1262   // The common case is that we aren't tracking the callee, either because we
1263   // are not doing interprocedural analysis or the callee is indirect, or is
1264   // external.  Handle these cases first.
1265   if (!F || F->isDeclaration()) {
1266 CallOverdefined:
1267     // Void return and not tracking callee, just bail.
1268     if (I->getType()->isVoidTy()) return;
1269 
1270     // Otherwise, if we have a single return value case, and if the function is
1271     // a declaration, maybe we can constant fold it.
1272     if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
1273         canConstantFoldCallTo(cast<CallBase>(CS.getInstruction()), F)) {
1274       SmallVector<Constant*, 8> Operands;
1275       for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1276            AI != E; ++AI) {
1277         if (AI->get()->getType()->isStructTy())
1278           return markOverdefined(I); // Can't handle struct args.
1279         LatticeVal State = getValueState(*AI);
1280 
1281         if (State.isUnknown())
1282           return;  // Operands are not resolved yet.
1283         if (State.isOverdefined())
1284           return (void)markOverdefined(I);
1285         assert(State.isConstant() && "Unknown state!");
1286         Operands.push_back(State.getConstant());
1287       }
1288 
1289       if (getValueState(I).isOverdefined())
1290         return;
1291 
1292       // If we can constant fold this, mark the result of the call as a
1293       // constant.
1294       if (Constant *C = ConstantFoldCall(cast<CallBase>(CS.getInstruction()), F,
1295                                          Operands, &GetTLI(*F))) {
1296         // call -> undef.
1297         if (isa<UndefValue>(C))
1298           return;
1299         return (void)markConstant(I, C);
1300       }
1301     }
1302 
1303     // Otherwise, we don't know anything about this call, mark it overdefined.
1304     return (void)markOverdefined(I);
1305   }
1306 
1307   // If this is a local function that doesn't have its address taken, mark its
1308   // entry block executable and merge in the actual arguments to the call into
1309   // the formal arguments of the function.
1310   if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
1311     MarkBlockExecutable(&F->front());
1312 
1313     // Propagate information from this call site into the callee.
1314     CallSite::arg_iterator CAI = CS.arg_begin();
1315     for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1316          AI != E; ++AI, ++CAI) {
1317       // If this argument is byval, and if the function is not readonly, there
1318       // will be an implicit copy formed of the input aggregate.
1319       if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
1320         markOverdefined(&*AI);
1321         continue;
1322       }
1323 
1324       if (auto *STy = dyn_cast<StructType>(AI->getType())) {
1325         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1326           LatticeVal CallArg = getStructValueState(*CAI, i);
1327           mergeInValue(getStructValueState(&*AI, i), &*AI, CallArg);
1328         }
1329       } else {
1330         // Most other parts of the Solver still only use the simpler value
1331         // lattice, so we propagate changes for parameters to both lattices.
1332         LatticeVal ConcreteArgument = getValueState(*CAI);
1333         bool ParamChanged =
1334             getParamState(&*AI).mergeIn(ConcreteArgument.toValueLattice(), DL);
1335          bool ValueChanged = mergeInValue(&*AI, ConcreteArgument);
1336         // Add argument to work list, if the state of a parameter changes but
1337         // ValueState does not change (because it is already overdefined there),
1338         // We have to take changes in ParamState into account, as it is used
1339         // when evaluating Cmp instructions.
1340         if (!ValueChanged && ParamChanged)
1341           pushToWorkList(ValueState[&*AI], &*AI);
1342       }
1343     }
1344   }
1345 
1346   // If this is a single/zero retval case, see if we're tracking the function.
1347   if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
1348     if (!MRVFunctionsTracked.count(F))
1349       goto CallOverdefined;  // Not tracking this callee.
1350 
1351     // If we are tracking this callee, propagate the result of the function
1352     // into this call site.
1353     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1354       mergeInValue(getStructValueState(I, i), I,
1355                    TrackedMultipleRetVals[std::make_pair(F, i)]);
1356   } else {
1357     MapVector<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1358     if (TFRVI == TrackedRetVals.end())
1359       goto CallOverdefined;  // Not tracking this callee.
1360 
1361     // If so, propagate the return value of the callee into this call result.
1362     mergeInValue(I, TFRVI->second);
1363   }
1364 }
1365 
Solve()1366 void SCCPSolver::Solve() {
1367   // Process the work lists until they are empty!
1368   while (!BBWorkList.empty() || !InstWorkList.empty() ||
1369          !OverdefinedInstWorkList.empty()) {
1370     // Process the overdefined instruction's work list first, which drives other
1371     // things to overdefined more quickly.
1372     while (!OverdefinedInstWorkList.empty()) {
1373       Value *I = OverdefinedInstWorkList.pop_back_val();
1374 
1375       LLVM_DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
1376 
1377       // "I" got into the work list because it either made the transition from
1378       // bottom to constant, or to overdefined.
1379       //
1380       // Anything on this worklist that is overdefined need not be visited
1381       // since all of its users will have already been marked as overdefined
1382       // Update all of the users of this instruction's value.
1383       //
1384       markUsersAsChanged(I);
1385     }
1386 
1387     // Process the instruction work list.
1388     while (!InstWorkList.empty()) {
1389       Value *I = InstWorkList.pop_back_val();
1390 
1391       LLVM_DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
1392 
1393       // "I" got into the work list because it made the transition from undef to
1394       // constant.
1395       //
1396       // Anything on this worklist that is overdefined need not be visited
1397       // since all of its users will have already been marked as overdefined.
1398       // Update all of the users of this instruction's value.
1399       //
1400       if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
1401         markUsersAsChanged(I);
1402     }
1403 
1404     // Process the basic block work list.
1405     while (!BBWorkList.empty()) {
1406       BasicBlock *BB = BBWorkList.back();
1407       BBWorkList.pop_back();
1408 
1409       LLVM_DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
1410 
1411       // Notify all instructions in this basic block that they are newly
1412       // executable.
1413       visit(BB);
1414     }
1415   }
1416 }
1417 
1418 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1419 /// that branches on undef values cannot reach any of their successors.
1420 /// However, this is not a safe assumption.  After we solve dataflow, this
1421 /// method should be use to handle this.  If this returns true, the solver
1422 /// should be rerun.
1423 ///
1424 /// This method handles this by finding an unresolved branch and marking it one
1425 /// of the edges from the block as being feasible, even though the condition
1426 /// doesn't say it would otherwise be.  This allows SCCP to find the rest of the
1427 /// CFG and only slightly pessimizes the analysis results (by marking one,
1428 /// potentially infeasible, edge feasible).  This cannot usefully modify the
1429 /// constraints on the condition of the branch, as that would impact other users
1430 /// of the value.
1431 ///
1432 /// This scan also checks for values that use undefs, whose results are actually
1433 /// defined.  For example, 'zext i8 undef to i32' should produce all zeros
1434 /// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1435 /// even if X isn't defined.
ResolvedUndefsIn(Function & F)1436 bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1437   for (BasicBlock &BB : F) {
1438     if (!BBExecutable.count(&BB))
1439       continue;
1440 
1441     for (Instruction &I : BB) {
1442       // Look for instructions which produce undef values.
1443       if (I.getType()->isVoidTy()) continue;
1444 
1445       if (auto *STy = dyn_cast<StructType>(I.getType())) {
1446         // Only a few things that can be structs matter for undef.
1447 
1448         // Tracked calls must never be marked overdefined in ResolvedUndefsIn.
1449         if (CallSite CS = CallSite(&I))
1450           if (Function *F = CS.getCalledFunction())
1451             if (MRVFunctionsTracked.count(F))
1452               continue;
1453 
1454         // extractvalue and insertvalue don't need to be marked; they are
1455         // tracked as precisely as their operands.
1456         if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I))
1457           continue;
1458 
1459         // Send the results of everything else to overdefined.  We could be
1460         // more precise than this but it isn't worth bothering.
1461         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1462           LatticeVal &LV = getStructValueState(&I, i);
1463           if (LV.isUnknown())
1464             markOverdefined(LV, &I);
1465         }
1466         continue;
1467       }
1468 
1469       LatticeVal &LV = getValueState(&I);
1470       if (!LV.isUnknown())
1471         continue;
1472 
1473       // There are two reasons a call can have an undef result
1474       // 1. It could be tracked.
1475       // 2. It could be constant-foldable.
1476       // Because of the way we solve return values, tracked calls must
1477       // never be marked overdefined in ResolvedUndefsIn.
1478       if (CallSite CS = CallSite(&I)) {
1479         if (Function *F = CS.getCalledFunction())
1480           if (TrackedRetVals.count(F))
1481             continue;
1482 
1483         // If the call is constant-foldable, we mark it overdefined because
1484         // we do not know what return values are valid.
1485         markOverdefined(&I);
1486         return true;
1487       }
1488 
1489       // extractvalue is safe; check here because the argument is a struct.
1490       if (isa<ExtractValueInst>(I))
1491         continue;
1492 
1493       // Compute the operand LatticeVals, for convenience below.
1494       // Anything taking a struct is conservatively assumed to require
1495       // overdefined markings.
1496       if (I.getOperand(0)->getType()->isStructTy()) {
1497         markOverdefined(&I);
1498         return true;
1499       }
1500       LatticeVal Op0LV = getValueState(I.getOperand(0));
1501       LatticeVal Op1LV;
1502       if (I.getNumOperands() == 2) {
1503         if (I.getOperand(1)->getType()->isStructTy()) {
1504           markOverdefined(&I);
1505           return true;
1506         }
1507 
1508         Op1LV = getValueState(I.getOperand(1));
1509       }
1510       // If this is an instructions whose result is defined even if the input is
1511       // not fully defined, propagate the information.
1512       Type *ITy = I.getType();
1513       switch (I.getOpcode()) {
1514       case Instruction::Add:
1515       case Instruction::Sub:
1516       case Instruction::Trunc:
1517       case Instruction::FPTrunc:
1518       case Instruction::BitCast:
1519         break; // Any undef -> undef
1520       case Instruction::FSub:
1521       case Instruction::FAdd:
1522       case Instruction::FMul:
1523       case Instruction::FDiv:
1524       case Instruction::FRem:
1525         // Floating-point binary operation: be conservative.
1526         if (Op0LV.isUnknown() && Op1LV.isUnknown())
1527           markForcedConstant(&I, Constant::getNullValue(ITy));
1528         else
1529           markOverdefined(&I);
1530         return true;
1531       case Instruction::FNeg:
1532         break; // fneg undef -> undef
1533       case Instruction::ZExt:
1534       case Instruction::SExt:
1535       case Instruction::FPToUI:
1536       case Instruction::FPToSI:
1537       case Instruction::FPExt:
1538       case Instruction::PtrToInt:
1539       case Instruction::IntToPtr:
1540       case Instruction::SIToFP:
1541       case Instruction::UIToFP:
1542         // undef -> 0; some outputs are impossible
1543         markForcedConstant(&I, Constant::getNullValue(ITy));
1544         return true;
1545       case Instruction::Mul:
1546       case Instruction::And:
1547         // Both operands undef -> undef
1548         if (Op0LV.isUnknown() && Op1LV.isUnknown())
1549           break;
1550         // undef * X -> 0.   X could be zero.
1551         // undef & X -> 0.   X could be zero.
1552         markForcedConstant(&I, Constant::getNullValue(ITy));
1553         return true;
1554       case Instruction::Or:
1555         // Both operands undef -> undef
1556         if (Op0LV.isUnknown() && Op1LV.isUnknown())
1557           break;
1558         // undef | X -> -1.   X could be -1.
1559         markForcedConstant(&I, Constant::getAllOnesValue(ITy));
1560         return true;
1561       case Instruction::Xor:
1562         // undef ^ undef -> 0; strictly speaking, this is not strictly
1563         // necessary, but we try to be nice to people who expect this
1564         // behavior in simple cases
1565         if (Op0LV.isUnknown() && Op1LV.isUnknown()) {
1566           markForcedConstant(&I, Constant::getNullValue(ITy));
1567           return true;
1568         }
1569         // undef ^ X -> undef
1570         break;
1571       case Instruction::SDiv:
1572       case Instruction::UDiv:
1573       case Instruction::SRem:
1574       case Instruction::URem:
1575         // X / undef -> undef.  No change.
1576         // X % undef -> undef.  No change.
1577         if (Op1LV.isUnknown()) break;
1578 
1579         // X / 0 -> undef.  No change.
1580         // X % 0 -> undef.  No change.
1581         if (Op1LV.isConstant() && Op1LV.getConstant()->isZeroValue())
1582           break;
1583 
1584         // undef / X -> 0.   X could be maxint.
1585         // undef % X -> 0.   X could be 1.
1586         markForcedConstant(&I, Constant::getNullValue(ITy));
1587         return true;
1588       case Instruction::AShr:
1589         // X >>a undef -> undef.
1590         if (Op1LV.isUnknown()) break;
1591 
1592         // Shifting by the bitwidth or more is undefined.
1593         if (Op1LV.isConstant()) {
1594           if (auto *ShiftAmt = Op1LV.getConstantInt())
1595             if (ShiftAmt->getLimitedValue() >=
1596                 ShiftAmt->getType()->getScalarSizeInBits())
1597               break;
1598         }
1599 
1600         // undef >>a X -> 0
1601         markForcedConstant(&I, Constant::getNullValue(ITy));
1602         return true;
1603       case Instruction::LShr:
1604       case Instruction::Shl:
1605         // X << undef -> undef.
1606         // X >> undef -> undef.
1607         if (Op1LV.isUnknown()) break;
1608 
1609         // Shifting by the bitwidth or more is undefined.
1610         if (Op1LV.isConstant()) {
1611           if (auto *ShiftAmt = Op1LV.getConstantInt())
1612             if (ShiftAmt->getLimitedValue() >=
1613                 ShiftAmt->getType()->getScalarSizeInBits())
1614               break;
1615         }
1616 
1617         // undef << X -> 0
1618         // undef >> X -> 0
1619         markForcedConstant(&I, Constant::getNullValue(ITy));
1620         return true;
1621       case Instruction::Select:
1622         Op1LV = getValueState(I.getOperand(1));
1623         // undef ? X : Y  -> X or Y.  There could be commonality between X/Y.
1624         if (Op0LV.isUnknown()) {
1625           if (!Op1LV.isConstant())  // Pick the constant one if there is any.
1626             Op1LV = getValueState(I.getOperand(2));
1627         } else if (Op1LV.isUnknown()) {
1628           // c ? undef : undef -> undef.  No change.
1629           Op1LV = getValueState(I.getOperand(2));
1630           if (Op1LV.isUnknown())
1631             break;
1632           // Otherwise, c ? undef : x -> x.
1633         } else {
1634           // Leave Op1LV as Operand(1)'s LatticeValue.
1635         }
1636 
1637         if (Op1LV.isConstant())
1638           markForcedConstant(&I, Op1LV.getConstant());
1639         else
1640           markOverdefined(&I);
1641         return true;
1642       case Instruction::Load:
1643         // A load here means one of two things: a load of undef from a global,
1644         // a load from an unknown pointer.  Either way, having it return undef
1645         // is okay.
1646         break;
1647       case Instruction::ICmp:
1648         // X == undef -> undef.  Other comparisons get more complicated.
1649         Op0LV = getValueState(I.getOperand(0));
1650         Op1LV = getValueState(I.getOperand(1));
1651 
1652         if ((Op0LV.isUnknown() || Op1LV.isUnknown()) &&
1653             cast<ICmpInst>(&I)->isEquality())
1654           break;
1655         markOverdefined(&I);
1656         return true;
1657       case Instruction::Call:
1658       case Instruction::Invoke:
1659       case Instruction::CallBr:
1660         llvm_unreachable("Call-like instructions should have be handled early");
1661       default:
1662         // If we don't know what should happen here, conservatively mark it
1663         // overdefined.
1664         markOverdefined(&I);
1665         return true;
1666       }
1667     }
1668 
1669     // Check to see if we have a branch or switch on an undefined value.  If so
1670     // we force the branch to go one way or the other to make the successor
1671     // values live.  It doesn't really matter which way we force it.
1672     Instruction *TI = BB.getTerminator();
1673     if (auto *BI = dyn_cast<BranchInst>(TI)) {
1674       if (!BI->isConditional()) continue;
1675       if (!getValueState(BI->getCondition()).isUnknown())
1676         continue;
1677 
1678       // If the input to SCCP is actually branch on undef, fix the undef to
1679       // false.
1680       if (isa<UndefValue>(BI->getCondition())) {
1681         BI->setCondition(ConstantInt::getFalse(BI->getContext()));
1682         markEdgeExecutable(&BB, TI->getSuccessor(1));
1683         return true;
1684       }
1685 
1686       // Otherwise, it is a branch on a symbolic value which is currently
1687       // considered to be undef.  Make sure some edge is executable, so a
1688       // branch on "undef" always flows somewhere.
1689       // FIXME: Distinguish between dead code and an LLVM "undef" value.
1690       BasicBlock *DefaultSuccessor = TI->getSuccessor(1);
1691       if (markEdgeExecutable(&BB, DefaultSuccessor))
1692         return true;
1693 
1694       continue;
1695     }
1696 
1697    if (auto *IBR = dyn_cast<IndirectBrInst>(TI)) {
1698       // Indirect branch with no successor ?. Its ok to assume it branches
1699       // to no target.
1700       if (IBR->getNumSuccessors() < 1)
1701         continue;
1702 
1703       if (!getValueState(IBR->getAddress()).isUnknown())
1704         continue;
1705 
1706       // If the input to SCCP is actually branch on undef, fix the undef to
1707       // the first successor of the indirect branch.
1708       if (isa<UndefValue>(IBR->getAddress())) {
1709         IBR->setAddress(BlockAddress::get(IBR->getSuccessor(0)));
1710         markEdgeExecutable(&BB, IBR->getSuccessor(0));
1711         return true;
1712       }
1713 
1714       // Otherwise, it is a branch on a symbolic value which is currently
1715       // considered to be undef.  Make sure some edge is executable, so a
1716       // branch on "undef" always flows somewhere.
1717       // FIXME: IndirectBr on "undef" doesn't actually need to go anywhere:
1718       // we can assume the branch has undefined behavior instead.
1719       BasicBlock *DefaultSuccessor = IBR->getSuccessor(0);
1720       if (markEdgeExecutable(&BB, DefaultSuccessor))
1721         return true;
1722 
1723       continue;
1724     }
1725 
1726     if (auto *SI = dyn_cast<SwitchInst>(TI)) {
1727       if (!SI->getNumCases() || !getValueState(SI->getCondition()).isUnknown())
1728         continue;
1729 
1730       // If the input to SCCP is actually switch on undef, fix the undef to
1731       // the first constant.
1732       if (isa<UndefValue>(SI->getCondition())) {
1733         SI->setCondition(SI->case_begin()->getCaseValue());
1734         markEdgeExecutable(&BB, SI->case_begin()->getCaseSuccessor());
1735         return true;
1736       }
1737 
1738       // Otherwise, it is a branch on a symbolic value which is currently
1739       // considered to be undef.  Make sure some edge is executable, so a
1740       // branch on "undef" always flows somewhere.
1741       // FIXME: Distinguish between dead code and an LLVM "undef" value.
1742       BasicBlock *DefaultSuccessor = SI->case_begin()->getCaseSuccessor();
1743       if (markEdgeExecutable(&BB, DefaultSuccessor))
1744         return true;
1745 
1746       continue;
1747     }
1748   }
1749 
1750   return false;
1751 }
1752 
tryToReplaceWithConstant(SCCPSolver & Solver,Value * V)1753 static bool tryToReplaceWithConstant(SCCPSolver &Solver, Value *V) {
1754   Constant *Const = nullptr;
1755   if (V->getType()->isStructTy()) {
1756     std::vector<LatticeVal> IVs = Solver.getStructLatticeValueFor(V);
1757     if (llvm::any_of(IVs,
1758                      [](const LatticeVal &LV) { return LV.isOverdefined(); }))
1759       return false;
1760     std::vector<Constant *> ConstVals;
1761     auto *ST = cast<StructType>(V->getType());
1762     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1763       LatticeVal V = IVs[i];
1764       ConstVals.push_back(V.isConstant()
1765                               ? V.getConstant()
1766                               : UndefValue::get(ST->getElementType(i)));
1767     }
1768     Const = ConstantStruct::get(ST, ConstVals);
1769   } else {
1770     const LatticeVal &IV = Solver.getLatticeValueFor(V);
1771     if (IV.isOverdefined())
1772       return false;
1773 
1774     Const = IV.isConstant() ? IV.getConstant() : UndefValue::get(V->getType());
1775   }
1776   assert(Const && "Constant is nullptr here!");
1777 
1778   // Replacing `musttail` instructions with constant breaks `musttail` invariant
1779   // unless the call itself can be removed
1780   CallInst *CI = dyn_cast<CallInst>(V);
1781   if (CI && CI->isMustTailCall() && !CI->isSafeToRemove()) {
1782     CallSite CS(CI);
1783     Function *F = CS.getCalledFunction();
1784 
1785     // Don't zap returns of the callee
1786     if (F)
1787       Solver.AddMustTailCallee(F);
1788 
1789     LLVM_DEBUG(dbgs() << "  Can\'t treat the result of musttail call : " << *CI
1790                       << " as a constant\n");
1791     return false;
1792   }
1793 
1794   LLVM_DEBUG(dbgs() << "  Constant: " << *Const << " = " << *V << '\n');
1795 
1796   // Replaces all of the uses of a variable with uses of the constant.
1797   V->replaceAllUsesWith(Const);
1798   return true;
1799 }
1800 
1801 // runSCCP() - Run the Sparse Conditional Constant Propagation algorithm,
1802 // and return true if the function was modified.
runSCCP(Function & F,const DataLayout & DL,const TargetLibraryInfo * TLI)1803 static bool runSCCP(Function &F, const DataLayout &DL,
1804                     const TargetLibraryInfo *TLI) {
1805   LLVM_DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
1806   SCCPSolver Solver(
1807       DL, [TLI](Function &F) -> const TargetLibraryInfo & { return *TLI; });
1808 
1809   // Mark the first block of the function as being executable.
1810   Solver.MarkBlockExecutable(&F.front());
1811 
1812   // Mark all arguments to the function as being overdefined.
1813   for (Argument &AI : F.args())
1814     Solver.markOverdefined(&AI);
1815 
1816   // Solve for constants.
1817   bool ResolvedUndefs = true;
1818   while (ResolvedUndefs) {
1819     Solver.Solve();
1820     LLVM_DEBUG(dbgs() << "RESOLVING UNDEFs\n");
1821     ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1822   }
1823 
1824   bool MadeChanges = false;
1825 
1826   // If we decided that there are basic blocks that are dead in this function,
1827   // delete their contents now.  Note that we cannot actually delete the blocks,
1828   // as we cannot modify the CFG of the function.
1829 
1830   for (BasicBlock &BB : F) {
1831     if (!Solver.isBlockExecutable(&BB)) {
1832       LLVM_DEBUG(dbgs() << "  BasicBlock Dead:" << BB);
1833 
1834       ++NumDeadBlocks;
1835       NumInstRemoved += removeAllNonTerminatorAndEHPadInstructions(&BB);
1836 
1837       MadeChanges = true;
1838       continue;
1839     }
1840 
1841     // Iterate over all of the instructions in a function, replacing them with
1842     // constants if we have found them to be of constant values.
1843     for (BasicBlock::iterator BI = BB.begin(), E = BB.end(); BI != E;) {
1844       Instruction *Inst = &*BI++;
1845       if (Inst->getType()->isVoidTy() || Inst->isTerminator())
1846         continue;
1847 
1848       if (tryToReplaceWithConstant(Solver, Inst)) {
1849         if (isInstructionTriviallyDead(Inst))
1850           Inst->eraseFromParent();
1851         // Hey, we just changed something!
1852         MadeChanges = true;
1853         ++NumInstRemoved;
1854       }
1855     }
1856   }
1857 
1858   return MadeChanges;
1859 }
1860 
run(Function & F,FunctionAnalysisManager & AM)1861 PreservedAnalyses SCCPPass::run(Function &F, FunctionAnalysisManager &AM) {
1862   const DataLayout &DL = F.getParent()->getDataLayout();
1863   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1864   if (!runSCCP(F, DL, &TLI))
1865     return PreservedAnalyses::all();
1866 
1867   auto PA = PreservedAnalyses();
1868   PA.preserve<GlobalsAA>();
1869   PA.preserveSet<CFGAnalyses>();
1870   return PA;
1871 }
1872 
1873 namespace {
1874 
1875 //===--------------------------------------------------------------------===//
1876 //
1877 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1878 /// Sparse Conditional Constant Propagator.
1879 ///
1880 class SCCPLegacyPass : public FunctionPass {
1881 public:
1882   // Pass identification, replacement for typeid
1883   static char ID;
1884 
SCCPLegacyPass()1885   SCCPLegacyPass() : FunctionPass(ID) {
1886     initializeSCCPLegacyPassPass(*PassRegistry::getPassRegistry());
1887   }
1888 
getAnalysisUsage(AnalysisUsage & AU) const1889   void getAnalysisUsage(AnalysisUsage &AU) const override {
1890     AU.addRequired<TargetLibraryInfoWrapperPass>();
1891     AU.addPreserved<GlobalsAAWrapperPass>();
1892     AU.setPreservesCFG();
1893   }
1894 
1895   // runOnFunction - Run the Sparse Conditional Constant Propagation
1896   // algorithm, and return true if the function was modified.
runOnFunction(Function & F)1897   bool runOnFunction(Function &F) override {
1898     if (skipFunction(F))
1899       return false;
1900     const DataLayout &DL = F.getParent()->getDataLayout();
1901     const TargetLibraryInfo *TLI =
1902         &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1903     return runSCCP(F, DL, TLI);
1904   }
1905 };
1906 
1907 } // end anonymous namespace
1908 
1909 char SCCPLegacyPass::ID = 0;
1910 
1911 INITIALIZE_PASS_BEGIN(SCCPLegacyPass, "sccp",
1912                       "Sparse Conditional Constant Propagation", false, false)
INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)1913 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1914 INITIALIZE_PASS_END(SCCPLegacyPass, "sccp",
1915                     "Sparse Conditional Constant Propagation", false, false)
1916 
1917 // createSCCPPass - This is the public interface to this file.
1918 FunctionPass *llvm::createSCCPPass() { return new SCCPLegacyPass(); }
1919 
findReturnsToZap(Function & F,SmallVector<ReturnInst *,8> & ReturnsToZap,SCCPSolver & Solver)1920 static void findReturnsToZap(Function &F,
1921                              SmallVector<ReturnInst *, 8> &ReturnsToZap,
1922                              SCCPSolver &Solver) {
1923   // We can only do this if we know that nothing else can call the function.
1924   if (!Solver.isArgumentTrackedFunction(&F))
1925     return;
1926 
1927   // There is a non-removable musttail call site of this function. Zapping
1928   // returns is not allowed.
1929   if (Solver.isMustTailCallee(&F)) {
1930     LLVM_DEBUG(dbgs() << "Can't zap returns of the function : " << F.getName()
1931                       << " due to present musttail call of it\n");
1932     return;
1933   }
1934 
1935   assert(
1936       all_of(F.users(),
1937              [&Solver](User *U) {
1938                if (isa<Instruction>(U) &&
1939                    !Solver.isBlockExecutable(cast<Instruction>(U)->getParent()))
1940                  return true;
1941                // Non-callsite uses are not impacted by zapping. Also, constant
1942                // uses (like blockaddresses) could stuck around, without being
1943                // used in the underlying IR, meaning we do not have lattice
1944                // values for them.
1945                if (!CallSite(U))
1946                  return true;
1947                if (U->getType()->isStructTy()) {
1948                  return all_of(
1949                      Solver.getStructLatticeValueFor(U),
1950                      [](const LatticeVal &LV) { return !LV.isOverdefined(); });
1951                }
1952                return !Solver.getLatticeValueFor(U).isOverdefined();
1953              }) &&
1954       "We can only zap functions where all live users have a concrete value");
1955 
1956   for (BasicBlock &BB : F) {
1957     if (CallInst *CI = BB.getTerminatingMustTailCall()) {
1958       LLVM_DEBUG(dbgs() << "Can't zap return of the block due to present "
1959                         << "musttail call : " << *CI << "\n");
1960       (void)CI;
1961       return;
1962     }
1963 
1964     if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
1965       if (!isa<UndefValue>(RI->getOperand(0)))
1966         ReturnsToZap.push_back(RI);
1967   }
1968 }
1969 
1970 // Update the condition for terminators that are branching on indeterminate
1971 // values, forcing them to use a specific edge.
forceIndeterminateEdge(Instruction * I,SCCPSolver & Solver)1972 static void forceIndeterminateEdge(Instruction* I, SCCPSolver &Solver) {
1973   BasicBlock *Dest = nullptr;
1974   Constant *C = nullptr;
1975   if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1976     if (!isa<ConstantInt>(SI->getCondition())) {
1977       // Indeterminate switch; use first case value.
1978       Dest = SI->case_begin()->getCaseSuccessor();
1979       C = SI->case_begin()->getCaseValue();
1980     }
1981   } else if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1982     if (!isa<ConstantInt>(BI->getCondition())) {
1983       // Indeterminate branch; use false.
1984       Dest = BI->getSuccessor(1);
1985       C = ConstantInt::getFalse(BI->getContext());
1986     }
1987   } else if (IndirectBrInst *IBR = dyn_cast<IndirectBrInst>(I)) {
1988     if (!isa<BlockAddress>(IBR->getAddress()->stripPointerCasts())) {
1989       // Indeterminate indirectbr; use successor 0.
1990       Dest = IBR->getSuccessor(0);
1991       C = BlockAddress::get(IBR->getSuccessor(0));
1992     }
1993   } else {
1994     llvm_unreachable("Unexpected terminator instruction");
1995   }
1996   if (C) {
1997     assert(Solver.isEdgeFeasible(I->getParent(), Dest) &&
1998            "Didn't find feasible edge?");
1999     (void)Dest;
2000 
2001     I->setOperand(0, C);
2002   }
2003 }
2004 
runIPSCCP(Module & M,const DataLayout & DL,std::function<const TargetLibraryInfo & (Function &)> GetTLI,function_ref<AnalysisResultsForFn (Function &)> getAnalysis)2005 bool llvm::runIPSCCP(
2006     Module &M, const DataLayout &DL,
2007     std::function<const TargetLibraryInfo &(Function &)> GetTLI,
2008     function_ref<AnalysisResultsForFn(Function &)> getAnalysis) {
2009   SCCPSolver Solver(DL, GetTLI);
2010 
2011   // Loop over all functions, marking arguments to those with their addresses
2012   // taken or that are external as overdefined.
2013   for (Function &F : M) {
2014     if (F.isDeclaration())
2015       continue;
2016 
2017     Solver.addAnalysis(F, getAnalysis(F));
2018 
2019     // Determine if we can track the function's return values. If so, add the
2020     // function to the solver's set of return-tracked functions.
2021     if (canTrackReturnsInterprocedurally(&F))
2022       Solver.AddTrackedFunction(&F);
2023 
2024     // Determine if we can track the function's arguments. If so, add the
2025     // function to the solver's set of argument-tracked functions.
2026     if (canTrackArgumentsInterprocedurally(&F)) {
2027       Solver.AddArgumentTrackedFunction(&F);
2028       continue;
2029     }
2030 
2031     // Assume the function is called.
2032     Solver.MarkBlockExecutable(&F.front());
2033 
2034     // Assume nothing about the incoming arguments.
2035     for (Argument &AI : F.args())
2036       Solver.markOverdefined(&AI);
2037   }
2038 
2039   // Determine if we can track any of the module's global variables. If so, add
2040   // the global variables we can track to the solver's set of tracked global
2041   // variables.
2042   for (GlobalVariable &G : M.globals()) {
2043     G.removeDeadConstantUsers();
2044     if (canTrackGlobalVariableInterprocedurally(&G))
2045       Solver.TrackValueOfGlobalVariable(&G);
2046   }
2047 
2048   // Solve for constants.
2049   bool ResolvedUndefs = true;
2050   Solver.Solve();
2051   while (ResolvedUndefs) {
2052     LLVM_DEBUG(dbgs() << "RESOLVING UNDEFS\n");
2053     ResolvedUndefs = false;
2054     for (Function &F : M)
2055       if (Solver.ResolvedUndefsIn(F)) {
2056         // We run Solve() after we resolved an undef in a function, because
2057         // we might deduce a fact that eliminates an undef in another function.
2058         Solver.Solve();
2059         ResolvedUndefs = true;
2060       }
2061   }
2062 
2063   bool MadeChanges = false;
2064 
2065   // Iterate over all of the instructions in the module, replacing them with
2066   // constants if we have found them to be of constant values.
2067 
2068   for (Function &F : M) {
2069     if (F.isDeclaration())
2070       continue;
2071 
2072     SmallVector<BasicBlock *, 512> BlocksToErase;
2073 
2074     if (Solver.isBlockExecutable(&F.front()))
2075       for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;
2076            ++AI) {
2077         if (!AI->use_empty() && tryToReplaceWithConstant(Solver, &*AI)) {
2078           ++IPNumArgsElimed;
2079           continue;
2080         }
2081       }
2082 
2083     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2084       if (!Solver.isBlockExecutable(&*BB)) {
2085         LLVM_DEBUG(dbgs() << "  BasicBlock Dead:" << *BB);
2086         ++NumDeadBlocks;
2087 
2088         MadeChanges = true;
2089 
2090         if (&*BB != &F.front())
2091           BlocksToErase.push_back(&*BB);
2092         continue;
2093       }
2094 
2095       for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
2096         Instruction *Inst = &*BI++;
2097         if (Inst->getType()->isVoidTy())
2098           continue;
2099         if (tryToReplaceWithConstant(Solver, Inst)) {
2100           if (Inst->isSafeToRemove())
2101             Inst->eraseFromParent();
2102           // Hey, we just changed something!
2103           MadeChanges = true;
2104           ++IPNumInstRemoved;
2105         }
2106       }
2107     }
2108 
2109     DomTreeUpdater DTU = Solver.getDTU(F);
2110     // Change dead blocks to unreachable. We do it after replacing constants
2111     // in all executable blocks, because changeToUnreachable may remove PHI
2112     // nodes in executable blocks we found values for. The function's entry
2113     // block is not part of BlocksToErase, so we have to handle it separately.
2114     for (BasicBlock *BB : BlocksToErase) {
2115       NumInstRemoved +=
2116           changeToUnreachable(BB->getFirstNonPHI(), /*UseLLVMTrap=*/false,
2117                               /*PreserveLCSSA=*/false, &DTU);
2118     }
2119     if (!Solver.isBlockExecutable(&F.front()))
2120       NumInstRemoved += changeToUnreachable(F.front().getFirstNonPHI(),
2121                                             /*UseLLVMTrap=*/false,
2122                                             /*PreserveLCSSA=*/false, &DTU);
2123 
2124     // Now that all instructions in the function are constant folded,
2125     // use ConstantFoldTerminator to get rid of in-edges, record DT updates and
2126     // delete dead BBs.
2127     for (BasicBlock *DeadBB : BlocksToErase) {
2128       // If there are any PHI nodes in this successor, drop entries for BB now.
2129       for (Value::user_iterator UI = DeadBB->user_begin(),
2130                                 UE = DeadBB->user_end();
2131            UI != UE;) {
2132         // Grab the user and then increment the iterator early, as the user
2133         // will be deleted. Step past all adjacent uses from the same user.
2134         auto *I = dyn_cast<Instruction>(*UI);
2135         do { ++UI; } while (UI != UE && *UI == I);
2136 
2137         // Ignore blockaddress users; BasicBlock's dtor will handle them.
2138         if (!I) continue;
2139 
2140         // If we have forced an edge for an indeterminate value, then force the
2141         // terminator to fold to that edge.
2142         forceIndeterminateEdge(I, Solver);
2143         BasicBlock *InstBB = I->getParent();
2144         bool Folded = ConstantFoldTerminator(InstBB,
2145                                              /*DeleteDeadConditions=*/false,
2146                                              /*TLI=*/nullptr, &DTU);
2147         assert(Folded &&
2148               "Expect TermInst on constantint or blockaddress to be folded");
2149         (void) Folded;
2150         // If we folded the terminator to an unconditional branch to another
2151         // dead block, replace it with Unreachable, to avoid trying to fold that
2152         // branch again.
2153         BranchInst *BI = cast<BranchInst>(InstBB->getTerminator());
2154         if (BI && BI->isUnconditional() &&
2155             !Solver.isBlockExecutable(BI->getSuccessor(0))) {
2156           InstBB->getTerminator()->eraseFromParent();
2157           new UnreachableInst(InstBB->getContext(), InstBB);
2158         }
2159       }
2160       // Mark dead BB for deletion.
2161       DTU.deleteBB(DeadBB);
2162     }
2163 
2164     for (BasicBlock &BB : F) {
2165       for (BasicBlock::iterator BI = BB.begin(), E = BB.end(); BI != E;) {
2166         Instruction *Inst = &*BI++;
2167         if (Solver.getPredicateInfoFor(Inst)) {
2168           if (auto *II = dyn_cast<IntrinsicInst>(Inst)) {
2169             if (II->getIntrinsicID() == Intrinsic::ssa_copy) {
2170               Value *Op = II->getOperand(0);
2171               Inst->replaceAllUsesWith(Op);
2172               Inst->eraseFromParent();
2173             }
2174           }
2175         }
2176       }
2177     }
2178   }
2179 
2180   // If we inferred constant or undef return values for a function, we replaced
2181   // all call uses with the inferred value.  This means we don't need to bother
2182   // actually returning anything from the function.  Replace all return
2183   // instructions with return undef.
2184   //
2185   // Do this in two stages: first identify the functions we should process, then
2186   // actually zap their returns.  This is important because we can only do this
2187   // if the address of the function isn't taken.  In cases where a return is the
2188   // last use of a function, the order of processing functions would affect
2189   // whether other functions are optimizable.
2190   SmallVector<ReturnInst*, 8> ReturnsToZap;
2191 
2192   const MapVector<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
2193   for (const auto &I : RV) {
2194     Function *F = I.first;
2195     if (I.second.isOverdefined() || F->getReturnType()->isVoidTy())
2196       continue;
2197     findReturnsToZap(*F, ReturnsToZap, Solver);
2198   }
2199 
2200   for (auto F : Solver.getMRVFunctionsTracked()) {
2201     assert(F->getReturnType()->isStructTy() &&
2202            "The return type should be a struct");
2203     StructType *STy = cast<StructType>(F->getReturnType());
2204     if (Solver.isStructLatticeConstant(F, STy))
2205       findReturnsToZap(*F, ReturnsToZap, Solver);
2206   }
2207 
2208   // Zap all returns which we've identified as zap to change.
2209   for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
2210     Function *F = ReturnsToZap[i]->getParent()->getParent();
2211     ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
2212   }
2213 
2214   // If we inferred constant or undef values for globals variables, we can
2215   // delete the global and any stores that remain to it.
2216   const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
2217   for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
2218          E = TG.end(); I != E; ++I) {
2219     GlobalVariable *GV = I->first;
2220     assert(!I->second.isOverdefined() &&
2221            "Overdefined values should have been taken out of the map!");
2222     LLVM_DEBUG(dbgs() << "Found that GV '" << GV->getName()
2223                       << "' is constant!\n");
2224     while (!GV->use_empty()) {
2225       StoreInst *SI = cast<StoreInst>(GV->user_back());
2226       SI->eraseFromParent();
2227     }
2228     M.getGlobalList().erase(GV);
2229     ++IPNumGlobalConst;
2230   }
2231 
2232   return MadeChanges;
2233 }
2234