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