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