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