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