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