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