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