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