1 //===- SCCPSolver.cpp - SCCP Utility --------------------------- *- C++ -*-===//
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 // \file
10 // This file implements the Sparse Conditional Constant Propagation (SCCP)
11 // utility.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Transforms/Utils/SCCPSolver.h"
16 #include "llvm/Analysis/ConstantFolding.h"
17 #include "llvm/Analysis/InstructionSimplify.h"
18 #include "llvm/Analysis/ValueLattice.h"
19 #include "llvm/IR/InstVisitor.h"
20 #include "llvm/Support/Casting.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include <cassert>
25 #include <utility>
26 #include <vector>
27 
28 using namespace llvm;
29 
30 #define DEBUG_TYPE "sccp"
31 
32 // The maximum number of range extensions allowed for operations requiring
33 // widening.
34 static const unsigned MaxNumRangeExtensions = 10;
35 
36 /// Returns MergeOptions with MaxWidenSteps set to MaxNumRangeExtensions.
37 static ValueLatticeElement::MergeOptions getMaxWidenStepsOpts() {
38   return ValueLatticeElement::MergeOptions().setMaxWidenSteps(
39       MaxNumRangeExtensions);
40 }
41 
42 namespace {
43 
44 // Helper to check if \p LV is either a constant or a constant
45 // range with a single element. This should cover exactly the same cases as the
46 // old ValueLatticeElement::isConstant() and is intended to be used in the
47 // transition to ValueLatticeElement.
48 bool isConstant(const ValueLatticeElement &LV) {
49   return LV.isConstant() ||
50          (LV.isConstantRange() && LV.getConstantRange().isSingleElement());
51 }
52 
53 // Helper to check if \p LV is either overdefined or a constant range with more
54 // than a single element. This should cover exactly the same cases as the old
55 // ValueLatticeElement::isOverdefined() and is intended to be used in the
56 // transition to ValueLatticeElement.
57 bool isOverdefined(const ValueLatticeElement &LV) {
58   return !LV.isUnknownOrUndef() && !isConstant(LV);
59 }
60 
61 } // namespace
62 
63 namespace llvm {
64 
65 /// Helper class for SCCPSolver. This implements the instruction visitor and
66 /// holds all the state.
67 class SCCPInstVisitor : public InstVisitor<SCCPInstVisitor> {
68   const DataLayout &DL;
69   std::function<const TargetLibraryInfo &(Function &)> GetTLI;
70   SmallPtrSet<BasicBlock *, 8> BBExecutable; // The BBs that are executable.
71   DenseMap<Value *, ValueLatticeElement>
72       ValueState; // The state each value is in.
73 
74   /// StructValueState - This maintains ValueState for values that have
75   /// StructType, for example for formal arguments, calls, insertelement, etc.
76   DenseMap<std::pair<Value *, unsigned>, ValueLatticeElement> StructValueState;
77 
78   /// GlobalValue - If we are tracking any values for the contents of a global
79   /// variable, we keep a mapping from the constant accessor to the element of
80   /// the global, to the currently known value.  If the value becomes
81   /// overdefined, it's entry is simply removed from this map.
82   DenseMap<GlobalVariable *, ValueLatticeElement> TrackedGlobals;
83 
84   /// TrackedRetVals - If we are tracking arguments into and the return
85   /// value out of a function, it will have an entry in this map, indicating
86   /// what the known return value for the function is.
87   MapVector<Function *, ValueLatticeElement> TrackedRetVals;
88 
89   /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
90   /// that return multiple values.
91   MapVector<std::pair<Function *, unsigned>, ValueLatticeElement>
92       TrackedMultipleRetVals;
93 
94   /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
95   /// represented here for efficient lookup.
96   SmallPtrSet<Function *, 16> MRVFunctionsTracked;
97 
98   /// A list of functions whose return cannot be modified.
99   SmallPtrSet<Function *, 16> MustPreserveReturnsInFunctions;
100 
101   /// TrackingIncomingArguments - This is the set of functions for whose
102   /// arguments we make optimistic assumptions about and try to prove as
103   /// constants.
104   SmallPtrSet<Function *, 16> TrackingIncomingArguments;
105 
106   /// The reason for two worklists is that overdefined is the lowest state
107   /// on the lattice, and moving things to overdefined as fast as possible
108   /// makes SCCP converge much faster.
109   ///
110   /// By having a separate worklist, we accomplish this because everything
111   /// possibly overdefined will become overdefined at the soonest possible
112   /// point.
113   SmallVector<Value *, 64> OverdefinedInstWorkList;
114   SmallVector<Value *, 64> InstWorkList;
115 
116   // The BasicBlock work list
117   SmallVector<BasicBlock *, 64> BBWorkList;
118 
119   /// KnownFeasibleEdges - Entries in this set are edges which have already had
120   /// PHI nodes retriggered.
121   using Edge = std::pair<BasicBlock *, BasicBlock *>;
122   DenseSet<Edge> KnownFeasibleEdges;
123 
124   DenseMap<Function *, AnalysisResultsForFn> AnalysisResults;
125   DenseMap<Value *, SmallPtrSet<User *, 2>> AdditionalUsers;
126 
127   LLVMContext &Ctx;
128 
129 private:
130   ConstantInt *getConstantInt(const ValueLatticeElement &IV) const {
131     return dyn_cast_or_null<ConstantInt>(getConstant(IV));
132   }
133 
134   // pushToWorkList - Helper for markConstant/markOverdefined
135   void pushToWorkList(ValueLatticeElement &IV, Value *V);
136 
137   // Helper to push \p V to the worklist, after updating it to \p IV. Also
138   // prints a debug message with the updated value.
139   void pushToWorkListMsg(ValueLatticeElement &IV, Value *V);
140 
141   // markConstant - Make a value be marked as "constant".  If the value
142   // is not already a constant, add it to the instruction work list so that
143   // the users of the instruction are updated later.
144   bool markConstant(ValueLatticeElement &IV, Value *V, Constant *C,
145                     bool MayIncludeUndef = false);
146 
147   bool markConstant(Value *V, Constant *C) {
148     assert(!V->getType()->isStructTy() && "structs should use mergeInValue");
149     return markConstant(ValueState[V], V, C);
150   }
151 
152   // markOverdefined - Make a value be marked as "overdefined". If the
153   // value is not already overdefined, add it to the overdefined instruction
154   // work list so that the users of the instruction are updated later.
155   bool markOverdefined(ValueLatticeElement &IV, Value *V);
156 
157   /// Merge \p MergeWithV into \p IV and push \p V to the worklist, if \p IV
158   /// changes.
159   bool mergeInValue(ValueLatticeElement &IV, Value *V,
160                     ValueLatticeElement MergeWithV,
161                     ValueLatticeElement::MergeOptions Opts = {
162                         /*MayIncludeUndef=*/false, /*CheckWiden=*/false});
163 
164   bool mergeInValue(Value *V, ValueLatticeElement MergeWithV,
165                     ValueLatticeElement::MergeOptions Opts = {
166                         /*MayIncludeUndef=*/false, /*CheckWiden=*/false}) {
167     assert(!V->getType()->isStructTy() &&
168            "non-structs should use markConstant");
169     return mergeInValue(ValueState[V], V, MergeWithV, Opts);
170   }
171 
172   /// getValueState - Return the ValueLatticeElement object that corresponds to
173   /// the value.  This function handles the case when the value hasn't been seen
174   /// yet by properly seeding constants etc.
175   ValueLatticeElement &getValueState(Value *V) {
176     assert(!V->getType()->isStructTy() && "Should use getStructValueState");
177 
178     auto I = ValueState.insert(std::make_pair(V, ValueLatticeElement()));
179     ValueLatticeElement &LV = I.first->second;
180 
181     if (!I.second)
182       return LV; // Common case, already in the map.
183 
184     if (auto *C = dyn_cast<Constant>(V))
185       LV.markConstant(C); // Constants are constant
186 
187     // All others are unknown by default.
188     return LV;
189   }
190 
191   /// getStructValueState - Return the ValueLatticeElement object that
192   /// corresponds to the value/field pair.  This function handles the case when
193   /// the value hasn't been seen yet by properly seeding constants etc.
194   ValueLatticeElement &getStructValueState(Value *V, unsigned i) {
195     assert(V->getType()->isStructTy() && "Should use getValueState");
196     assert(i < cast<StructType>(V->getType())->getNumElements() &&
197            "Invalid element #");
198 
199     auto I = StructValueState.insert(
200         std::make_pair(std::make_pair(V, i), ValueLatticeElement()));
201     ValueLatticeElement &LV = I.first->second;
202 
203     if (!I.second)
204       return LV; // Common case, already in the map.
205 
206     if (auto *C = dyn_cast<Constant>(V)) {
207       Constant *Elt = C->getAggregateElement(i);
208 
209       if (!Elt)
210         LV.markOverdefined(); // Unknown sort of constant.
211       else
212         LV.markConstant(Elt); // Constants are constant.
213     }
214 
215     // All others are underdefined by default.
216     return LV;
217   }
218 
219   /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
220   /// work list if it is not already executable.
221   bool markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest);
222 
223   // getFeasibleSuccessors - Return a vector of booleans to indicate which
224   // successors are reachable from a given terminator instruction.
225   void getFeasibleSuccessors(Instruction &TI, SmallVectorImpl<bool> &Succs);
226 
227   // OperandChangedState - This method is invoked on all of the users of an
228   // instruction that was just changed state somehow.  Based on this
229   // information, we need to update the specified user of this instruction.
230   void operandChangedState(Instruction *I) {
231     if (BBExecutable.count(I->getParent())) // Inst is executable?
232       visit(*I);
233   }
234 
235   // Add U as additional user of V.
236   void addAdditionalUser(Value *V, User *U) {
237     auto Iter = AdditionalUsers.insert({V, {}});
238     Iter.first->second.insert(U);
239   }
240 
241   // Mark I's users as changed, including AdditionalUsers.
242   void markUsersAsChanged(Value *I) {
243     // Functions include their arguments in the use-list. Changed function
244     // values mean that the result of the function changed. We only need to
245     // update the call sites with the new function result and do not have to
246     // propagate the call arguments.
247     if (isa<Function>(I)) {
248       for (User *U : I->users()) {
249         if (auto *CB = dyn_cast<CallBase>(U))
250           handleCallResult(*CB);
251       }
252     } else {
253       for (User *U : I->users())
254         if (auto *UI = dyn_cast<Instruction>(U))
255           operandChangedState(UI);
256     }
257 
258     auto Iter = AdditionalUsers.find(I);
259     if (Iter != AdditionalUsers.end()) {
260       // Copy additional users before notifying them of changes, because new
261       // users may be added, potentially invalidating the iterator.
262       SmallVector<Instruction *, 2> ToNotify;
263       for (User *U : Iter->second)
264         if (auto *UI = dyn_cast<Instruction>(U))
265           ToNotify.push_back(UI);
266       for (Instruction *UI : ToNotify)
267         operandChangedState(UI);
268     }
269   }
270   void handleCallOverdefined(CallBase &CB);
271   void handleCallResult(CallBase &CB);
272   void handleCallArguments(CallBase &CB);
273 
274 private:
275   friend class InstVisitor<SCCPInstVisitor>;
276 
277   // visit implementations - Something changed in this instruction.  Either an
278   // operand made a transition, or the instruction is newly executable.  Change
279   // the value type of I to reflect these changes if appropriate.
280   void visitPHINode(PHINode &I);
281 
282   // Terminators
283 
284   void visitReturnInst(ReturnInst &I);
285   void visitTerminator(Instruction &TI);
286 
287   void visitCastInst(CastInst &I);
288   void visitSelectInst(SelectInst &I);
289   void visitUnaryOperator(Instruction &I);
290   void visitBinaryOperator(Instruction &I);
291   void visitCmpInst(CmpInst &I);
292   void visitExtractValueInst(ExtractValueInst &EVI);
293   void visitInsertValueInst(InsertValueInst &IVI);
294 
295   void visitCatchSwitchInst(CatchSwitchInst &CPI) {
296     markOverdefined(&CPI);
297     visitTerminator(CPI);
298   }
299 
300   // Instructions that cannot be folded away.
301 
302   void visitStoreInst(StoreInst &I);
303   void visitLoadInst(LoadInst &I);
304   void visitGetElementPtrInst(GetElementPtrInst &I);
305 
306   void visitInvokeInst(InvokeInst &II) {
307     visitCallBase(II);
308     visitTerminator(II);
309   }
310 
311   void visitCallBrInst(CallBrInst &CBI) {
312     visitCallBase(CBI);
313     visitTerminator(CBI);
314   }
315 
316   void visitCallBase(CallBase &CB);
317   void visitResumeInst(ResumeInst &I) { /*returns void*/
318   }
319   void visitUnreachableInst(UnreachableInst &I) { /*returns void*/
320   }
321   void visitFenceInst(FenceInst &I) { /*returns void*/
322   }
323 
324   void visitInstruction(Instruction &I);
325 
326 public:
327   void addAnalysis(Function &F, AnalysisResultsForFn A) {
328     AnalysisResults.insert({&F, std::move(A)});
329   }
330 
331   void visitCallInst(CallInst &I) { visitCallBase(I); }
332 
333   bool markBlockExecutable(BasicBlock *BB);
334 
335   const PredicateBase *getPredicateInfoFor(Instruction *I) {
336     auto A = AnalysisResults.find(I->getParent()->getParent());
337     if (A == AnalysisResults.end())
338       return nullptr;
339     return A->second.PredInfo->getPredicateInfoFor(I);
340   }
341 
342   DomTreeUpdater getDTU(Function &F) {
343     auto A = AnalysisResults.find(&F);
344     assert(A != AnalysisResults.end() && "Need analysis results for function.");
345     return {A->second.DT, A->second.PDT, DomTreeUpdater::UpdateStrategy::Lazy};
346   }
347 
348   SCCPInstVisitor(const DataLayout &DL,
349                   std::function<const TargetLibraryInfo &(Function &)> GetTLI,
350                   LLVMContext &Ctx)
351       : DL(DL), GetTLI(GetTLI), Ctx(Ctx) {}
352 
353   void trackValueOfGlobalVariable(GlobalVariable *GV) {
354     // We only track the contents of scalar globals.
355     if (GV->getValueType()->isSingleValueType()) {
356       ValueLatticeElement &IV = TrackedGlobals[GV];
357       IV.markConstant(GV->getInitializer());
358     }
359   }
360 
361   void addTrackedFunction(Function *F) {
362     // Add an entry, F -> undef.
363     if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
364       MRVFunctionsTracked.insert(F);
365       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
366         TrackedMultipleRetVals.insert(
367             std::make_pair(std::make_pair(F, i), ValueLatticeElement()));
368     } else if (!F->getReturnType()->isVoidTy())
369       TrackedRetVals.insert(std::make_pair(F, ValueLatticeElement()));
370   }
371 
372   void addToMustPreserveReturnsInFunctions(Function *F) {
373     MustPreserveReturnsInFunctions.insert(F);
374   }
375 
376   bool mustPreserveReturn(Function *F) {
377     return MustPreserveReturnsInFunctions.count(F);
378   }
379 
380   void addArgumentTrackedFunction(Function *F) {
381     TrackingIncomingArguments.insert(F);
382   }
383 
384   bool isArgumentTrackedFunction(Function *F) {
385     return TrackingIncomingArguments.count(F);
386   }
387 
388   void solve();
389 
390   bool resolvedUndefsIn(Function &F);
391 
392   bool isBlockExecutable(BasicBlock *BB) const {
393     return BBExecutable.count(BB);
394   }
395 
396   bool isEdgeFeasible(BasicBlock *From, BasicBlock *To) const;
397 
398   std::vector<ValueLatticeElement> getStructLatticeValueFor(Value *V) const {
399     std::vector<ValueLatticeElement> StructValues;
400     auto *STy = dyn_cast<StructType>(V->getType());
401     assert(STy && "getStructLatticeValueFor() can be called only on structs");
402     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
403       auto I = StructValueState.find(std::make_pair(V, i));
404       assert(I != StructValueState.end() && "Value not in valuemap!");
405       StructValues.push_back(I->second);
406     }
407     return StructValues;
408   }
409 
410   void removeLatticeValueFor(Value *V) { ValueState.erase(V); }
411 
412   const ValueLatticeElement &getLatticeValueFor(Value *V) const {
413     assert(!V->getType()->isStructTy() &&
414            "Should use getStructLatticeValueFor");
415     DenseMap<Value *, ValueLatticeElement>::const_iterator I =
416         ValueState.find(V);
417     assert(I != ValueState.end() &&
418            "V not found in ValueState nor Paramstate map!");
419     return I->second;
420   }
421 
422   const MapVector<Function *, ValueLatticeElement> &getTrackedRetVals() {
423     return TrackedRetVals;
424   }
425 
426   const DenseMap<GlobalVariable *, ValueLatticeElement> &getTrackedGlobals() {
427     return TrackedGlobals;
428   }
429 
430   const SmallPtrSet<Function *, 16> getMRVFunctionsTracked() {
431     return MRVFunctionsTracked;
432   }
433 
434   void markOverdefined(Value *V) {
435     if (auto *STy = dyn_cast<StructType>(V->getType()))
436       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
437         markOverdefined(getStructValueState(V, i), V);
438     else
439       markOverdefined(ValueState[V], V);
440   }
441 
442   bool isStructLatticeConstant(Function *F, StructType *STy);
443 
444   Constant *getConstant(const ValueLatticeElement &LV) const;
445 
446   SmallPtrSetImpl<Function *> &getArgumentTrackedFunctions() {
447     return TrackingIncomingArguments;
448   }
449 
450   void markArgInFuncSpecialization(Function *F,
451                                    const SmallVectorImpl<ArgInfo> &Args);
452 
453   void markFunctionUnreachable(Function *F) {
454     for (auto &BB : *F)
455       BBExecutable.erase(&BB);
456   }
457 };
458 
459 } // namespace llvm
460 
461 bool SCCPInstVisitor::markBlockExecutable(BasicBlock *BB) {
462   if (!BBExecutable.insert(BB).second)
463     return false;
464   LLVM_DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << '\n');
465   BBWorkList.push_back(BB); // Add the block to the work list!
466   return true;
467 }
468 
469 void SCCPInstVisitor::pushToWorkList(ValueLatticeElement &IV, Value *V) {
470   if (IV.isOverdefined())
471     return OverdefinedInstWorkList.push_back(V);
472   InstWorkList.push_back(V);
473 }
474 
475 void SCCPInstVisitor::pushToWorkListMsg(ValueLatticeElement &IV, Value *V) {
476   LLVM_DEBUG(dbgs() << "updated " << IV << ": " << *V << '\n');
477   pushToWorkList(IV, V);
478 }
479 
480 bool SCCPInstVisitor::markConstant(ValueLatticeElement &IV, Value *V,
481                                    Constant *C, bool MayIncludeUndef) {
482   if (!IV.markConstant(C, MayIncludeUndef))
483     return false;
484   LLVM_DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
485   pushToWorkList(IV, V);
486   return true;
487 }
488 
489 bool SCCPInstVisitor::markOverdefined(ValueLatticeElement &IV, Value *V) {
490   if (!IV.markOverdefined())
491     return false;
492 
493   LLVM_DEBUG(dbgs() << "markOverdefined: ";
494              if (auto *F = dyn_cast<Function>(V)) dbgs()
495              << "Function '" << F->getName() << "'\n";
496              else dbgs() << *V << '\n');
497   // Only instructions go on the work list
498   pushToWorkList(IV, V);
499   return true;
500 }
501 
502 bool SCCPInstVisitor::isStructLatticeConstant(Function *F, StructType *STy) {
503   for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
504     const auto &It = TrackedMultipleRetVals.find(std::make_pair(F, i));
505     assert(It != TrackedMultipleRetVals.end());
506     ValueLatticeElement LV = It->second;
507     if (!isConstant(LV))
508       return false;
509   }
510   return true;
511 }
512 
513 Constant *SCCPInstVisitor::getConstant(const ValueLatticeElement &LV) const {
514   if (LV.isConstant())
515     return LV.getConstant();
516 
517   if (LV.isConstantRange()) {
518     const auto &CR = LV.getConstantRange();
519     if (CR.getSingleElement())
520       return ConstantInt::get(Ctx, *CR.getSingleElement());
521   }
522   return nullptr;
523 }
524 
525 void SCCPInstVisitor::markArgInFuncSpecialization(
526     Function *F, const SmallVectorImpl<ArgInfo> &Args) {
527   assert(!Args.empty() && "Specialization without arguments");
528   assert(F->arg_size() == Args[0].Formal->getParent()->arg_size() &&
529          "Functions should have the same number of arguments");
530 
531   auto Iter = Args.begin();
532   Argument *NewArg = F->arg_begin();
533   Argument *OldArg = Args[0].Formal->getParent()->arg_begin();
534   for (auto End = F->arg_end(); NewArg != End; ++NewArg, ++OldArg) {
535 
536     LLVM_DEBUG(dbgs() << "SCCP: Marking argument "
537                       << NewArg->getNameOrAsOperand() << "\n");
538 
539     if (Iter != Args.end() && OldArg == Iter->Formal) {
540       // Mark the argument constants in the new function.
541       markConstant(NewArg, Iter->Actual);
542       ++Iter;
543     } else if (ValueState.count(OldArg)) {
544       // For the remaining arguments in the new function, copy the lattice state
545       // over from the old function.
546       //
547       // Note: This previously looked like this:
548       // ValueState[NewArg] = ValueState[OldArg];
549       // This is incorrect because the DenseMap class may resize the underlying
550       // memory when inserting `NewArg`, which will invalidate the reference to
551       // `OldArg`. Instead, we make sure `NewArg` exists before setting it.
552       auto &NewValue = ValueState[NewArg];
553       NewValue = ValueState[OldArg];
554       pushToWorkList(NewValue, NewArg);
555     }
556   }
557 }
558 
559 void SCCPInstVisitor::visitInstruction(Instruction &I) {
560   // All the instructions we don't do any special handling for just
561   // go to overdefined.
562   LLVM_DEBUG(dbgs() << "SCCP: Don't know how to handle: " << I << '\n');
563   markOverdefined(&I);
564 }
565 
566 bool SCCPInstVisitor::mergeInValue(ValueLatticeElement &IV, Value *V,
567                                    ValueLatticeElement MergeWithV,
568                                    ValueLatticeElement::MergeOptions Opts) {
569   if (IV.mergeIn(MergeWithV, Opts)) {
570     pushToWorkList(IV, V);
571     LLVM_DEBUG(dbgs() << "Merged " << MergeWithV << " into " << *V << " : "
572                       << IV << "\n");
573     return true;
574   }
575   return false;
576 }
577 
578 bool SCCPInstVisitor::markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
579   if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
580     return false; // This edge is already known to be executable!
581 
582   if (!markBlockExecutable(Dest)) {
583     // If the destination is already executable, we just made an *edge*
584     // feasible that wasn't before.  Revisit the PHI nodes in the block
585     // because they have potentially new operands.
586     LLVM_DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
587                       << " -> " << Dest->getName() << '\n');
588 
589     for (PHINode &PN : Dest->phis())
590       visitPHINode(PN);
591   }
592   return true;
593 }
594 
595 // getFeasibleSuccessors - Return a vector of booleans to indicate which
596 // successors are reachable from a given terminator instruction.
597 void SCCPInstVisitor::getFeasibleSuccessors(Instruction &TI,
598                                             SmallVectorImpl<bool> &Succs) {
599   Succs.resize(TI.getNumSuccessors());
600   if (auto *BI = dyn_cast<BranchInst>(&TI)) {
601     if (BI->isUnconditional()) {
602       Succs[0] = true;
603       return;
604     }
605 
606     ValueLatticeElement BCValue = getValueState(BI->getCondition());
607     ConstantInt *CI = getConstantInt(BCValue);
608     if (!CI) {
609       // Overdefined condition variables, and branches on unfoldable constant
610       // conditions, mean the branch could go either way.
611       if (!BCValue.isUnknownOrUndef())
612         Succs[0] = Succs[1] = true;
613       return;
614     }
615 
616     // Constant condition variables mean the branch can only go a single way.
617     Succs[CI->isZero()] = true;
618     return;
619   }
620 
621   // Unwinding instructions successors are always executable.
622   if (TI.isExceptionalTerminator()) {
623     Succs.assign(TI.getNumSuccessors(), true);
624     return;
625   }
626 
627   if (auto *SI = dyn_cast<SwitchInst>(&TI)) {
628     if (!SI->getNumCases()) {
629       Succs[0] = true;
630       return;
631     }
632     const ValueLatticeElement &SCValue = getValueState(SI->getCondition());
633     if (ConstantInt *CI = getConstantInt(SCValue)) {
634       Succs[SI->findCaseValue(CI)->getSuccessorIndex()] = true;
635       return;
636     }
637 
638     // TODO: Switch on undef is UB. Stop passing false once the rest of LLVM
639     // is ready.
640     if (SCValue.isConstantRange(/*UndefAllowed=*/false)) {
641       const ConstantRange &Range = SCValue.getConstantRange();
642       for (const auto &Case : SI->cases()) {
643         const APInt &CaseValue = Case.getCaseValue()->getValue();
644         if (Range.contains(CaseValue))
645           Succs[Case.getSuccessorIndex()] = true;
646       }
647 
648       // TODO: Determine whether default case is reachable.
649       Succs[SI->case_default()->getSuccessorIndex()] = true;
650       return;
651     }
652 
653     // Overdefined or unknown condition? All destinations are executable!
654     if (!SCValue.isUnknownOrUndef())
655       Succs.assign(TI.getNumSuccessors(), true);
656     return;
657   }
658 
659   // In case of indirect branch and its address is a blockaddress, we mark
660   // the target as executable.
661   if (auto *IBR = dyn_cast<IndirectBrInst>(&TI)) {
662     // Casts are folded by visitCastInst.
663     ValueLatticeElement IBRValue = getValueState(IBR->getAddress());
664     BlockAddress *Addr = dyn_cast_or_null<BlockAddress>(getConstant(IBRValue));
665     if (!Addr) { // Overdefined or unknown condition?
666       // All destinations are executable!
667       if (!IBRValue.isUnknownOrUndef())
668         Succs.assign(TI.getNumSuccessors(), true);
669       return;
670     }
671 
672     BasicBlock *T = Addr->getBasicBlock();
673     assert(Addr->getFunction() == T->getParent() &&
674            "Block address of a different function ?");
675     for (unsigned i = 0; i < IBR->getNumSuccessors(); ++i) {
676       // This is the target.
677       if (IBR->getDestination(i) == T) {
678         Succs[i] = true;
679         return;
680       }
681     }
682 
683     // If we didn't find our destination in the IBR successor list, then we
684     // have undefined behavior. Its ok to assume no successor is executable.
685     return;
686   }
687 
688   // In case of callbr, we pessimistically assume that all successors are
689   // feasible.
690   if (isa<CallBrInst>(&TI)) {
691     Succs.assign(TI.getNumSuccessors(), true);
692     return;
693   }
694 
695   LLVM_DEBUG(dbgs() << "Unknown terminator instruction: " << TI << '\n');
696   llvm_unreachable("SCCP: Don't know how to handle this terminator!");
697 }
698 
699 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
700 // block to the 'To' basic block is currently feasible.
701 bool SCCPInstVisitor::isEdgeFeasible(BasicBlock *From, BasicBlock *To) const {
702   // Check if we've called markEdgeExecutable on the edge yet. (We could
703   // be more aggressive and try to consider edges which haven't been marked
704   // yet, but there isn't any need.)
705   return KnownFeasibleEdges.count(Edge(From, To));
706 }
707 
708 // visit Implementations - Something changed in this instruction, either an
709 // operand made a transition, or the instruction is newly executable.  Change
710 // the value type of I to reflect these changes if appropriate.  This method
711 // makes sure to do the following actions:
712 //
713 // 1. If a phi node merges two constants in, and has conflicting value coming
714 //    from different branches, or if the PHI node merges in an overdefined
715 //    value, then the PHI node becomes overdefined.
716 // 2. If a phi node merges only constants in, and they all agree on value, the
717 //    PHI node becomes a constant value equal to that.
718 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
719 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
720 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
721 // 6. If a conditional branch has a value that is constant, make the selected
722 //    destination executable
723 // 7. If a conditional branch has a value that is overdefined, make all
724 //    successors executable.
725 void SCCPInstVisitor::visitPHINode(PHINode &PN) {
726   // If this PN returns a struct, just mark the result overdefined.
727   // TODO: We could do a lot better than this if code actually uses this.
728   if (PN.getType()->isStructTy())
729     return (void)markOverdefined(&PN);
730 
731   if (getValueState(&PN).isOverdefined())
732     return; // Quick exit
733 
734   // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
735   // and slow us down a lot.  Just mark them overdefined.
736   if (PN.getNumIncomingValues() > 64)
737     return (void)markOverdefined(&PN);
738 
739   unsigned NumActiveIncoming = 0;
740 
741   // Look at all of the executable operands of the PHI node.  If any of them
742   // are overdefined, the PHI becomes overdefined as well.  If they are all
743   // constant, and they agree with each other, the PHI becomes the identical
744   // constant.  If they are constant and don't agree, the PHI is a constant
745   // range. If there are no executable operands, the PHI remains unknown.
746   ValueLatticeElement PhiState = getValueState(&PN);
747   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
748     if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
749       continue;
750 
751     ValueLatticeElement IV = getValueState(PN.getIncomingValue(i));
752     PhiState.mergeIn(IV);
753     NumActiveIncoming++;
754     if (PhiState.isOverdefined())
755       break;
756   }
757 
758   // We allow up to 1 range extension per active incoming value and one
759   // additional extension. Note that we manually adjust the number of range
760   // extensions to match the number of active incoming values. This helps to
761   // limit multiple extensions caused by the same incoming value, if other
762   // incoming values are equal.
763   mergeInValue(&PN, PhiState,
764                ValueLatticeElement::MergeOptions().setMaxWidenSteps(
765                    NumActiveIncoming + 1));
766   ValueLatticeElement &PhiStateRef = getValueState(&PN);
767   PhiStateRef.setNumRangeExtensions(
768       std::max(NumActiveIncoming, PhiStateRef.getNumRangeExtensions()));
769 }
770 
771 void SCCPInstVisitor::visitReturnInst(ReturnInst &I) {
772   if (I.getNumOperands() == 0)
773     return; // ret void
774 
775   Function *F = I.getParent()->getParent();
776   Value *ResultOp = I.getOperand(0);
777 
778   // If we are tracking the return value of this function, merge it in.
779   if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
780     auto TFRVI = TrackedRetVals.find(F);
781     if (TFRVI != TrackedRetVals.end()) {
782       mergeInValue(TFRVI->second, F, getValueState(ResultOp));
783       return;
784     }
785   }
786 
787   // Handle functions that return multiple values.
788   if (!TrackedMultipleRetVals.empty()) {
789     if (auto *STy = dyn_cast<StructType>(ResultOp->getType()))
790       if (MRVFunctionsTracked.count(F))
791         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
792           mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
793                        getStructValueState(ResultOp, i));
794   }
795 }
796 
797 void SCCPInstVisitor::visitTerminator(Instruction &TI) {
798   SmallVector<bool, 16> SuccFeasible;
799   getFeasibleSuccessors(TI, SuccFeasible);
800 
801   BasicBlock *BB = TI.getParent();
802 
803   // Mark all feasible successors executable.
804   for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
805     if (SuccFeasible[i])
806       markEdgeExecutable(BB, TI.getSuccessor(i));
807 }
808 
809 void SCCPInstVisitor::visitCastInst(CastInst &I) {
810   // ResolvedUndefsIn might mark I as overdefined. Bail out, even if we would
811   // discover a concrete value later.
812   if (ValueState[&I].isOverdefined())
813     return;
814 
815   ValueLatticeElement OpSt = getValueState(I.getOperand(0));
816   if (OpSt.isUnknownOrUndef())
817     return;
818 
819   if (Constant *OpC = getConstant(OpSt)) {
820     // Fold the constant as we build.
821     Constant *C = ConstantFoldCastOperand(I.getOpcode(), OpC, I.getType(), DL);
822     markConstant(&I, C);
823   } else if (I.getDestTy()->isIntegerTy()) {
824     auto &LV = getValueState(&I);
825     ConstantRange OpRange =
826         OpSt.isConstantRange()
827             ? OpSt.getConstantRange()
828             : ConstantRange::getFull(
829                   I.getOperand(0)->getType()->getScalarSizeInBits());
830 
831     Type *DestTy = I.getDestTy();
832     // Vectors where all elements have the same known constant range are treated
833     // as a single constant range in the lattice. When bitcasting such vectors,
834     // there is a mis-match between the width of the lattice value (single
835     // constant range) and the original operands (vector). Go to overdefined in
836     // that case.
837     if (I.getOpcode() == Instruction::BitCast &&
838         I.getOperand(0)->getType()->isVectorTy() &&
839         OpRange.getBitWidth() < DL.getTypeSizeInBits(DestTy))
840       return (void)markOverdefined(&I);
841 
842     ConstantRange Res =
843         OpRange.castOp(I.getOpcode(), DL.getTypeSizeInBits(DestTy));
844     mergeInValue(LV, &I, ValueLatticeElement::getRange(Res));
845   } else
846     markOverdefined(&I);
847 }
848 
849 void SCCPInstVisitor::visitExtractValueInst(ExtractValueInst &EVI) {
850   // If this returns a struct, mark all elements over defined, we don't track
851   // structs in structs.
852   if (EVI.getType()->isStructTy())
853     return (void)markOverdefined(&EVI);
854 
855   // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would
856   // discover a concrete value later.
857   if (ValueState[&EVI].isOverdefined())
858     return (void)markOverdefined(&EVI);
859 
860   // If this is extracting from more than one level of struct, we don't know.
861   if (EVI.getNumIndices() != 1)
862     return (void)markOverdefined(&EVI);
863 
864   Value *AggVal = EVI.getAggregateOperand();
865   if (AggVal->getType()->isStructTy()) {
866     unsigned i = *EVI.idx_begin();
867     ValueLatticeElement EltVal = getStructValueState(AggVal, i);
868     mergeInValue(getValueState(&EVI), &EVI, EltVal);
869   } else {
870     // Otherwise, must be extracting from an array.
871     return (void)markOverdefined(&EVI);
872   }
873 }
874 
875 void SCCPInstVisitor::visitInsertValueInst(InsertValueInst &IVI) {
876   auto *STy = dyn_cast<StructType>(IVI.getType());
877   if (!STy)
878     return (void)markOverdefined(&IVI);
879 
880   // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would
881   // discover a concrete value later.
882   if (isOverdefined(ValueState[&IVI]))
883     return (void)markOverdefined(&IVI);
884 
885   // If this has more than one index, we can't handle it, drive all results to
886   // undef.
887   if (IVI.getNumIndices() != 1)
888     return (void)markOverdefined(&IVI);
889 
890   Value *Aggr = IVI.getAggregateOperand();
891   unsigned Idx = *IVI.idx_begin();
892 
893   // Compute the result based on what we're inserting.
894   for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
895     // This passes through all values that aren't the inserted element.
896     if (i != Idx) {
897       ValueLatticeElement EltVal = getStructValueState(Aggr, i);
898       mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
899       continue;
900     }
901 
902     Value *Val = IVI.getInsertedValueOperand();
903     if (Val->getType()->isStructTy())
904       // We don't track structs in structs.
905       markOverdefined(getStructValueState(&IVI, i), &IVI);
906     else {
907       ValueLatticeElement InVal = getValueState(Val);
908       mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
909     }
910   }
911 }
912 
913 void SCCPInstVisitor::visitSelectInst(SelectInst &I) {
914   // If this select returns a struct, just mark the result overdefined.
915   // TODO: We could do a lot better than this if code actually uses this.
916   if (I.getType()->isStructTy())
917     return (void)markOverdefined(&I);
918 
919   // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would
920   // discover a concrete value later.
921   if (ValueState[&I].isOverdefined())
922     return (void)markOverdefined(&I);
923 
924   ValueLatticeElement CondValue = getValueState(I.getCondition());
925   if (CondValue.isUnknownOrUndef())
926     return;
927 
928   if (ConstantInt *CondCB = getConstantInt(CondValue)) {
929     Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
930     mergeInValue(&I, getValueState(OpVal));
931     return;
932   }
933 
934   // Otherwise, the condition is overdefined or a constant we can't evaluate.
935   // See if we can produce something better than overdefined based on the T/F
936   // value.
937   ValueLatticeElement TVal = getValueState(I.getTrueValue());
938   ValueLatticeElement FVal = getValueState(I.getFalseValue());
939 
940   bool Changed = ValueState[&I].mergeIn(TVal);
941   Changed |= ValueState[&I].mergeIn(FVal);
942   if (Changed)
943     pushToWorkListMsg(ValueState[&I], &I);
944 }
945 
946 // Handle Unary Operators.
947 void SCCPInstVisitor::visitUnaryOperator(Instruction &I) {
948   ValueLatticeElement V0State = getValueState(I.getOperand(0));
949 
950   ValueLatticeElement &IV = ValueState[&I];
951   // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would
952   // discover a concrete value later.
953   if (isOverdefined(IV))
954     return (void)markOverdefined(&I);
955 
956   // If something is unknown/undef, wait for it to resolve.
957   if (V0State.isUnknownOrUndef())
958     return;
959 
960   if (isConstant(V0State))
961     if (Constant *C = ConstantFoldUnaryOpOperand(I.getOpcode(),
962                                                  getConstant(V0State), DL))
963       return (void)markConstant(IV, &I, C);
964 
965   markOverdefined(&I);
966 }
967 
968 // Handle Binary Operators.
969 void SCCPInstVisitor::visitBinaryOperator(Instruction &I) {
970   ValueLatticeElement V1State = getValueState(I.getOperand(0));
971   ValueLatticeElement V2State = getValueState(I.getOperand(1));
972 
973   ValueLatticeElement &IV = ValueState[&I];
974   if (IV.isOverdefined())
975     return;
976 
977   // If something is undef, wait for it to resolve.
978   if (V1State.isUnknownOrUndef() || V2State.isUnknownOrUndef())
979     return;
980 
981   if (V1State.isOverdefined() && V2State.isOverdefined())
982     return (void)markOverdefined(&I);
983 
984   // If either of the operands is a constant, try to fold it to a constant.
985   // TODO: Use information from notconstant better.
986   if ((V1State.isConstant() || V2State.isConstant())) {
987     Value *V1 = isConstant(V1State) ? getConstant(V1State) : I.getOperand(0);
988     Value *V2 = isConstant(V2State) ? getConstant(V2State) : I.getOperand(1);
989     Value *R = simplifyBinOp(I.getOpcode(), V1, V2, SimplifyQuery(DL));
990     auto *C = dyn_cast_or_null<Constant>(R);
991     if (C) {
992       // Conservatively assume that the result may be based on operands that may
993       // be undef. Note that we use mergeInValue to combine the constant with
994       // the existing lattice value for I, as different constants might be found
995       // after one of the operands go to overdefined, e.g. due to one operand
996       // being a special floating value.
997       ValueLatticeElement NewV;
998       NewV.markConstant(C, /*MayIncludeUndef=*/true);
999       return (void)mergeInValue(&I, NewV);
1000     }
1001   }
1002 
1003   // Only use ranges for binary operators on integers.
1004   if (!I.getType()->isIntegerTy())
1005     return markOverdefined(&I);
1006 
1007   // Try to simplify to a constant range.
1008   ConstantRange A = ConstantRange::getFull(I.getType()->getScalarSizeInBits());
1009   ConstantRange B = ConstantRange::getFull(I.getType()->getScalarSizeInBits());
1010   if (V1State.isConstantRange())
1011     A = V1State.getConstantRange();
1012   if (V2State.isConstantRange())
1013     B = V2State.getConstantRange();
1014 
1015   ConstantRange R = A.binaryOp(cast<BinaryOperator>(&I)->getOpcode(), B);
1016   mergeInValue(&I, ValueLatticeElement::getRange(R));
1017 
1018   // TODO: Currently we do not exploit special values that produce something
1019   // better than overdefined with an overdefined operand for vector or floating
1020   // point types, like and <4 x i32> overdefined, zeroinitializer.
1021 }
1022 
1023 // Handle ICmpInst instruction.
1024 void SCCPInstVisitor::visitCmpInst(CmpInst &I) {
1025   // Do not cache this lookup, getValueState calls later in the function might
1026   // invalidate the reference.
1027   if (isOverdefined(ValueState[&I]))
1028     return (void)markOverdefined(&I);
1029 
1030   Value *Op1 = I.getOperand(0);
1031   Value *Op2 = I.getOperand(1);
1032 
1033   // For parameters, use ParamState which includes constant range info if
1034   // available.
1035   auto V1State = getValueState(Op1);
1036   auto V2State = getValueState(Op2);
1037 
1038   Constant *C = V1State.getCompare(I.getPredicate(), I.getType(), V2State);
1039   if (C) {
1040     // TODO: getCompare() currently has incorrect handling for unknown/undef.
1041     if (isa<UndefValue>(C))
1042       return;
1043     ValueLatticeElement CV;
1044     CV.markConstant(C);
1045     mergeInValue(&I, CV);
1046     return;
1047   }
1048 
1049   // If operands are still unknown, wait for it to resolve.
1050   if ((V1State.isUnknownOrUndef() || V2State.isUnknownOrUndef()) &&
1051       !isConstant(ValueState[&I]))
1052     return;
1053 
1054   markOverdefined(&I);
1055 }
1056 
1057 // Handle getelementptr instructions.  If all operands are constants then we
1058 // can turn this into a getelementptr ConstantExpr.
1059 void SCCPInstVisitor::visitGetElementPtrInst(GetElementPtrInst &I) {
1060   if (isOverdefined(ValueState[&I]))
1061     return (void)markOverdefined(&I);
1062 
1063   SmallVector<Constant *, 8> Operands;
1064   Operands.reserve(I.getNumOperands());
1065 
1066   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1067     ValueLatticeElement State = getValueState(I.getOperand(i));
1068     if (State.isUnknownOrUndef())
1069       return; // Operands are not resolved yet.
1070 
1071     if (isOverdefined(State))
1072       return (void)markOverdefined(&I);
1073 
1074     if (Constant *C = getConstant(State)) {
1075       Operands.push_back(C);
1076       continue;
1077     }
1078 
1079     return (void)markOverdefined(&I);
1080   }
1081 
1082   Constant *Ptr = Operands[0];
1083   auto Indices = makeArrayRef(Operands.begin() + 1, Operands.end());
1084   Constant *C =
1085       ConstantExpr::getGetElementPtr(I.getSourceElementType(), Ptr, Indices);
1086   markConstant(&I, C);
1087 }
1088 
1089 void SCCPInstVisitor::visitStoreInst(StoreInst &SI) {
1090   // If this store is of a struct, ignore it.
1091   if (SI.getOperand(0)->getType()->isStructTy())
1092     return;
1093 
1094   if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1095     return;
1096 
1097   GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1098   auto I = TrackedGlobals.find(GV);
1099   if (I == TrackedGlobals.end())
1100     return;
1101 
1102   // Get the value we are storing into the global, then merge it.
1103   mergeInValue(I->second, GV, getValueState(SI.getOperand(0)),
1104                ValueLatticeElement::MergeOptions().setCheckWiden(false));
1105   if (I->second.isOverdefined())
1106     TrackedGlobals.erase(I); // No need to keep tracking this!
1107 }
1108 
1109 static ValueLatticeElement getValueFromMetadata(const Instruction *I) {
1110   if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range))
1111     if (I->getType()->isIntegerTy())
1112       return ValueLatticeElement::getRange(
1113           getConstantRangeFromMetadata(*Ranges));
1114   if (I->hasMetadata(LLVMContext::MD_nonnull))
1115     return ValueLatticeElement::getNot(
1116         ConstantPointerNull::get(cast<PointerType>(I->getType())));
1117   return ValueLatticeElement::getOverdefined();
1118 }
1119 
1120 // Handle load instructions.  If the operand is a constant pointer to a constant
1121 // global, we can replace the load with the loaded constant value!
1122 void SCCPInstVisitor::visitLoadInst(LoadInst &I) {
1123   // If this load is of a struct or the load is volatile, just mark the result
1124   // as overdefined.
1125   if (I.getType()->isStructTy() || I.isVolatile())
1126     return (void)markOverdefined(&I);
1127 
1128   // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would
1129   // discover a concrete value later.
1130   if (ValueState[&I].isOverdefined())
1131     return (void)markOverdefined(&I);
1132 
1133   ValueLatticeElement PtrVal = getValueState(I.getOperand(0));
1134   if (PtrVal.isUnknownOrUndef())
1135     return; // The pointer is not resolved yet!
1136 
1137   ValueLatticeElement &IV = ValueState[&I];
1138 
1139   if (isConstant(PtrVal)) {
1140     Constant *Ptr = getConstant(PtrVal);
1141 
1142     // load null is undefined.
1143     if (isa<ConstantPointerNull>(Ptr)) {
1144       if (NullPointerIsDefined(I.getFunction(), I.getPointerAddressSpace()))
1145         return (void)markOverdefined(IV, &I);
1146       else
1147         return;
1148     }
1149 
1150     // Transform load (constant global) into the value loaded.
1151     if (auto *GV = dyn_cast<GlobalVariable>(Ptr)) {
1152       if (!TrackedGlobals.empty()) {
1153         // If we are tracking this global, merge in the known value for it.
1154         auto It = TrackedGlobals.find(GV);
1155         if (It != TrackedGlobals.end()) {
1156           mergeInValue(IV, &I, It->second, getMaxWidenStepsOpts());
1157           return;
1158         }
1159       }
1160     }
1161 
1162     // Transform load from a constant into a constant if possible.
1163     if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, I.getType(), DL))
1164       return (void)markConstant(IV, &I, C);
1165   }
1166 
1167   // Fall back to metadata.
1168   mergeInValue(&I, getValueFromMetadata(&I));
1169 }
1170 
1171 void SCCPInstVisitor::visitCallBase(CallBase &CB) {
1172   handleCallResult(CB);
1173   handleCallArguments(CB);
1174 }
1175 
1176 void SCCPInstVisitor::handleCallOverdefined(CallBase &CB) {
1177   Function *F = CB.getCalledFunction();
1178 
1179   // Void return and not tracking callee, just bail.
1180   if (CB.getType()->isVoidTy())
1181     return;
1182 
1183   // Always mark struct return as overdefined.
1184   if (CB.getType()->isStructTy())
1185     return (void)markOverdefined(&CB);
1186 
1187   // Otherwise, if we have a single return value case, and if the function is
1188   // a declaration, maybe we can constant fold it.
1189   if (F && F->isDeclaration() && canConstantFoldCallTo(&CB, F)) {
1190     SmallVector<Constant *, 8> Operands;
1191     for (const Use &A : CB.args()) {
1192       if (A.get()->getType()->isStructTy())
1193         return markOverdefined(&CB); // Can't handle struct args.
1194       ValueLatticeElement State = getValueState(A);
1195 
1196       if (State.isUnknownOrUndef())
1197         return; // Operands are not resolved yet.
1198       if (isOverdefined(State))
1199         return (void)markOverdefined(&CB);
1200       assert(isConstant(State) && "Unknown state!");
1201       Operands.push_back(getConstant(State));
1202     }
1203 
1204     if (isOverdefined(getValueState(&CB)))
1205       return (void)markOverdefined(&CB);
1206 
1207     // If we can constant fold this, mark the result of the call as a
1208     // constant.
1209     if (Constant *C = ConstantFoldCall(&CB, F, Operands, &GetTLI(*F)))
1210       return (void)markConstant(&CB, C);
1211   }
1212 
1213   // Fall back to metadata.
1214   mergeInValue(&CB, getValueFromMetadata(&CB));
1215 }
1216 
1217 void SCCPInstVisitor::handleCallArguments(CallBase &CB) {
1218   Function *F = CB.getCalledFunction();
1219   // If this is a local function that doesn't have its address taken, mark its
1220   // entry block executable and merge in the actual arguments to the call into
1221   // the formal arguments of the function.
1222   if (!TrackingIncomingArguments.empty() &&
1223       TrackingIncomingArguments.count(F)) {
1224     markBlockExecutable(&F->front());
1225 
1226     // Propagate information from this call site into the callee.
1227     auto CAI = CB.arg_begin();
1228     for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
1229          ++AI, ++CAI) {
1230       // If this argument is byval, and if the function is not readonly, there
1231       // will be an implicit copy formed of the input aggregate.
1232       if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
1233         markOverdefined(&*AI);
1234         continue;
1235       }
1236 
1237       if (auto *STy = dyn_cast<StructType>(AI->getType())) {
1238         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1239           ValueLatticeElement CallArg = getStructValueState(*CAI, i);
1240           mergeInValue(getStructValueState(&*AI, i), &*AI, CallArg,
1241                        getMaxWidenStepsOpts());
1242         }
1243       } else
1244         mergeInValue(&*AI, getValueState(*CAI), getMaxWidenStepsOpts());
1245     }
1246   }
1247 }
1248 
1249 void SCCPInstVisitor::handleCallResult(CallBase &CB) {
1250   Function *F = CB.getCalledFunction();
1251 
1252   if (auto *II = dyn_cast<IntrinsicInst>(&CB)) {
1253     if (II->getIntrinsicID() == Intrinsic::ssa_copy) {
1254       if (ValueState[&CB].isOverdefined())
1255         return;
1256 
1257       Value *CopyOf = CB.getOperand(0);
1258       ValueLatticeElement CopyOfVal = getValueState(CopyOf);
1259       const auto *PI = getPredicateInfoFor(&CB);
1260       assert(PI && "Missing predicate info for ssa.copy");
1261 
1262       const Optional<PredicateConstraint> &Constraint = PI->getConstraint();
1263       if (!Constraint) {
1264         mergeInValue(ValueState[&CB], &CB, CopyOfVal);
1265         return;
1266       }
1267 
1268       CmpInst::Predicate Pred = Constraint->Predicate;
1269       Value *OtherOp = Constraint->OtherOp;
1270 
1271       // Wait until OtherOp is resolved.
1272       if (getValueState(OtherOp).isUnknown()) {
1273         addAdditionalUser(OtherOp, &CB);
1274         return;
1275       }
1276 
1277       ValueLatticeElement CondVal = getValueState(OtherOp);
1278       ValueLatticeElement &IV = ValueState[&CB];
1279       if (CondVal.isConstantRange() || CopyOfVal.isConstantRange()) {
1280         auto ImposedCR =
1281             ConstantRange::getFull(DL.getTypeSizeInBits(CopyOf->getType()));
1282 
1283         // Get the range imposed by the condition.
1284         if (CondVal.isConstantRange())
1285           ImposedCR = ConstantRange::makeAllowedICmpRegion(
1286               Pred, CondVal.getConstantRange());
1287 
1288         // Combine range info for the original value with the new range from the
1289         // condition.
1290         auto CopyOfCR = CopyOfVal.isConstantRange()
1291                             ? CopyOfVal.getConstantRange()
1292                             : ConstantRange::getFull(
1293                                   DL.getTypeSizeInBits(CopyOf->getType()));
1294         auto NewCR = ImposedCR.intersectWith(CopyOfCR);
1295         // If the existing information is != x, do not use the information from
1296         // a chained predicate, as the != x information is more likely to be
1297         // helpful in practice.
1298         if (!CopyOfCR.contains(NewCR) && CopyOfCR.getSingleMissingElement())
1299           NewCR = CopyOfCR;
1300 
1301         // The new range is based on a branch condition. That guarantees that
1302         // neither of the compare operands can be undef in the branch targets,
1303         // unless we have conditions that are always true/false (e.g. icmp ule
1304         // i32, %a, i32_max). For the latter overdefined/empty range will be
1305         // inferred, but the branch will get folded accordingly anyways.
1306         addAdditionalUser(OtherOp, &CB);
1307         mergeInValue(
1308             IV, &CB,
1309             ValueLatticeElement::getRange(NewCR, /*MayIncludeUndef*/ false));
1310         return;
1311       } else if (Pred == CmpInst::ICMP_EQ && CondVal.isConstant()) {
1312         // For non-integer values or integer constant expressions, only
1313         // propagate equal constants.
1314         addAdditionalUser(OtherOp, &CB);
1315         mergeInValue(IV, &CB, CondVal);
1316         return;
1317       } else if (Pred == CmpInst::ICMP_NE && CondVal.isConstant()) {
1318         // Propagate inequalities.
1319         addAdditionalUser(OtherOp, &CB);
1320         mergeInValue(IV, &CB,
1321                      ValueLatticeElement::getNot(CondVal.getConstant()));
1322         return;
1323       }
1324 
1325       return (void)mergeInValue(IV, &CB, CopyOfVal);
1326     }
1327 
1328     if (ConstantRange::isIntrinsicSupported(II->getIntrinsicID())) {
1329       // Compute result range for intrinsics supported by ConstantRange.
1330       // Do this even if we don't know a range for all operands, as we may
1331       // still know something about the result range, e.g. of abs(x).
1332       SmallVector<ConstantRange, 2> OpRanges;
1333       for (Value *Op : II->args()) {
1334         const ValueLatticeElement &State = getValueState(Op);
1335         if (State.isConstantRange())
1336           OpRanges.push_back(State.getConstantRange());
1337         else
1338           OpRanges.push_back(
1339               ConstantRange::getFull(Op->getType()->getScalarSizeInBits()));
1340       }
1341 
1342       ConstantRange Result =
1343           ConstantRange::intrinsic(II->getIntrinsicID(), OpRanges);
1344       return (void)mergeInValue(II, ValueLatticeElement::getRange(Result));
1345     }
1346   }
1347 
1348   // The common case is that we aren't tracking the callee, either because we
1349   // are not doing interprocedural analysis or the callee is indirect, or is
1350   // external.  Handle these cases first.
1351   if (!F || F->isDeclaration())
1352     return handleCallOverdefined(CB);
1353 
1354   // If this is a single/zero retval case, see if we're tracking the function.
1355   if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
1356     if (!MRVFunctionsTracked.count(F))
1357       return handleCallOverdefined(CB); // Not tracking this callee.
1358 
1359     // If we are tracking this callee, propagate the result of the function
1360     // into this call site.
1361     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1362       mergeInValue(getStructValueState(&CB, i), &CB,
1363                    TrackedMultipleRetVals[std::make_pair(F, i)],
1364                    getMaxWidenStepsOpts());
1365   } else {
1366     auto TFRVI = TrackedRetVals.find(F);
1367     if (TFRVI == TrackedRetVals.end())
1368       return handleCallOverdefined(CB); // Not tracking this callee.
1369 
1370     // If so, propagate the return value of the callee into this call result.
1371     mergeInValue(&CB, TFRVI->second, getMaxWidenStepsOpts());
1372   }
1373 }
1374 
1375 void SCCPInstVisitor::solve() {
1376   // Process the work lists until they are empty!
1377   while (!BBWorkList.empty() || !InstWorkList.empty() ||
1378          !OverdefinedInstWorkList.empty()) {
1379     // Process the overdefined instruction's work list first, which drives other
1380     // things to overdefined more quickly.
1381     while (!OverdefinedInstWorkList.empty()) {
1382       Value *I = OverdefinedInstWorkList.pop_back_val();
1383 
1384       LLVM_DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
1385 
1386       // "I" got into the work list because it either made the transition from
1387       // bottom to constant, or to overdefined.
1388       //
1389       // Anything on this worklist that is overdefined need not be visited
1390       // since all of its users will have already been marked as overdefined
1391       // Update all of the users of this instruction's value.
1392       //
1393       markUsersAsChanged(I);
1394     }
1395 
1396     // Process the instruction work list.
1397     while (!InstWorkList.empty()) {
1398       Value *I = InstWorkList.pop_back_val();
1399 
1400       LLVM_DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
1401 
1402       // "I" got into the work list because it made the transition from undef to
1403       // constant.
1404       //
1405       // Anything on this worklist that is overdefined need not be visited
1406       // since all of its users will have already been marked as overdefined.
1407       // Update all of the users of this instruction's value.
1408       //
1409       if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
1410         markUsersAsChanged(I);
1411     }
1412 
1413     // Process the basic block work list.
1414     while (!BBWorkList.empty()) {
1415       BasicBlock *BB = BBWorkList.pop_back_val();
1416 
1417       LLVM_DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
1418 
1419       // Notify all instructions in this basic block that they are newly
1420       // executable.
1421       visit(BB);
1422     }
1423   }
1424 }
1425 
1426 /// While solving the dataflow for a function, we don't compute a result for
1427 /// operations with an undef operand, to allow undef to be lowered to a
1428 /// constant later. For example, constant folding of "zext i8 undef to i16"
1429 /// would result in "i16 0", and if undef is later lowered to "i8 1", then the
1430 /// zext result would become "i16 1" and would result into an overdefined
1431 /// lattice value once merged with the previous result. Not computing the
1432 /// result of the zext (treating undef the same as unknown) allows us to handle
1433 /// a later undef->constant lowering more optimally.
1434 ///
1435 /// However, if the operand remains undef when the solver returns, we do need
1436 /// to assign some result to the instruction (otherwise we would treat it as
1437 /// unreachable). For simplicity, we mark any instructions that are still
1438 /// unknown as overdefined.
1439 bool SCCPInstVisitor::resolvedUndefsIn(Function &F) {
1440   bool MadeChange = false;
1441   for (BasicBlock &BB : F) {
1442     if (!BBExecutable.count(&BB))
1443       continue;
1444 
1445     for (Instruction &I : BB) {
1446       // Look for instructions which produce undef values.
1447       if (I.getType()->isVoidTy())
1448         continue;
1449 
1450       if (auto *STy = dyn_cast<StructType>(I.getType())) {
1451         // Only a few things that can be structs matter for undef.
1452 
1453         // Tracked calls must never be marked overdefined in resolvedUndefsIn.
1454         if (auto *CB = dyn_cast<CallBase>(&I))
1455           if (Function *F = CB->getCalledFunction())
1456             if (MRVFunctionsTracked.count(F))
1457               continue;
1458 
1459         // extractvalue and insertvalue don't need to be marked; they are
1460         // tracked as precisely as their operands.
1461         if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I))
1462           continue;
1463         // Send the results of everything else to overdefined.  We could be
1464         // more precise than this but it isn't worth bothering.
1465         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1466           ValueLatticeElement &LV = getStructValueState(&I, i);
1467           if (LV.isUnknown()) {
1468             markOverdefined(LV, &I);
1469             MadeChange = true;
1470           }
1471         }
1472         continue;
1473       }
1474 
1475       ValueLatticeElement &LV = getValueState(&I);
1476       if (!LV.isUnknown())
1477         continue;
1478 
1479       // There are two reasons a call can have an undef result
1480       // 1. It could be tracked.
1481       // 2. It could be constant-foldable.
1482       // Because of the way we solve return values, tracked calls must
1483       // never be marked overdefined in resolvedUndefsIn.
1484       if (auto *CB = dyn_cast<CallBase>(&I))
1485         if (Function *F = CB->getCalledFunction())
1486           if (TrackedRetVals.count(F))
1487             continue;
1488 
1489       if (isa<LoadInst>(I)) {
1490         // A load here means one of two things: a load of undef from a global,
1491         // a load from an unknown pointer.  Either way, having it return undef
1492         // is okay.
1493         continue;
1494       }
1495 
1496       markOverdefined(&I);
1497       MadeChange = true;
1498     }
1499   }
1500 
1501   return MadeChange;
1502 }
1503 
1504 //===----------------------------------------------------------------------===//
1505 //
1506 // SCCPSolver implementations
1507 //
1508 SCCPSolver::SCCPSolver(
1509     const DataLayout &DL,
1510     std::function<const TargetLibraryInfo &(Function &)> GetTLI,
1511     LLVMContext &Ctx)
1512     : Visitor(new SCCPInstVisitor(DL, std::move(GetTLI), Ctx)) {}
1513 
1514 SCCPSolver::~SCCPSolver() = default;
1515 
1516 void SCCPSolver::addAnalysis(Function &F, AnalysisResultsForFn A) {
1517   return Visitor->addAnalysis(F, std::move(A));
1518 }
1519 
1520 bool SCCPSolver::markBlockExecutable(BasicBlock *BB) {
1521   return Visitor->markBlockExecutable(BB);
1522 }
1523 
1524 const PredicateBase *SCCPSolver::getPredicateInfoFor(Instruction *I) {
1525   return Visitor->getPredicateInfoFor(I);
1526 }
1527 
1528 DomTreeUpdater SCCPSolver::getDTU(Function &F) { return Visitor->getDTU(F); }
1529 
1530 void SCCPSolver::trackValueOfGlobalVariable(GlobalVariable *GV) {
1531   Visitor->trackValueOfGlobalVariable(GV);
1532 }
1533 
1534 void SCCPSolver::addTrackedFunction(Function *F) {
1535   Visitor->addTrackedFunction(F);
1536 }
1537 
1538 void SCCPSolver::addToMustPreserveReturnsInFunctions(Function *F) {
1539   Visitor->addToMustPreserveReturnsInFunctions(F);
1540 }
1541 
1542 bool SCCPSolver::mustPreserveReturn(Function *F) {
1543   return Visitor->mustPreserveReturn(F);
1544 }
1545 
1546 void SCCPSolver::addArgumentTrackedFunction(Function *F) {
1547   Visitor->addArgumentTrackedFunction(F);
1548 }
1549 
1550 bool SCCPSolver::isArgumentTrackedFunction(Function *F) {
1551   return Visitor->isArgumentTrackedFunction(F);
1552 }
1553 
1554 void SCCPSolver::solve() { Visitor->solve(); }
1555 
1556 bool SCCPSolver::resolvedUndefsIn(Function &F) {
1557   return Visitor->resolvedUndefsIn(F);
1558 }
1559 
1560 bool SCCPSolver::isBlockExecutable(BasicBlock *BB) const {
1561   return Visitor->isBlockExecutable(BB);
1562 }
1563 
1564 bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) const {
1565   return Visitor->isEdgeFeasible(From, To);
1566 }
1567 
1568 std::vector<ValueLatticeElement>
1569 SCCPSolver::getStructLatticeValueFor(Value *V) const {
1570   return Visitor->getStructLatticeValueFor(V);
1571 }
1572 
1573 void SCCPSolver::removeLatticeValueFor(Value *V) {
1574   return Visitor->removeLatticeValueFor(V);
1575 }
1576 
1577 const ValueLatticeElement &SCCPSolver::getLatticeValueFor(Value *V) const {
1578   return Visitor->getLatticeValueFor(V);
1579 }
1580 
1581 const MapVector<Function *, ValueLatticeElement> &
1582 SCCPSolver::getTrackedRetVals() {
1583   return Visitor->getTrackedRetVals();
1584 }
1585 
1586 const DenseMap<GlobalVariable *, ValueLatticeElement> &
1587 SCCPSolver::getTrackedGlobals() {
1588   return Visitor->getTrackedGlobals();
1589 }
1590 
1591 const SmallPtrSet<Function *, 16> SCCPSolver::getMRVFunctionsTracked() {
1592   return Visitor->getMRVFunctionsTracked();
1593 }
1594 
1595 void SCCPSolver::markOverdefined(Value *V) { Visitor->markOverdefined(V); }
1596 
1597 bool SCCPSolver::isStructLatticeConstant(Function *F, StructType *STy) {
1598   return Visitor->isStructLatticeConstant(F, STy);
1599 }
1600 
1601 Constant *SCCPSolver::getConstant(const ValueLatticeElement &LV) const {
1602   return Visitor->getConstant(LV);
1603 }
1604 
1605 SmallPtrSetImpl<Function *> &SCCPSolver::getArgumentTrackedFunctions() {
1606   return Visitor->getArgumentTrackedFunctions();
1607 }
1608 
1609 void SCCPSolver::markArgInFuncSpecialization(
1610     Function *F, const SmallVectorImpl<ArgInfo> &Args) {
1611   Visitor->markArgInFuncSpecialization(F, Args);
1612 }
1613 
1614 void SCCPSolver::markFunctionUnreachable(Function *F) {
1615   Visitor->markFunctionUnreachable(F);
1616 }
1617 
1618 void SCCPSolver::visit(Instruction *I) { Visitor->visit(I); }
1619 
1620 void SCCPSolver::visitCall(CallInst &I) { Visitor->visitCall(I); }
1621