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