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