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