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 (auto *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     auto *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 (auto *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/markOverdefined
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 (auto *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     pushToWorkList(IV, 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 (auto *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 (auto *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 visitExtractValueInst(ExtractValueInst &EVI);
515   void visitInsertValueInst(InsertValueInst &IVI);
516   void visitLandingPadInst(LandingPadInst &I) { markAnythingOverdefined(&I); }
517   void visitFuncletPadInst(FuncletPadInst &FPI) {
518     markAnythingOverdefined(&FPI);
519   }
520   void visitCatchSwitchInst(CatchSwitchInst &CPI) {
521     markAnythingOverdefined(&CPI);
522     visitTerminatorInst(CPI);
523   }
524 
525   // Instructions that cannot be folded away.
526   void visitStoreInst     (StoreInst &I);
527   void visitLoadInst      (LoadInst &I);
528   void visitGetElementPtrInst(GetElementPtrInst &I);
529   void visitCallInst      (CallInst &I) {
530     visitCallSite(&I);
531   }
532   void visitInvokeInst    (InvokeInst &II) {
533     visitCallSite(&II);
534     visitTerminatorInst(II);
535   }
536   void visitCallSite      (CallSite CS);
537   void visitResumeInst    (TerminatorInst &I) { /*returns void*/ }
538   void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
539   void visitFenceInst     (FenceInst &I) { /*returns void*/ }
540   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
541     markAnythingOverdefined(&I);
542   }
543   void visitAtomicRMWInst (AtomicRMWInst &I) { markOverdefined(&I); }
544   void visitAllocaInst    (Instruction &I) { markOverdefined(&I); }
545   void visitVAArgInst     (Instruction &I) { markAnythingOverdefined(&I); }
546 
547   void visitInstruction(Instruction &I) {
548     // If a new instruction is added to LLVM that we don't handle.
549     DEBUG(dbgs() << "SCCP: Don't know how to handle: " << I << '\n');
550     markAnythingOverdefined(&I);   // Just in case
551   }
552 };
553 
554 } // end anonymous namespace
555 
556 
557 // getFeasibleSuccessors - Return a vector of booleans to indicate which
558 // successors are reachable from a given terminator instruction.
559 //
560 void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
561                                        SmallVectorImpl<bool> &Succs) {
562   Succs.resize(TI.getNumSuccessors());
563   if (auto *BI = dyn_cast<BranchInst>(&TI)) {
564     if (BI->isUnconditional()) {
565       Succs[0] = true;
566       return;
567     }
568 
569     LatticeVal BCValue = getValueState(BI->getCondition());
570     ConstantInt *CI = BCValue.getConstantInt();
571     if (!CI) {
572       // Overdefined condition variables, and branches on unfoldable constant
573       // conditions, mean the branch could go either way.
574       if (!BCValue.isUnknown())
575         Succs[0] = Succs[1] = true;
576       return;
577     }
578 
579     // Constant condition variables mean the branch can only go a single way.
580     Succs[CI->isZero()] = true;
581     return;
582   }
583 
584   // Unwinding instructions successors are always executable.
585   if (TI.isExceptional()) {
586     Succs.assign(TI.getNumSuccessors(), true);
587     return;
588   }
589 
590   if (auto *SI = dyn_cast<SwitchInst>(&TI)) {
591     if (!SI->getNumCases()) {
592       Succs[0] = true;
593       return;
594     }
595     LatticeVal SCValue = getValueState(SI->getCondition());
596     ConstantInt *CI = SCValue.getConstantInt();
597 
598     if (!CI) {   // Overdefined or unknown condition?
599       // All destinations are executable!
600       if (!SCValue.isUnknown())
601         Succs.assign(TI.getNumSuccessors(), true);
602       return;
603     }
604 
605     Succs[SI->findCaseValue(CI).getSuccessorIndex()] = true;
606     return;
607   }
608 
609   // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
610   if (isa<IndirectBrInst>(&TI)) {
611     // Just mark all destinations executable!
612     Succs.assign(TI.getNumSuccessors(), true);
613     return;
614   }
615 
616   DEBUG(dbgs() << "Unknown terminator instruction: " << TI << '\n');
617   llvm_unreachable("SCCP: Don't know how to handle this terminator!");
618 }
619 
620 
621 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
622 // block to the 'To' basic block is currently feasible.
623 //
624 bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
625   assert(BBExecutable.count(To) && "Dest should always be alive!");
626 
627   // Make sure the source basic block is executable!!
628   if (!BBExecutable.count(From)) return false;
629 
630   // Check to make sure this edge itself is actually feasible now.
631   TerminatorInst *TI = From->getTerminator();
632   if (auto *BI = dyn_cast<BranchInst>(TI)) {
633     if (BI->isUnconditional())
634       return true;
635 
636     LatticeVal BCValue = getValueState(BI->getCondition());
637 
638     // Overdefined condition variables mean the branch could go either way,
639     // undef conditions mean that neither edge is feasible yet.
640     ConstantInt *CI = BCValue.getConstantInt();
641     if (!CI)
642       return !BCValue.isUnknown();
643 
644     // Constant condition variables mean the branch can only go a single way.
645     return BI->getSuccessor(CI->isZero()) == To;
646   }
647 
648   // Unwinding instructions successors are always executable.
649   if (TI->isExceptional())
650     return true;
651 
652   if (auto *SI = dyn_cast<SwitchInst>(TI)) {
653     if (SI->getNumCases() < 1)
654       return true;
655 
656     LatticeVal SCValue = getValueState(SI->getCondition());
657     ConstantInt *CI = SCValue.getConstantInt();
658 
659     if (!CI)
660       return !SCValue.isUnknown();
661 
662     return SI->findCaseValue(CI).getCaseSuccessor() == To;
663   }
664 
665   // Just mark all destinations executable!
666   // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
667   if (isa<IndirectBrInst>(TI))
668     return true;
669 
670   DEBUG(dbgs() << "Unknown terminator instruction: " << *TI << '\n');
671   llvm_unreachable("SCCP: Don't know how to handle this terminator!");
672 }
673 
674 // visit Implementations - Something changed in this instruction, either an
675 // operand made a transition, or the instruction is newly executable.  Change
676 // the value type of I to reflect these changes if appropriate.  This method
677 // makes sure to do the following actions:
678 //
679 // 1. If a phi node merges two constants in, and has conflicting value coming
680 //    from different branches, or if the PHI node merges in an overdefined
681 //    value, then the PHI node becomes overdefined.
682 // 2. If a phi node merges only constants in, and they all agree on value, the
683 //    PHI node becomes a constant value equal to that.
684 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
685 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
686 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
687 // 6. If a conditional branch has a value that is constant, make the selected
688 //    destination executable
689 // 7. If a conditional branch has a value that is overdefined, make all
690 //    successors executable.
691 //
692 void SCCPSolver::visitPHINode(PHINode &PN) {
693   // If this PN returns a struct, just mark the result overdefined.
694   // TODO: We could do a lot better than this if code actually uses this.
695   if (PN.getType()->isStructTy())
696     return markAnythingOverdefined(&PN);
697 
698   if (getValueState(&PN).isOverdefined())
699     return;  // Quick exit
700 
701   // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
702   // and slow us down a lot.  Just mark them overdefined.
703   if (PN.getNumIncomingValues() > 64)
704     return markOverdefined(&PN);
705 
706   // Look at all of the executable operands of the PHI node.  If any of them
707   // are overdefined, the PHI becomes overdefined as well.  If they are all
708   // constant, and they agree with each other, the PHI becomes the identical
709   // constant.  If they are constant and don't agree, the PHI is overdefined.
710   // If there are no executable operands, the PHI remains unknown.
711   //
712   Constant *OperandVal = nullptr;
713   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
714     LatticeVal IV = getValueState(PN.getIncomingValue(i));
715     if (IV.isUnknown()) continue;  // Doesn't influence PHI node.
716 
717     if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
718       continue;
719 
720     if (IV.isOverdefined())    // PHI node becomes overdefined!
721       return markOverdefined(&PN);
722 
723     if (!OperandVal) {   // Grab the first value.
724       OperandVal = IV.getConstant();
725       continue;
726     }
727 
728     // There is already a reachable operand.  If we conflict with it,
729     // then the PHI node becomes overdefined.  If we agree with it, we
730     // can continue on.
731 
732     // Check to see if there are two different constants merging, if so, the PHI
733     // node is overdefined.
734     if (IV.getConstant() != OperandVal)
735       return markOverdefined(&PN);
736   }
737 
738   // If we exited the loop, this means that the PHI node only has constant
739   // arguments that agree with each other(and OperandVal is the constant) or
740   // OperandVal is null because there are no defined incoming arguments.  If
741   // this is the case, the PHI remains unknown.
742   //
743   if (OperandVal)
744     markConstant(&PN, OperandVal);      // Acquire operand value
745 }
746 
747 void SCCPSolver::visitReturnInst(ReturnInst &I) {
748   if (I.getNumOperands() == 0) return;  // ret void
749 
750   Function *F = I.getParent()->getParent();
751   Value *ResultOp = I.getOperand(0);
752 
753   // If we are tracking the return value of this function, merge it in.
754   if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
755     DenseMap<Function*, LatticeVal>::iterator TFRVI =
756       TrackedRetVals.find(F);
757     if (TFRVI != TrackedRetVals.end()) {
758       mergeInValue(TFRVI->second, F, getValueState(ResultOp));
759       return;
760     }
761   }
762 
763   // Handle functions that return multiple values.
764   if (!TrackedMultipleRetVals.empty()) {
765     if (auto *STy = dyn_cast<StructType>(ResultOp->getType()))
766       if (MRVFunctionsTracked.count(F))
767         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
768           mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
769                        getStructValueState(ResultOp, i));
770 
771   }
772 }
773 
774 void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
775   SmallVector<bool, 16> SuccFeasible;
776   getFeasibleSuccessors(TI, SuccFeasible);
777 
778   BasicBlock *BB = TI.getParent();
779 
780   // Mark all feasible successors executable.
781   for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
782     if (SuccFeasible[i])
783       markEdgeExecutable(BB, TI.getSuccessor(i));
784 }
785 
786 void SCCPSolver::visitCastInst(CastInst &I) {
787   LatticeVal OpSt = getValueState(I.getOperand(0));
788   if (OpSt.isOverdefined())          // Inherit overdefinedness of operand
789     markOverdefined(&I);
790   else if (OpSt.isConstant()) {
791     // Fold the constant as we build.
792     Constant *C = ConstantFoldCastOperand(I.getOpcode(), OpSt.getConstant(),
793                                           I.getType(), DL);
794     if (isa<UndefValue>(C))
795       return;
796     // Propagate constant value
797     markConstant(&I, C);
798   }
799 }
800 
801 
802 void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
803   // If this returns a struct, mark all elements over defined, we don't track
804   // structs in structs.
805   if (EVI.getType()->isStructTy())
806     return markAnythingOverdefined(&EVI);
807 
808   // If this is extracting from more than one level of struct, we don't know.
809   if (EVI.getNumIndices() != 1)
810     return markOverdefined(&EVI);
811 
812   Value *AggVal = EVI.getAggregateOperand();
813   if (AggVal->getType()->isStructTy()) {
814     unsigned i = *EVI.idx_begin();
815     LatticeVal EltVal = getStructValueState(AggVal, i);
816     mergeInValue(getValueState(&EVI), &EVI, EltVal);
817   } else {
818     // Otherwise, must be extracting from an array.
819     return markOverdefined(&EVI);
820   }
821 }
822 
823 void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
824   auto *STy = dyn_cast<StructType>(IVI.getType());
825   if (!STy)
826     return markOverdefined(&IVI);
827 
828   // If this has more than one index, we can't handle it, drive all results to
829   // undef.
830   if (IVI.getNumIndices() != 1)
831     return markAnythingOverdefined(&IVI);
832 
833   Value *Aggr = IVI.getAggregateOperand();
834   unsigned Idx = *IVI.idx_begin();
835 
836   // Compute the result based on what we're inserting.
837   for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
838     // This passes through all values that aren't the inserted element.
839     if (i != Idx) {
840       LatticeVal EltVal = getStructValueState(Aggr, i);
841       mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
842       continue;
843     }
844 
845     Value *Val = IVI.getInsertedValueOperand();
846     if (Val->getType()->isStructTy())
847       // We don't track structs in structs.
848       markOverdefined(getStructValueState(&IVI, i), &IVI);
849     else {
850       LatticeVal InVal = getValueState(Val);
851       mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
852     }
853   }
854 }
855 
856 void SCCPSolver::visitSelectInst(SelectInst &I) {
857   // If this select returns a struct, just mark the result overdefined.
858   // TODO: We could do a lot better than this if code actually uses this.
859   if (I.getType()->isStructTy())
860     return markAnythingOverdefined(&I);
861 
862   LatticeVal CondValue = getValueState(I.getCondition());
863   if (CondValue.isUnknown())
864     return;
865 
866   if (ConstantInt *CondCB = CondValue.getConstantInt()) {
867     Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
868     mergeInValue(&I, getValueState(OpVal));
869     return;
870   }
871 
872   // Otherwise, the condition is overdefined or a constant we can't evaluate.
873   // See if we can produce something better than overdefined based on the T/F
874   // value.
875   LatticeVal TVal = getValueState(I.getTrueValue());
876   LatticeVal FVal = getValueState(I.getFalseValue());
877 
878   // select ?, C, C -> C.
879   if (TVal.isConstant() && FVal.isConstant() &&
880       TVal.getConstant() == FVal.getConstant())
881     return markConstant(&I, FVal.getConstant());
882 
883   if (TVal.isUnknown())   // select ?, undef, X -> X.
884     return mergeInValue(&I, FVal);
885   if (FVal.isUnknown())   // select ?, X, undef -> X.
886     return mergeInValue(&I, TVal);
887   markOverdefined(&I);
888 }
889 
890 // Handle Binary Operators.
891 void SCCPSolver::visitBinaryOperator(Instruction &I) {
892   LatticeVal V1State = getValueState(I.getOperand(0));
893   LatticeVal V2State = getValueState(I.getOperand(1));
894 
895   LatticeVal &IV = ValueState[&I];
896   if (IV.isOverdefined()) return;
897 
898   if (V1State.isConstant() && V2State.isConstant()) {
899     Constant *C = ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
900                                     V2State.getConstant());
901     // X op Y -> undef.
902     if (isa<UndefValue>(C))
903       return;
904     return markConstant(IV, &I, C);
905   }
906 
907   // If something is undef, wait for it to resolve.
908   if (!V1State.isOverdefined() && !V2State.isOverdefined())
909     return;
910 
911   // Otherwise, one of our operands is overdefined.  Try to produce something
912   // better than overdefined with some tricks.
913   // If this is 0 / Y, it doesn't matter that the second operand is
914   // overdefined, and we can replace it with zero.
915   if (I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction::SDiv)
916     if (V1State.isConstant() && V1State.getConstant()->isNullValue())
917       return markConstant(IV, &I, V1State.getConstant());
918 
919   // If this is:
920   // -> AND/MUL with 0
921   // -> OR with -1
922   // it doesn't matter that the other operand is overdefined.
923   if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Mul ||
924       I.getOpcode() == Instruction::Or) {
925     LatticeVal *NonOverdefVal = nullptr;
926     if (!V1State.isOverdefined())
927       NonOverdefVal = &V1State;
928     else if (!V2State.isOverdefined())
929       NonOverdefVal = &V2State;
930 
931     if (NonOverdefVal) {
932       if (NonOverdefVal->isUnknown())
933         return;
934 
935       if (I.getOpcode() == Instruction::And ||
936           I.getOpcode() == Instruction::Mul) {
937         // X and 0 = 0
938         // X * 0 = 0
939         if (NonOverdefVal->getConstant()->isNullValue())
940           return markConstant(IV, &I, NonOverdefVal->getConstant());
941       } else {
942         // X or -1 = -1
943         if (ConstantInt *CI = NonOverdefVal->getConstantInt())
944           if (CI->isAllOnesValue())
945             return markConstant(IV, &I, NonOverdefVal->getConstant());
946       }
947     }
948   }
949 
950 
951   markOverdefined(&I);
952 }
953 
954 // Handle ICmpInst instruction.
955 void SCCPSolver::visitCmpInst(CmpInst &I) {
956   LatticeVal V1State = getValueState(I.getOperand(0));
957   LatticeVal V2State = getValueState(I.getOperand(1));
958 
959   LatticeVal &IV = ValueState[&I];
960   if (IV.isOverdefined()) return;
961 
962   if (V1State.isConstant() && V2State.isConstant()) {
963     Constant *C = ConstantExpr::getCompare(
964         I.getPredicate(), V1State.getConstant(), V2State.getConstant());
965     if (isa<UndefValue>(C))
966       return;
967     return markConstant(IV, &I, C);
968   }
969 
970   // If operands are still unknown, wait for it to resolve.
971   if (!V1State.isOverdefined() && !V2State.isOverdefined())
972     return;
973 
974   markOverdefined(&I);
975 }
976 
977 // Handle getelementptr instructions.  If all operands are constants then we
978 // can turn this into a getelementptr ConstantExpr.
979 //
980 void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
981   if (ValueState[&I].isOverdefined()) return;
982 
983   SmallVector<Constant*, 8> Operands;
984   Operands.reserve(I.getNumOperands());
985 
986   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
987     LatticeVal State = getValueState(I.getOperand(i));
988     if (State.isUnknown())
989       return;  // Operands are not resolved yet.
990 
991     if (State.isOverdefined())
992       return markOverdefined(&I);
993 
994     assert(State.isConstant() && "Unknown state!");
995     Operands.push_back(State.getConstant());
996   }
997 
998   Constant *Ptr = Operands[0];
999   auto Indices = makeArrayRef(Operands.begin() + 1, Operands.end());
1000   Constant *C =
1001       ConstantExpr::getGetElementPtr(I.getSourceElementType(), Ptr, Indices);
1002   if (isa<UndefValue>(C))
1003       return;
1004   markConstant(&I, C);
1005 }
1006 
1007 void SCCPSolver::visitStoreInst(StoreInst &SI) {
1008   // If this store is of a struct, ignore it.
1009   if (SI.getOperand(0)->getType()->isStructTy())
1010     return;
1011 
1012   if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1013     return;
1014 
1015   GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1016   DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
1017   if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1018 
1019   // Get the value we are storing into the global, then merge it.
1020   mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
1021   if (I->second.isOverdefined())
1022     TrackedGlobals.erase(I);      // No need to keep tracking this!
1023 }
1024 
1025 
1026 // Handle load instructions.  If the operand is a constant pointer to a constant
1027 // global, we can replace the load with the loaded constant value!
1028 void SCCPSolver::visitLoadInst(LoadInst &I) {
1029   // If this load is of a struct, just mark the result overdefined.
1030   if (I.getType()->isStructTy())
1031     return markAnythingOverdefined(&I);
1032 
1033   LatticeVal PtrVal = getValueState(I.getOperand(0));
1034   if (PtrVal.isUnknown()) return;   // The pointer is not resolved yet!
1035 
1036   LatticeVal &IV = ValueState[&I];
1037   if (IV.isOverdefined()) return;
1038 
1039   if (!PtrVal.isConstant() || I.isVolatile())
1040     return markOverdefined(IV, &I);
1041 
1042   Constant *Ptr = PtrVal.getConstant();
1043 
1044   // load null is undefined.
1045   if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
1046     return;
1047 
1048   // Transform load (constant global) into the value loaded.
1049   if (auto *GV = dyn_cast<GlobalVariable>(Ptr)) {
1050     if (!TrackedGlobals.empty()) {
1051       // If we are tracking this global, merge in the known value for it.
1052       DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1053         TrackedGlobals.find(GV);
1054       if (It != TrackedGlobals.end()) {
1055         mergeInValue(IV, &I, It->second);
1056         return;
1057       }
1058     }
1059   }
1060 
1061   // Transform load from a constant into a constant if possible.
1062   if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, I.getType(), DL)) {
1063     if (isa<UndefValue>(C))
1064       return;
1065     return markConstant(IV, &I, C);
1066   }
1067 
1068   // Otherwise we cannot say for certain what value this load will produce.
1069   // Bail out.
1070   markOverdefined(IV, &I);
1071 }
1072 
1073 void SCCPSolver::visitCallSite(CallSite CS) {
1074   Function *F = CS.getCalledFunction();
1075   Instruction *I = CS.getInstruction();
1076 
1077   // The common case is that we aren't tracking the callee, either because we
1078   // are not doing interprocedural analysis or the callee is indirect, or is
1079   // external.  Handle these cases first.
1080   if (!F || F->isDeclaration()) {
1081 CallOverdefined:
1082     // Void return and not tracking callee, just bail.
1083     if (I->getType()->isVoidTy()) return;
1084 
1085     // Otherwise, if we have a single return value case, and if the function is
1086     // a declaration, maybe we can constant fold it.
1087     if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
1088         canConstantFoldCallTo(F)) {
1089 
1090       SmallVector<Constant*, 8> Operands;
1091       for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1092            AI != E; ++AI) {
1093         LatticeVal State = getValueState(*AI);
1094 
1095         if (State.isUnknown())
1096           return;  // Operands are not resolved yet.
1097         if (State.isOverdefined())
1098           return markOverdefined(I);
1099         assert(State.isConstant() && "Unknown state!");
1100         Operands.push_back(State.getConstant());
1101       }
1102 
1103       if (getValueState(I).isOverdefined())
1104         return;
1105 
1106       // If we can constant fold this, mark the result of the call as a
1107       // constant.
1108       if (Constant *C = ConstantFoldCall(F, Operands, TLI)) {
1109         // call -> undef.
1110         if (isa<UndefValue>(C))
1111           return;
1112         return markConstant(I, C);
1113       }
1114     }
1115 
1116     // Otherwise, we don't know anything about this call, mark it overdefined.
1117     return markAnythingOverdefined(I);
1118   }
1119 
1120   // If this is a local function that doesn't have its address taken, mark its
1121   // entry block executable and merge in the actual arguments to the call into
1122   // the formal arguments of the function.
1123   if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
1124     MarkBlockExecutable(&F->front());
1125 
1126     // Propagate information from this call site into the callee.
1127     CallSite::arg_iterator CAI = CS.arg_begin();
1128     for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1129          AI != E; ++AI, ++CAI) {
1130       // If this argument is byval, and if the function is not readonly, there
1131       // will be an implicit copy formed of the input aggregate.
1132       if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
1133         markOverdefined(&*AI);
1134         continue;
1135       }
1136 
1137       if (auto *STy = dyn_cast<StructType>(AI->getType())) {
1138         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1139           LatticeVal CallArg = getStructValueState(*CAI, i);
1140           mergeInValue(getStructValueState(&*AI, i), &*AI, CallArg);
1141         }
1142       } else {
1143         mergeInValue(&*AI, getValueState(*CAI));
1144       }
1145     }
1146   }
1147 
1148   // If this is a single/zero retval case, see if we're tracking the function.
1149   if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
1150     if (!MRVFunctionsTracked.count(F))
1151       goto CallOverdefined;  // Not tracking this callee.
1152 
1153     // If we are tracking this callee, propagate the result of the function
1154     // into this call site.
1155     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1156       mergeInValue(getStructValueState(I, i), I,
1157                    TrackedMultipleRetVals[std::make_pair(F, i)]);
1158   } else {
1159     DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1160     if (TFRVI == TrackedRetVals.end())
1161       goto CallOverdefined;  // Not tracking this callee.
1162 
1163     // If so, propagate the return value of the callee into this call result.
1164     mergeInValue(I, TFRVI->second);
1165   }
1166 }
1167 
1168 void SCCPSolver::Solve() {
1169   // Process the work lists until they are empty!
1170   while (!BBWorkList.empty() || !InstWorkList.empty() ||
1171          !OverdefinedInstWorkList.empty()) {
1172     // Process the overdefined instruction's work list first, which drives other
1173     // things to overdefined more quickly.
1174     while (!OverdefinedInstWorkList.empty()) {
1175       Value *I = OverdefinedInstWorkList.pop_back_val();
1176 
1177       DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
1178 
1179       // "I" got into the work list because it either made the transition from
1180       // bottom to constant, or to overdefined.
1181       //
1182       // Anything on this worklist that is overdefined need not be visited
1183       // since all of its users will have already been marked as overdefined
1184       // Update all of the users of this instruction's value.
1185       //
1186       for (User *U : I->users())
1187         if (auto *UI = dyn_cast<Instruction>(U))
1188           OperandChangedState(UI);
1189     }
1190 
1191     // Process the instruction work list.
1192     while (!InstWorkList.empty()) {
1193       Value *I = InstWorkList.pop_back_val();
1194 
1195       DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
1196 
1197       // "I" got into the work list because it made the transition from undef to
1198       // constant.
1199       //
1200       // Anything on this worklist that is overdefined need not be visited
1201       // since all of its users will have already been marked as overdefined.
1202       // Update all of the users of this instruction's value.
1203       //
1204       if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
1205         for (User *U : I->users())
1206           if (auto *UI = dyn_cast<Instruction>(U))
1207             OperandChangedState(UI);
1208     }
1209 
1210     // Process the basic block work list.
1211     while (!BBWorkList.empty()) {
1212       BasicBlock *BB = BBWorkList.back();
1213       BBWorkList.pop_back();
1214 
1215       DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
1216 
1217       // Notify all instructions in this basic block that they are newly
1218       // executable.
1219       visit(BB);
1220     }
1221   }
1222 }
1223 
1224 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1225 /// that branches on undef values cannot reach any of their successors.
1226 /// However, this is not a safe assumption.  After we solve dataflow, this
1227 /// method should be use to handle this.  If this returns true, the solver
1228 /// should be rerun.
1229 ///
1230 /// This method handles this by finding an unresolved branch and marking it one
1231 /// of the edges from the block as being feasible, even though the condition
1232 /// doesn't say it would otherwise be.  This allows SCCP to find the rest of the
1233 /// CFG and only slightly pessimizes the analysis results (by marking one,
1234 /// potentially infeasible, edge feasible).  This cannot usefully modify the
1235 /// constraints on the condition of the branch, as that would impact other users
1236 /// of the value.
1237 ///
1238 /// This scan also checks for values that use undefs, whose results are actually
1239 /// defined.  For example, 'zext i8 undef to i32' should produce all zeros
1240 /// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1241 /// even if X isn't defined.
1242 bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1243   for (BasicBlock &BB : F) {
1244     if (!BBExecutable.count(&BB))
1245       continue;
1246 
1247     for (Instruction &I : BB) {
1248       // Look for instructions which produce undef values.
1249       if (I.getType()->isVoidTy()) continue;
1250 
1251       if (auto *STy = dyn_cast<StructType>(I.getType())) {
1252         // Only a few things that can be structs matter for undef.
1253 
1254         // Tracked calls must never be marked overdefined in ResolvedUndefsIn.
1255         if (CallSite CS = CallSite(&I))
1256           if (Function *F = CS.getCalledFunction())
1257             if (MRVFunctionsTracked.count(F))
1258               continue;
1259 
1260         // extractvalue and insertvalue don't need to be marked; they are
1261         // tracked as precisely as their operands.
1262         if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I))
1263           continue;
1264 
1265         // Send the results of everything else to overdefined.  We could be
1266         // more precise than this but it isn't worth bothering.
1267         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1268           LatticeVal &LV = getStructValueState(&I, i);
1269           if (LV.isUnknown())
1270             markOverdefined(LV, &I);
1271         }
1272         continue;
1273       }
1274 
1275       LatticeVal &LV = getValueState(&I);
1276       if (!LV.isUnknown()) continue;
1277 
1278       // extractvalue is safe; check here because the argument is a struct.
1279       if (isa<ExtractValueInst>(I))
1280         continue;
1281 
1282       // Compute the operand LatticeVals, for convenience below.
1283       // Anything taking a struct is conservatively assumed to require
1284       // overdefined markings.
1285       if (I.getOperand(0)->getType()->isStructTy()) {
1286         markOverdefined(&I);
1287         return true;
1288       }
1289       LatticeVal Op0LV = getValueState(I.getOperand(0));
1290       LatticeVal Op1LV;
1291       if (I.getNumOperands() == 2) {
1292         if (I.getOperand(1)->getType()->isStructTy()) {
1293           markOverdefined(&I);
1294           return true;
1295         }
1296 
1297         Op1LV = getValueState(I.getOperand(1));
1298       }
1299       // If this is an instructions whose result is defined even if the input is
1300       // not fully defined, propagate the information.
1301       Type *ITy = I.getType();
1302       switch (I.getOpcode()) {
1303       case Instruction::Add:
1304       case Instruction::Sub:
1305       case Instruction::Trunc:
1306       case Instruction::FPTrunc:
1307       case Instruction::BitCast:
1308         break; // Any undef -> undef
1309       case Instruction::FSub:
1310       case Instruction::FAdd:
1311       case Instruction::FMul:
1312       case Instruction::FDiv:
1313       case Instruction::FRem:
1314         // Floating-point binary operation: be conservative.
1315         if (Op0LV.isUnknown() && Op1LV.isUnknown())
1316           markForcedConstant(&I, Constant::getNullValue(ITy));
1317         else
1318           markOverdefined(&I);
1319         return true;
1320       case Instruction::ZExt:
1321       case Instruction::SExt:
1322       case Instruction::FPToUI:
1323       case Instruction::FPToSI:
1324       case Instruction::FPExt:
1325       case Instruction::PtrToInt:
1326       case Instruction::IntToPtr:
1327       case Instruction::SIToFP:
1328       case Instruction::UIToFP:
1329         // undef -> 0; some outputs are impossible
1330         markForcedConstant(&I, Constant::getNullValue(ITy));
1331         return true;
1332       case Instruction::Mul:
1333       case Instruction::And:
1334         // Both operands undef -> undef
1335         if (Op0LV.isUnknown() && Op1LV.isUnknown())
1336           break;
1337         // undef * X -> 0.   X could be zero.
1338         // undef & X -> 0.   X could be zero.
1339         markForcedConstant(&I, Constant::getNullValue(ITy));
1340         return true;
1341 
1342       case Instruction::Or:
1343         // Both operands undef -> undef
1344         if (Op0LV.isUnknown() && Op1LV.isUnknown())
1345           break;
1346         // undef | X -> -1.   X could be -1.
1347         markForcedConstant(&I, Constant::getAllOnesValue(ITy));
1348         return true;
1349 
1350       case Instruction::Xor:
1351         // undef ^ undef -> 0; strictly speaking, this is not strictly
1352         // necessary, but we try to be nice to people who expect this
1353         // behavior in simple cases
1354         if (Op0LV.isUnknown() && Op1LV.isUnknown()) {
1355           markForcedConstant(&I, Constant::getNullValue(ITy));
1356           return true;
1357         }
1358         // undef ^ X -> undef
1359         break;
1360 
1361       case Instruction::SDiv:
1362       case Instruction::UDiv:
1363       case Instruction::SRem:
1364       case Instruction::URem:
1365         // X / undef -> undef.  No change.
1366         // X % undef -> undef.  No change.
1367         if (Op1LV.isUnknown()) break;
1368 
1369         // X / 0 -> undef.  No change.
1370         // X % 0 -> undef.  No change.
1371         if (Op1LV.isConstant() && Op1LV.getConstant()->isZeroValue())
1372           break;
1373 
1374         // undef / X -> 0.   X could be maxint.
1375         // undef % X -> 0.   X could be 1.
1376         markForcedConstant(&I, Constant::getNullValue(ITy));
1377         return true;
1378 
1379       case Instruction::AShr:
1380         // X >>a undef -> undef.
1381         if (Op1LV.isUnknown()) break;
1382 
1383         // Shifting by the bitwidth or more is undefined.
1384         if (Op1LV.isConstant()) {
1385           if (auto *ShiftAmt = Op1LV.getConstantInt())
1386             if (ShiftAmt->getLimitedValue() >=
1387                 ShiftAmt->getType()->getScalarSizeInBits())
1388               break;
1389         }
1390 
1391         // undef >>a X -> 0
1392         markForcedConstant(&I, Constant::getNullValue(ITy));
1393         return true;
1394       case Instruction::LShr:
1395       case Instruction::Shl:
1396         // X << undef -> undef.
1397         // X >> undef -> undef.
1398         if (Op1LV.isUnknown()) break;
1399 
1400         // Shifting by the bitwidth or more is undefined.
1401         if (Op1LV.isConstant()) {
1402           if (auto *ShiftAmt = Op1LV.getConstantInt())
1403             if (ShiftAmt->getLimitedValue() >=
1404                 ShiftAmt->getType()->getScalarSizeInBits())
1405               break;
1406         }
1407 
1408         // undef << X -> 0
1409         // undef >> X -> 0
1410         markForcedConstant(&I, Constant::getNullValue(ITy));
1411         return true;
1412       case Instruction::Select:
1413         Op1LV = getValueState(I.getOperand(1));
1414         // undef ? X : Y  -> X or Y.  There could be commonality between X/Y.
1415         if (Op0LV.isUnknown()) {
1416           if (!Op1LV.isConstant())  // Pick the constant one if there is any.
1417             Op1LV = getValueState(I.getOperand(2));
1418         } else if (Op1LV.isUnknown()) {
1419           // c ? undef : undef -> undef.  No change.
1420           Op1LV = getValueState(I.getOperand(2));
1421           if (Op1LV.isUnknown())
1422             break;
1423           // Otherwise, c ? undef : x -> x.
1424         } else {
1425           // Leave Op1LV as Operand(1)'s LatticeValue.
1426         }
1427 
1428         if (Op1LV.isConstant())
1429           markForcedConstant(&I, Op1LV.getConstant());
1430         else
1431           markOverdefined(&I);
1432         return true;
1433       case Instruction::Load:
1434         // A load here means one of two things: a load of undef from a global,
1435         // a load from an unknown pointer.  Either way, having it return undef
1436         // is okay.
1437         break;
1438       case Instruction::ICmp:
1439         // X == undef -> undef.  Other comparisons get more complicated.
1440         if (cast<ICmpInst>(&I)->isEquality())
1441           break;
1442         markOverdefined(&I);
1443         return true;
1444       case Instruction::Call:
1445       case Instruction::Invoke: {
1446         // There are two reasons a call can have an undef result
1447         // 1. It could be tracked.
1448         // 2. It could be constant-foldable.
1449         // Because of the way we solve return values, tracked calls must
1450         // never be marked overdefined in ResolvedUndefsIn.
1451         if (Function *F = CallSite(&I).getCalledFunction())
1452           if (TrackedRetVals.count(F))
1453             break;
1454 
1455         // If the call is constant-foldable, we mark it overdefined because
1456         // we do not know what return values are valid.
1457         markOverdefined(&I);
1458         return true;
1459       }
1460       default:
1461         // If we don't know what should happen here, conservatively mark it
1462         // overdefined.
1463         markOverdefined(&I);
1464         return true;
1465       }
1466     }
1467 
1468     // Check to see if we have a branch or switch on an undefined value.  If so
1469     // we force the branch to go one way or the other to make the successor
1470     // values live.  It doesn't really matter which way we force it.
1471     TerminatorInst *TI = BB.getTerminator();
1472     if (auto *BI = dyn_cast<BranchInst>(TI)) {
1473       if (!BI->isConditional()) continue;
1474       if (!getValueState(BI->getCondition()).isUnknown())
1475         continue;
1476 
1477       // If the input to SCCP is actually branch on undef, fix the undef to
1478       // false.
1479       if (isa<UndefValue>(BI->getCondition())) {
1480         BI->setCondition(ConstantInt::getFalse(BI->getContext()));
1481         markEdgeExecutable(&BB, TI->getSuccessor(1));
1482         return true;
1483       }
1484 
1485       // Otherwise, it is a branch on a symbolic value which is currently
1486       // considered to be undef.  Handle this by forcing the input value to the
1487       // branch to false.
1488       markForcedConstant(BI->getCondition(),
1489                          ConstantInt::getFalse(TI->getContext()));
1490       return true;
1491     }
1492 
1493     if (auto *SI = dyn_cast<SwitchInst>(TI)) {
1494       if (!SI->getNumCases() || !getValueState(SI->getCondition()).isUnknown())
1495         continue;
1496 
1497       // If the input to SCCP is actually switch on undef, fix the undef to
1498       // the first constant.
1499       if (isa<UndefValue>(SI->getCondition())) {
1500         SI->setCondition(SI->case_begin().getCaseValue());
1501         markEdgeExecutable(&BB, SI->case_begin().getCaseSuccessor());
1502         return true;
1503       }
1504 
1505       markForcedConstant(SI->getCondition(), SI->case_begin().getCaseValue());
1506       return true;
1507     }
1508   }
1509 
1510   return false;
1511 }
1512 
1513 static bool tryToReplaceWithConstant(SCCPSolver &Solver, Value *V) {
1514   Constant *Const = nullptr;
1515   if (V->getType()->isStructTy()) {
1516     std::vector<LatticeVal> IVs = Solver.getStructLatticeValueFor(V);
1517     if (any_of(IVs, [](const LatticeVal &LV) { return LV.isOverdefined(); }))
1518       return false;
1519     std::vector<Constant *> ConstVals;
1520     auto *ST = dyn_cast<StructType>(V->getType());
1521     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1522       LatticeVal V = IVs[i];
1523       ConstVals.push_back(V.isConstant()
1524                               ? V.getConstant()
1525                               : UndefValue::get(ST->getElementType(i)));
1526     }
1527     Const = ConstantStruct::get(ST, ConstVals);
1528   } else {
1529     LatticeVal IV = Solver.getLatticeValueFor(V);
1530     if (IV.isOverdefined())
1531       return false;
1532     Const = IV.isConstant() ? IV.getConstant() : UndefValue::get(V->getType());
1533   }
1534   assert(Const && "Constant is nullptr here!");
1535   DEBUG(dbgs() << "  Constant: " << *Const << " = " << *V << '\n');
1536 
1537   // Replaces all of the uses of a variable with uses of the constant.
1538   V->replaceAllUsesWith(Const);
1539   return true;
1540 }
1541 
1542 // runSCCP() - Run the Sparse Conditional Constant Propagation algorithm,
1543 // and return true if the function was modified.
1544 //
1545 static bool runSCCP(Function &F, const DataLayout &DL,
1546                     const TargetLibraryInfo *TLI) {
1547   DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
1548   SCCPSolver Solver(DL, TLI);
1549 
1550   // Mark the first block of the function as being executable.
1551   Solver.MarkBlockExecutable(&F.front());
1552 
1553   // Mark all arguments to the function as being overdefined.
1554   for (Argument &AI : F.args())
1555     Solver.markAnythingOverdefined(&AI);
1556 
1557   // Solve for constants.
1558   bool ResolvedUndefs = true;
1559   while (ResolvedUndefs) {
1560     Solver.Solve();
1561     DEBUG(dbgs() << "RESOLVING UNDEFs\n");
1562     ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1563   }
1564 
1565   bool MadeChanges = false;
1566 
1567   // If we decided that there are basic blocks that are dead in this function,
1568   // delete their contents now.  Note that we cannot actually delete the blocks,
1569   // as we cannot modify the CFG of the function.
1570 
1571   for (BasicBlock &BB : F) {
1572     if (!Solver.isBlockExecutable(&BB)) {
1573       DEBUG(dbgs() << "  BasicBlock Dead:" << BB);
1574 
1575       ++NumDeadBlocks;
1576       NumInstRemoved += removeAllNonTerminatorAndEHPadInstructions(&BB);
1577 
1578       MadeChanges = true;
1579       continue;
1580     }
1581 
1582     // Iterate over all of the instructions in a function, replacing them with
1583     // constants if we have found them to be of constant values.
1584     //
1585     for (BasicBlock::iterator BI = BB.begin(), E = BB.end(); BI != E;) {
1586       Instruction *Inst = &*BI++;
1587       if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1588         continue;
1589 
1590       if (tryToReplaceWithConstant(Solver, Inst)) {
1591         if (isInstructionTriviallyDead(Inst))
1592           Inst->eraseFromParent();
1593         // Hey, we just changed something!
1594         MadeChanges = true;
1595         ++NumInstRemoved;
1596       }
1597     }
1598   }
1599 
1600   return MadeChanges;
1601 }
1602 
1603 PreservedAnalyses SCCPPass::run(Function &F, FunctionAnalysisManager &AM) {
1604   const DataLayout &DL = F.getParent()->getDataLayout();
1605   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1606   if (!runSCCP(F, DL, &TLI))
1607     return PreservedAnalyses::all();
1608 
1609   auto PA = PreservedAnalyses();
1610   PA.preserve<GlobalsAA>();
1611   return PA;
1612 }
1613 
1614 namespace {
1615 //===--------------------------------------------------------------------===//
1616 //
1617 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1618 /// Sparse Conditional Constant Propagator.
1619 ///
1620 class SCCPLegacyPass : public FunctionPass {
1621 public:
1622   void getAnalysisUsage(AnalysisUsage &AU) const override {
1623     AU.addRequired<TargetLibraryInfoWrapperPass>();
1624     AU.addPreserved<GlobalsAAWrapperPass>();
1625   }
1626   static char ID; // Pass identification, replacement for typeid
1627   SCCPLegacyPass() : FunctionPass(ID) {
1628     initializeSCCPLegacyPassPass(*PassRegistry::getPassRegistry());
1629   }
1630 
1631   // runOnFunction - Run the Sparse Conditional Constant Propagation
1632   // algorithm, and return true if the function was modified.
1633   //
1634   bool runOnFunction(Function &F) override {
1635     if (skipFunction(F))
1636       return false;
1637     const DataLayout &DL = F.getParent()->getDataLayout();
1638     const TargetLibraryInfo *TLI =
1639         &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1640     return runSCCP(F, DL, TLI);
1641   }
1642 };
1643 } // end anonymous namespace
1644 
1645 char SCCPLegacyPass::ID = 0;
1646 INITIALIZE_PASS_BEGIN(SCCPLegacyPass, "sccp",
1647                       "Sparse Conditional Constant Propagation", false, false)
1648 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1649 INITIALIZE_PASS_END(SCCPLegacyPass, "sccp",
1650                     "Sparse Conditional Constant Propagation", false, false)
1651 
1652 // createSCCPPass - This is the public interface to this file.
1653 FunctionPass *llvm::createSCCPPass() { return new SCCPLegacyPass(); }
1654 
1655 static bool AddressIsTaken(const GlobalValue *GV) {
1656   // Delete any dead constantexpr klingons.
1657   GV->removeDeadConstantUsers();
1658 
1659   for (const Use &U : GV->uses()) {
1660     const User *UR = U.getUser();
1661     if (const auto *SI = dyn_cast<StoreInst>(UR)) {
1662       if (SI->getOperand(0) == GV || SI->isVolatile())
1663         return true;  // Storing addr of GV.
1664     } else if (isa<InvokeInst>(UR) || isa<CallInst>(UR)) {
1665       // Make sure we are calling the function, not passing the address.
1666       ImmutableCallSite CS(cast<Instruction>(UR));
1667       if (!CS.isCallee(&U))
1668         return true;
1669     } else if (const auto *LI = dyn_cast<LoadInst>(UR)) {
1670       if (LI->isVolatile())
1671         return true;
1672     } else if (isa<BlockAddress>(UR)) {
1673       // blockaddress doesn't take the address of the function, it takes addr
1674       // of label.
1675     } else {
1676       return true;
1677     }
1678   }
1679   return false;
1680 }
1681 
1682 static void findReturnsToZap(Function &F,
1683                              SmallPtrSet<Function *, 32> &AddressTakenFunctions,
1684                              SmallVector<ReturnInst *, 8> &ReturnsToZap) {
1685   // We can only do this if we know that nothing else can call the function.
1686   if (!F.hasLocalLinkage() || AddressTakenFunctions.count(&F))
1687     return;
1688 
1689   for (BasicBlock &BB : F)
1690     if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
1691       if (!isa<UndefValue>(RI->getOperand(0)))
1692         ReturnsToZap.push_back(RI);
1693 }
1694 
1695 static bool runIPSCCP(Module &M, const DataLayout &DL,
1696                       const TargetLibraryInfo *TLI) {
1697   SCCPSolver Solver(DL, TLI);
1698 
1699   // AddressTakenFunctions - This set keeps track of the address-taken functions
1700   // that are in the input.  As IPSCCP runs through and simplifies code,
1701   // functions that were address taken can end up losing their
1702   // address-taken-ness.  Because of this, we keep track of their addresses from
1703   // the first pass so we can use them for the later simplification pass.
1704   SmallPtrSet<Function*, 32> AddressTakenFunctions;
1705 
1706   // Loop over all functions, marking arguments to those with their addresses
1707   // taken or that are external as overdefined.
1708   //
1709   for (Function &F : M) {
1710     if (F.isDeclaration())
1711       continue;
1712 
1713     // If this is an exact definition of this function, then we can propagate
1714     // information about its result into callsites of it.
1715     if (F.hasExactDefinition())
1716       Solver.AddTrackedFunction(&F);
1717 
1718     // If this function only has direct calls that we can see, we can track its
1719     // arguments and return value aggressively, and can assume it is not called
1720     // unless we see evidence to the contrary.
1721     if (F.hasLocalLinkage()) {
1722       if (AddressIsTaken(&F))
1723         AddressTakenFunctions.insert(&F);
1724       else {
1725         Solver.AddArgumentTrackedFunction(&F);
1726         continue;
1727       }
1728     }
1729 
1730     // Assume the function is called.
1731     Solver.MarkBlockExecutable(&F.front());
1732 
1733     // Assume nothing about the incoming arguments.
1734     for (Argument &AI : F.args())
1735       Solver.markAnythingOverdefined(&AI);
1736   }
1737 
1738   // Loop over global variables.  We inform the solver about any internal global
1739   // variables that do not have their 'addresses taken'.  If they don't have
1740   // their addresses taken, we can propagate constants through them.
1741   for (GlobalVariable &G : M.globals())
1742     if (!G.isConstant() && G.hasLocalLinkage() && !AddressIsTaken(&G))
1743       Solver.TrackValueOfGlobalVariable(&G);
1744 
1745   // Solve for constants.
1746   bool ResolvedUndefs = true;
1747   while (ResolvedUndefs) {
1748     Solver.Solve();
1749 
1750     DEBUG(dbgs() << "RESOLVING UNDEFS\n");
1751     ResolvedUndefs = false;
1752     for (Function &F : M)
1753       ResolvedUndefs |= Solver.ResolvedUndefsIn(F);
1754   }
1755 
1756   bool MadeChanges = false;
1757 
1758   // Iterate over all of the instructions in the module, replacing them with
1759   // constants if we have found them to be of constant values.
1760   //
1761   SmallVector<BasicBlock*, 512> BlocksToErase;
1762 
1763   for (Function &F : M) {
1764     if (F.isDeclaration())
1765       continue;
1766 
1767     if (Solver.isBlockExecutable(&F.front())) {
1768       for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;
1769            ++AI) {
1770         if (AI->use_empty())
1771           continue;
1772         if (tryToReplaceWithConstant(Solver, &*AI))
1773           ++IPNumArgsElimed;
1774       }
1775     }
1776 
1777     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1778       if (!Solver.isBlockExecutable(&*BB)) {
1779         DEBUG(dbgs() << "  BasicBlock Dead:" << *BB);
1780 
1781         ++NumDeadBlocks;
1782         NumInstRemoved +=
1783             changeToUnreachable(BB->getFirstNonPHI(), /*UseLLVMTrap=*/false);
1784 
1785         MadeChanges = true;
1786 
1787         if (&*BB != &F.front())
1788           BlocksToErase.push_back(&*BB);
1789         continue;
1790       }
1791 
1792       for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1793         Instruction *Inst = &*BI++;
1794         if (Inst->getType()->isVoidTy())
1795           continue;
1796         if (tryToReplaceWithConstant(Solver, Inst)) {
1797           if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1798             Inst->eraseFromParent();
1799           // Hey, we just changed something!
1800           MadeChanges = true;
1801           ++IPNumInstRemoved;
1802         }
1803       }
1804     }
1805 
1806     // Now that all instructions in the function are constant folded, erase dead
1807     // blocks, because we can now use ConstantFoldTerminator to get rid of
1808     // in-edges.
1809     for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1810       // If there are any PHI nodes in this successor, drop entries for BB now.
1811       BasicBlock *DeadBB = BlocksToErase[i];
1812       for (Value::user_iterator UI = DeadBB->user_begin(),
1813                                 UE = DeadBB->user_end();
1814            UI != UE;) {
1815         // Grab the user and then increment the iterator early, as the user
1816         // will be deleted. Step past all adjacent uses from the same user.
1817         auto *I = dyn_cast<Instruction>(*UI);
1818         do { ++UI; } while (UI != UE && *UI == I);
1819 
1820         // Ignore blockaddress users; BasicBlock's dtor will handle them.
1821         if (!I) continue;
1822 
1823         bool Folded = ConstantFoldTerminator(I->getParent());
1824         if (!Folded) {
1825           // The constant folder may not have been able to fold the terminator
1826           // if this is a branch or switch on undef.  Fold it manually as a
1827           // branch to the first successor.
1828 #ifndef NDEBUG
1829           if (auto *BI = dyn_cast<BranchInst>(I)) {
1830             assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1831                    "Branch should be foldable!");
1832           } else if (auto *SI = dyn_cast<SwitchInst>(I)) {
1833             assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1834           } else {
1835             llvm_unreachable("Didn't fold away reference to block!");
1836           }
1837 #endif
1838 
1839           // Make this an uncond branch to the first successor.
1840           TerminatorInst *TI = I->getParent()->getTerminator();
1841           BranchInst::Create(TI->getSuccessor(0), TI);
1842 
1843           // Remove entries in successor phi nodes to remove edges.
1844           for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1845             TI->getSuccessor(i)->removePredecessor(TI->getParent());
1846 
1847           // Remove the old terminator.
1848           TI->eraseFromParent();
1849         }
1850       }
1851 
1852       // Finally, delete the basic block.
1853       F.getBasicBlockList().erase(DeadBB);
1854     }
1855     BlocksToErase.clear();
1856   }
1857 
1858   // If we inferred constant or undef return values for a function, we replaced
1859   // all call uses with the inferred value.  This means we don't need to bother
1860   // actually returning anything from the function.  Replace all return
1861   // instructions with return undef.
1862   //
1863   // Do this in two stages: first identify the functions we should process, then
1864   // actually zap their returns.  This is important because we can only do this
1865   // if the address of the function isn't taken.  In cases where a return is the
1866   // last use of a function, the order of processing functions would affect
1867   // whether other functions are optimizable.
1868   SmallVector<ReturnInst*, 8> ReturnsToZap;
1869 
1870   const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
1871   for (const auto &I : RV) {
1872     Function *F = I.first;
1873     if (I.second.isOverdefined() || F->getReturnType()->isVoidTy())
1874       continue;
1875     findReturnsToZap(*F, AddressTakenFunctions, ReturnsToZap);
1876   }
1877 
1878   for (const auto &F : Solver.getMRVFunctionsTracked()) {
1879     assert(F->getReturnType()->isStructTy() &&
1880            "The return type should be a struct");
1881     StructType *STy = cast<StructType>(F->getReturnType());
1882     if (Solver.isStructLatticeConstant(F, STy))
1883       findReturnsToZap(*F, AddressTakenFunctions, ReturnsToZap);
1884   }
1885 
1886   // Zap all returns which we've identified as zap to change.
1887   for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
1888     Function *F = ReturnsToZap[i]->getParent()->getParent();
1889     ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
1890   }
1891 
1892   // If we inferred constant or undef values for globals variables, we can
1893   // delete the global and any stores that remain to it.
1894   const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1895   for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1896          E = TG.end(); I != E; ++I) {
1897     GlobalVariable *GV = I->first;
1898     assert(!I->second.isOverdefined() &&
1899            "Overdefined values should have been taken out of the map!");
1900     DEBUG(dbgs() << "Found that GV '" << GV->getName() << "' is constant!\n");
1901     while (!GV->use_empty()) {
1902       StoreInst *SI = cast<StoreInst>(GV->user_back());
1903       SI->eraseFromParent();
1904     }
1905     M.getGlobalList().erase(GV);
1906     ++IPNumGlobalConst;
1907   }
1908 
1909   return MadeChanges;
1910 }
1911 
1912 PreservedAnalyses IPSCCPPass::run(Module &M, ModuleAnalysisManager &AM) {
1913   const DataLayout &DL = M.getDataLayout();
1914   auto &TLI = AM.getResult<TargetLibraryAnalysis>(M);
1915   if (!runIPSCCP(M, DL, &TLI))
1916     return PreservedAnalyses::all();
1917   return PreservedAnalyses::none();
1918 }
1919 
1920 namespace {
1921 //===--------------------------------------------------------------------===//
1922 //
1923 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1924 /// Constant Propagation.
1925 ///
1926 class IPSCCPLegacyPass : public ModulePass {
1927 public:
1928   static char ID;
1929 
1930   IPSCCPLegacyPass() : ModulePass(ID) {
1931     initializeIPSCCPLegacyPassPass(*PassRegistry::getPassRegistry());
1932   }
1933 
1934   bool runOnModule(Module &M) override {
1935     if (skipModule(M))
1936       return false;
1937     const DataLayout &DL = M.getDataLayout();
1938     const TargetLibraryInfo *TLI =
1939         &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1940     return runIPSCCP(M, DL, TLI);
1941   }
1942 
1943   void getAnalysisUsage(AnalysisUsage &AU) const override {
1944     AU.addRequired<TargetLibraryInfoWrapperPass>();
1945   }
1946 };
1947 } // end anonymous namespace
1948 
1949 char IPSCCPLegacyPass::ID = 0;
1950 INITIALIZE_PASS_BEGIN(IPSCCPLegacyPass, "ipsccp",
1951                       "Interprocedural Sparse Conditional Constant Propagation",
1952                       false, false)
1953 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1954 INITIALIZE_PASS_END(IPSCCPLegacyPass, "ipsccp",
1955                     "Interprocedural Sparse Conditional Constant Propagation",
1956                     false, false)
1957 
1958 // createIPSCCPPass - This is the public interface to this file.
1959 ModulePass *llvm::createIPSCCPPass() { return new IPSCCPLegacyPass(); }
1960