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