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