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