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