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