Convert code to compile with vc7.1.
[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 was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 #include "llvm/Transforms/Scalar.h"
25 #include "llvm/Constants.h"
26 #include "llvm/Function.h"
27 #include "llvm/GlobalVariable.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Pass.h"
30 #include "llvm/Type.h"
31 #include "llvm/Support/InstVisitor.h"
32 #include "llvm/Transforms/Utils/Local.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/ADT/hash_map"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include <algorithm>
38 #include <set>
39 using namespace llvm;
40
41 // InstVal class - This class represents the different lattice values that an 
42 // instruction may occupy.  It is a simple class with value semantics.
43 //
44 namespace {
45   Statistic<> NumInstRemoved("sccp", "Number of instructions removed");
46
47 class InstVal {
48   enum { 
49     undefined,           // This instruction has no known value
50     constant,            // This instruction has a constant value
51     overdefined          // This instruction has an unknown value
52   } LatticeValue;        // The current lattice position
53   Constant *ConstantVal; // If Constant value, the current value
54 public:
55   inline InstVal() : LatticeValue(undefined), ConstantVal(0) {}
56
57   // markOverdefined - Return true if this is a new status to be in...
58   inline bool markOverdefined() {
59     if (LatticeValue != overdefined) {
60       LatticeValue = overdefined;
61       return true;
62     }
63     return false;
64   }
65
66   // markConstant - Return true if this is a new status for us...
67   inline bool markConstant(Constant *V) {
68     if (LatticeValue != constant) {
69       LatticeValue = constant;
70       ConstantVal = V;
71       return true;
72     } else {
73       assert(ConstantVal == V && "Marking constant with different value");
74     }
75     return false;
76   }
77
78   inline bool isUndefined()   const { return LatticeValue == undefined; }
79   inline bool isConstant()    const { return LatticeValue == constant; }
80   inline bool isOverdefined() const { return LatticeValue == overdefined; }
81
82   inline Constant *getConstant() const {
83     assert(isConstant() && "Cannot get the constant of a non-constant!");
84     return ConstantVal;
85   }
86 };
87
88 } // end anonymous namespace
89
90
91 //===----------------------------------------------------------------------===//
92 // SCCP Class
93 //
94 // This class does all of the work of Sparse Conditional Constant Propagation.
95 //
96 namespace {
97 class SCCP : public FunctionPass, public InstVisitor<SCCP> {
98   std::set<BasicBlock*>     BBExecutable;// The basic blocks that are executable
99   hash_map<Value*, InstVal> ValueState;  // The state each value is in...
100
101   // The reason for two worklists is that overdefined is the lowest state
102   // on the lattice, and moving things to overdefined as fast as possible
103   // makes SCCP converge much faster.
104   // By having a separate worklist, we accomplish this because everything
105   // possibly overdefined will become overdefined at the soonest possible
106   // point.
107   std::vector<Instruction*> OverdefinedInstWorkList;// The overdefined 
108                                                     // instruction work list
109   std::vector<Instruction*> InstWorkList;// The instruction work list
110
111
112   std::vector<BasicBlock*>  BBWorkList;  // The BasicBlock work list
113
114   /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
115   /// overdefined, despite the fact that the PHI node is overdefined.
116   std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
117
118   /// KnownFeasibleEdges - Entries in this set are edges which have already had
119   /// PHI nodes retriggered.
120   typedef std::pair<BasicBlock*,BasicBlock*> Edge;
121   std::set<Edge> KnownFeasibleEdges;
122 public:
123
124   // runOnFunction - Run the Sparse Conditional Constant Propagation algorithm,
125   // and return true if the function was modified.
126   //
127   bool runOnFunction(Function &F);
128
129   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
130     AU.setPreservesCFG();
131   }
132
133
134   //===--------------------------------------------------------------------===//
135   // The implementation of this class
136   //
137 private:
138   friend class InstVisitor<SCCP>;        // Allow callbacks from visitor
139
140   // markConstant - Make a value be marked as "constant".  If the value
141   // is not already a constant, add it to the instruction work list so that 
142   // the users of the instruction are updated later.
143   //
144   inline void markConstant(InstVal &IV, Instruction *I, Constant *C) {
145     if (IV.markConstant(C)) {
146       DEBUG(std::cerr << "markConstant: " << *C << ": " << *I);
147       InstWorkList.push_back(I);
148     }
149   }
150   inline void markConstant(Instruction *I, Constant *C) {
151     markConstant(ValueState[I], I, C);
152   }
153
154   // markOverdefined - Make a value be marked as "overdefined". If the
155   // value is not already overdefined, add it to the overdefined instruction 
156   // work list so that the users of the instruction are updated later.
157   
158   inline void markOverdefined(InstVal &IV, Instruction *I) {
159     if (IV.markOverdefined()) {
160       DEBUG(std::cerr << "markOverdefined: " << *I);
161       OverdefinedInstWorkList.push_back(I);  // Only instructions go on the work list
162     }
163   }
164   inline void markOverdefined(Instruction *I) {
165     markOverdefined(ValueState[I], I);
166   }
167
168   // getValueState - Return the InstVal object that corresponds to the value.
169   // This function is necessary because not all values should start out in the
170   // underdefined state... Argument's should be overdefined, and
171   // constants should be marked as constants.  If a value is not known to be an
172   // Instruction object, then use this accessor to get its value from the map.
173   //
174   inline InstVal &getValueState(Value *V) {
175     hash_map<Value*, InstVal>::iterator I = ValueState.find(V);
176     if (I != ValueState.end()) return I->second;  // Common case, in the map
177       
178     if (Constant *CPV = dyn_cast<Constant>(V)) {  // Constants are constant
179       ValueState[CPV].markConstant(CPV);
180     } else if (isa<Argument>(V)) {                // Arguments are overdefined
181       ValueState[V].markOverdefined();
182     }
183     // All others are underdefined by default...
184     return ValueState[V];
185   }
186
187   // markEdgeExecutable - Mark a basic block as executable, adding it to the BB 
188   // work list if it is not already executable...
189   // 
190   void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
191     if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
192       return;  // This edge is already known to be executable!
193
194     if (BBExecutable.count(Dest)) {
195       DEBUG(std::cerr << "Marking Edge Executable: " << Source->getName()
196                       << " -> " << Dest->getName() << "\n");
197
198       // The destination is already executable, but we just made an edge
199       // feasible that wasn't before.  Revisit the PHI nodes in the block
200       // because they have potentially new operands.
201       for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I) {
202         PHINode *PN = cast<PHINode>(I);
203         visitPHINode(*PN);
204       }
205
206     } else {
207       DEBUG(std::cerr << "Marking Block Executable: " << Dest->getName()<<"\n");
208       BBExecutable.insert(Dest);   // Basic block is executable!
209       BBWorkList.push_back(Dest);  // Add the block to the work list!
210     }
211   }
212
213
214   // visit implementations - Something changed in this instruction... Either an 
215   // operand made a transition, or the instruction is newly executable.  Change
216   // the value type of I to reflect these changes if appropriate.
217   //
218   void visitPHINode(PHINode &I);
219
220   // Terminators
221   void visitReturnInst(ReturnInst &I) { /*does not have an effect*/ }
222   void visitTerminatorInst(TerminatorInst &TI);
223
224   void visitCastInst(CastInst &I);
225   void visitSelectInst(SelectInst &I);
226   void visitBinaryOperator(Instruction &I);
227   void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
228
229   // Instructions that cannot be folded away...
230   void visitStoreInst     (Instruction &I) { /*returns void*/ }
231   void visitLoadInst      (LoadInst &I);
232   void visitGetElementPtrInst(GetElementPtrInst &I);
233   void visitCallInst      (CallInst &I);
234   void visitInvokeInst    (TerminatorInst &I) {
235     if (I.getType() != Type::VoidTy) markOverdefined(&I);
236     visitTerminatorInst(I);
237   }
238   void visitUnwindInst    (TerminatorInst &I) { /*returns void*/ }
239   void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
240   void visitVANextInst    (Instruction &I) { markOverdefined(&I); }
241   void visitVAArgInst     (Instruction &I) { markOverdefined(&I); }
242   void visitFreeInst      (Instruction &I) { /*returns void*/ }
243
244   void visitInstruction(Instruction &I) {
245     // If a new instruction is added to LLVM that we don't handle...
246     std::cerr << "SCCP: Don't know how to handle: " << I;
247     markOverdefined(&I);   // Just in case
248   }
249
250   // getFeasibleSuccessors - Return a vector of booleans to indicate which
251   // successors are reachable from a given terminator instruction.
252   //
253   void getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs);
254
255   // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
256   // block to the 'To' basic block is currently feasible...
257   //
258   bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
259
260   // OperandChangedState - This method is invoked on all of the users of an
261   // instruction that was just changed state somehow....  Based on this
262   // information, we need to update the specified user of this instruction.
263   //
264   void OperandChangedState(User *U) {
265     // Only instructions use other variable values!
266     Instruction &I = cast<Instruction>(*U);
267     if (BBExecutable.count(I.getParent()))   // Inst is executable?
268       visit(I);
269   }
270 };
271
272   RegisterOpt<SCCP> X("sccp", "Sparse Conditional Constant Propagation");
273 } // end anonymous namespace
274
275
276 // createSCCPPass - This is the public interface to this file...
277 Pass *llvm::createSCCPPass() {
278   return new SCCP();
279 }
280
281
282 //===----------------------------------------------------------------------===//
283 // SCCP Class Implementation
284
285
286 // runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
287 // and return true if the function was modified.
288 //
289 bool SCCP::runOnFunction(Function &F) {
290   // Mark the first block of the function as being executable...
291   BBExecutable.insert(F.begin());   // Basic block is executable!
292   BBWorkList.push_back(F.begin());  // Add the block to the work list!
293
294   // Process the work lists until they are empty!
295   while (!BBWorkList.empty() || !InstWorkList.empty() || 
296          !OverdefinedInstWorkList.empty()) {
297     // Process the instruction work list...
298     while (!OverdefinedInstWorkList.empty()) {
299       Instruction *I = OverdefinedInstWorkList.back();
300       OverdefinedInstWorkList.pop_back();
301
302       DEBUG(std::cerr << "\nPopped off OI-WL: " << I);
303       
304       // "I" got into the work list because it either made the transition from
305       // bottom to constant
306       //
307       // Anything on this worklist that is overdefined need not be visited
308       // since all of its users will have already been marked as overdefined
309       // Update all of the users of this instruction's value...
310       //
311       for_each(I->use_begin(), I->use_end(),
312                bind_obj(this, &SCCP::OperandChangedState));
313     }
314     // Process the instruction work list...
315     while (!InstWorkList.empty()) {
316       Instruction *I = InstWorkList.back();
317       InstWorkList.pop_back();
318
319       DEBUG(std::cerr << "\nPopped off I-WL: " << *I);
320       
321       // "I" got into the work list because it either made the transition from
322       // bottom to constant
323       //
324       // Anything on this worklist that is overdefined need not be visited
325       // since all of its users will have already been marked as overdefined.
326       // Update all of the users of this instruction's value...
327       //
328       InstVal &Ival = getValueState (I);
329       if (!Ival.isOverdefined())
330         for_each(I->use_begin(), I->use_end(),
331                  bind_obj(this, &SCCP::OperandChangedState));
332     }
333
334     // Process the basic block work list...
335     while (!BBWorkList.empty()) {
336       BasicBlock *BB = BBWorkList.back();
337       BBWorkList.pop_back();
338
339       DEBUG(std::cerr << "\nPopped off BBWL: " << *BB);
340
341       // Notify all instructions in this basic block that they are newly
342       // executable.
343       visit(BB);
344     }
345   }
346
347   if (DebugFlag) {
348     for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
349       if (!BBExecutable.count(I))
350         std::cerr << "BasicBlock Dead:" << *I;
351   }
352
353   // Iterate over all of the instructions in a function, replacing them with
354   // constants if we have found them to be of constant values.
355   //
356   bool MadeChanges = false;
357   for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
358     for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
359       Instruction &Inst = *BI;
360       InstVal &IV = ValueState[&Inst];
361       if (IV.isConstant()) {
362         Constant *Const = IV.getConstant();
363         DEBUG(std::cerr << "Constant: " << *Const << " = " << Inst);
364
365         // Replaces all of the uses of a variable with uses of the constant.
366         Inst.replaceAllUsesWith(Const);
367
368         // Remove the operator from the list of definitions... and delete it.
369         BI = BB->getInstList().erase(BI);
370
371         // Hey, we just changed something!
372         MadeChanges = true;
373         ++NumInstRemoved;
374       } else {
375         ++BI;
376       }
377     }
378
379   // Reset state so that the next invocation will have empty data structures
380   BBExecutable.clear();
381   ValueState.clear();
382   std::vector<Instruction*>().swap(OverdefinedInstWorkList);
383   std::vector<Instruction*>().swap(InstWorkList);
384   std::vector<BasicBlock*>().swap(BBWorkList);
385
386   return MadeChanges;
387 }
388
389
390 // getFeasibleSuccessors - Return a vector of booleans to indicate which
391 // successors are reachable from a given terminator instruction.
392 //
393 void SCCP::getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs) {
394   Succs.resize(TI.getNumSuccessors());
395   if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
396     if (BI->isUnconditional()) {
397       Succs[0] = true;
398     } else {
399       InstVal &BCValue = getValueState(BI->getCondition());
400       if (BCValue.isOverdefined() ||
401           (BCValue.isConstant() && !isa<ConstantBool>(BCValue.getConstant()))) {
402         // Overdefined condition variables, and branches on unfoldable constant
403         // conditions, mean the branch could go either way.
404         Succs[0] = Succs[1] = true;
405       } else if (BCValue.isConstant()) {
406         // Constant condition variables mean the branch can only go a single way
407         Succs[BCValue.getConstant() == ConstantBool::False] = true;
408       }
409     }
410   } else if (InvokeInst *II = dyn_cast<InvokeInst>(&TI)) {
411     // Invoke instructions successors are always executable.
412     Succs[0] = Succs[1] = true;
413   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
414     InstVal &SCValue = getValueState(SI->getCondition());
415     if (SCValue.isOverdefined() ||   // Overdefined condition?
416         (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
417       // All destinations are executable!
418       Succs.assign(TI.getNumSuccessors(), true);
419     } else if (SCValue.isConstant()) {
420       Constant *CPV = SCValue.getConstant();
421       // Make sure to skip the "default value" which isn't a value
422       for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
423         if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
424           Succs[i] = true;
425           return;
426         }
427       }
428
429       // Constant value not equal to any of the branches... must execute
430       // default branch then...
431       Succs[0] = true;
432     }
433   } else {
434     std::cerr << "SCCP: Don't know how to handle: " << TI;
435     Succs.assign(TI.getNumSuccessors(), true);
436   }
437 }
438
439
440 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
441 // block to the 'To' basic block is currently feasible...
442 //
443 bool SCCP::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
444   assert(BBExecutable.count(To) && "Dest should always be alive!");
445
446   // Make sure the source basic block is executable!!
447   if (!BBExecutable.count(From)) return false;
448   
449   // Check to make sure this edge itself is actually feasible now...
450   TerminatorInst *TI = From->getTerminator();
451   if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
452     if (BI->isUnconditional())
453       return true;
454     else {
455       InstVal &BCValue = getValueState(BI->getCondition());
456       if (BCValue.isOverdefined()) {
457         // Overdefined condition variables mean the branch could go either way.
458         return true;
459       } else if (BCValue.isConstant()) {
460         // Not branching on an evaluatable constant?
461         if (!isa<ConstantBool>(BCValue.getConstant())) return true;
462
463         // Constant condition variables mean the branch can only go a single way
464         return BI->getSuccessor(BCValue.getConstant() == 
465                                        ConstantBool::False) == To;
466       }
467       return false;
468     }
469   } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
470     // Invoke instructions successors are always executable.
471     return true;
472   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
473     InstVal &SCValue = getValueState(SI->getCondition());
474     if (SCValue.isOverdefined()) {  // Overdefined condition?
475       // All destinations are executable!
476       return true;
477     } else if (SCValue.isConstant()) {
478       Constant *CPV = SCValue.getConstant();
479       if (!isa<ConstantInt>(CPV))
480         return true;  // not a foldable constant?
481
482       // Make sure to skip the "default value" which isn't a value
483       for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
484         if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
485           return SI->getSuccessor(i) == To;
486
487       // Constant value not equal to any of the branches... must execute
488       // default branch then...
489       return SI->getDefaultDest() == To;
490     }
491     return false;
492   } else {
493     std::cerr << "Unknown terminator instruction: " << *TI;
494     abort();
495   }
496 }
497
498 // visit Implementations - Something changed in this instruction... Either an
499 // operand made a transition, or the instruction is newly executable.  Change
500 // the value type of I to reflect these changes if appropriate.  This method
501 // makes sure to do the following actions:
502 //
503 // 1. If a phi node merges two constants in, and has conflicting value coming
504 //    from different branches, or if the PHI node merges in an overdefined
505 //    value, then the PHI node becomes overdefined.
506 // 2. If a phi node merges only constants in, and they all agree on value, the
507 //    PHI node becomes a constant value equal to that.
508 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
509 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
510 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
511 // 6. If a conditional branch has a value that is constant, make the selected
512 //    destination executable
513 // 7. If a conditional branch has a value that is overdefined, make all
514 //    successors executable.
515 //
516 void SCCP::visitPHINode(PHINode &PN) {
517   InstVal &PNIV = getValueState(&PN);
518   if (PNIV.isOverdefined()) {
519     // There may be instructions using this PHI node that are not overdefined
520     // themselves.  If so, make sure that they know that the PHI node operand
521     // changed.
522     std::multimap<PHINode*, Instruction*>::iterator I, E;
523     tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
524     if (I != E) {
525       std::vector<Instruction*> Users;
526       Users.reserve(std::distance(I, E));
527       for (; I != E; ++I) Users.push_back(I->second);
528       while (!Users.empty()) {
529         visit(Users.back());
530         Users.pop_back();
531       }
532     }
533     return;  // Quick exit
534   }
535
536   // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
537   // and slow us down a lot.  Just mark them overdefined.
538   if (PN.getNumIncomingValues() > 64) {
539     markOverdefined(PNIV, &PN);
540     return;
541   }
542
543   // Look at all of the executable operands of the PHI node.  If any of them
544   // are overdefined, the PHI becomes overdefined as well.  If they are all
545   // constant, and they agree with each other, the PHI becomes the identical
546   // constant.  If they are constant and don't agree, the PHI is overdefined.
547   // If there are no executable operands, the PHI remains undefined.
548   //
549   Constant *OperandVal = 0;
550   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
551     InstVal &IV = getValueState(PN.getIncomingValue(i));
552     if (IV.isUndefined()) continue;  // Doesn't influence PHI node.
553     
554     if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
555       if (IV.isOverdefined()) {   // PHI node becomes overdefined!
556         markOverdefined(PNIV, &PN);
557         return;
558       }
559
560       if (OperandVal == 0) {   // Grab the first value...
561         OperandVal = IV.getConstant();
562       } else {                // Another value is being merged in!
563         // There is already a reachable operand.  If we conflict with it,
564         // then the PHI node becomes overdefined.  If we agree with it, we
565         // can continue on.
566         
567         // Check to see if there are two different constants merging...
568         if (IV.getConstant() != OperandVal) {
569           // Yes there is.  This means the PHI node is not constant.
570           // You must be overdefined poor PHI.
571           //
572           markOverdefined(PNIV, &PN);    // The PHI node now becomes overdefined
573           return;    // I'm done analyzing you
574         }
575       }
576     }
577   }
578
579   // If we exited the loop, this means that the PHI node only has constant
580   // arguments that agree with each other(and OperandVal is the constant) or
581   // OperandVal is null because there are no defined incoming arguments.  If
582   // this is the case, the PHI remains undefined.
583   //
584   if (OperandVal)
585     markConstant(PNIV, &PN, OperandVal);      // Acquire operand value
586 }
587
588 void SCCP::visitTerminatorInst(TerminatorInst &TI) {
589   std::vector<bool> SuccFeasible;
590   getFeasibleSuccessors(TI, SuccFeasible);
591
592   BasicBlock *BB = TI.getParent();
593
594   // Mark all feasible successors executable...
595   for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
596     if (SuccFeasible[i])
597       markEdgeExecutable(BB, TI.getSuccessor(i));
598 }
599
600 void SCCP::visitCastInst(CastInst &I) {
601   Value *V = I.getOperand(0);
602   InstVal &VState = getValueState(V);
603   if (VState.isOverdefined())          // Inherit overdefinedness of operand
604     markOverdefined(&I);
605   else if (VState.isConstant())        // Propagate constant value
606     markConstant(&I, ConstantExpr::getCast(VState.getConstant(), I.getType()));
607 }
608
609 void SCCP::visitSelectInst(SelectInst &I) {
610   InstVal &CondValue = getValueState(I.getCondition());
611   if (CondValue.isOverdefined())
612     markOverdefined(&I);
613   else if (CondValue.isConstant()) {
614     if (CondValue.getConstant() == ConstantBool::True) {
615       InstVal &Val = getValueState(I.getTrueValue());
616       if (Val.isOverdefined())
617         markOverdefined(&I);
618       else if (Val.isConstant())
619         markConstant(&I, Val.getConstant());
620     } else if (CondValue.getConstant() == ConstantBool::False) {
621       InstVal &Val = getValueState(I.getFalseValue());
622       if (Val.isOverdefined())
623         markOverdefined(&I);
624       else if (Val.isConstant())
625         markConstant(&I, Val.getConstant());
626     } else
627       markOverdefined(&I);
628   }
629 }
630
631 // Handle BinaryOperators and Shift Instructions...
632 void SCCP::visitBinaryOperator(Instruction &I) {
633   InstVal &IV = ValueState[&I];
634   if (IV.isOverdefined()) return;
635
636   InstVal &V1State = getValueState(I.getOperand(0));
637   InstVal &V2State = getValueState(I.getOperand(1));
638
639   if (V1State.isOverdefined() || V2State.isOverdefined()) {
640     // If both operands are PHI nodes, it is possible that this instruction has
641     // a constant value, despite the fact that the PHI node doesn't.  Check for
642     // this condition now.
643     if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
644       if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
645         if (PN1->getParent() == PN2->getParent()) {
646           // Since the two PHI nodes are in the same basic block, they must have
647           // entries for the same predecessors.  Walk the predecessor list, and
648           // if all of the incoming values are constants, and the result of
649           // evaluating this expression with all incoming value pairs is the
650           // same, then this expression is a constant even though the PHI node
651           // is not a constant!
652           InstVal Result;
653           for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
654             InstVal &In1 = getValueState(PN1->getIncomingValue(i));
655             BasicBlock *InBlock = PN1->getIncomingBlock(i);
656             InstVal &In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
657
658             if (In1.isOverdefined() || In2.isOverdefined()) {
659               Result.markOverdefined();
660               break;  // Cannot fold this operation over the PHI nodes!
661             } else if (In1.isConstant() && In2.isConstant()) {
662               Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
663                                               In2.getConstant());
664               if (Result.isUndefined())
665                 Result.markConstant(V);
666               else if (Result.isConstant() && Result.getConstant() != V) {
667                 Result.markOverdefined();
668                 break;
669               }
670             }
671           }
672
673           // If we found a constant value here, then we know the instruction is
674           // constant despite the fact that the PHI nodes are overdefined.
675           if (Result.isConstant()) {
676             markConstant(IV, &I, Result.getConstant());
677             // Remember that this instruction is virtually using the PHI node
678             // operands.
679             UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
680             UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
681             return;
682           } else if (Result.isUndefined()) {
683             return;
684           }
685
686           // Okay, this really is overdefined now.  Since we might have
687           // speculatively thought that this was not overdefined before, and
688           // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
689           // make sure to clean out any entries that we put there, for
690           // efficiency.
691           std::multimap<PHINode*, Instruction*>::iterator It, E;
692           tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
693           while (It != E) {
694             if (It->second == &I) {
695               UsersOfOverdefinedPHIs.erase(It++);
696             } else
697               ++It;
698           }
699           tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
700           while (It != E) {
701             if (It->second == &I) {
702               UsersOfOverdefinedPHIs.erase(It++);
703             } else
704               ++It;
705           }
706         }
707
708     markOverdefined(IV, &I);
709   } else if (V1State.isConstant() && V2State.isConstant()) {
710     markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
711                                            V2State.getConstant()));
712   }
713 }
714
715 // Handle getelementptr instructions... if all operands are constants then we
716 // can turn this into a getelementptr ConstantExpr.
717 //
718 void SCCP::visitGetElementPtrInst(GetElementPtrInst &I) {
719   InstVal &IV = ValueState[&I];
720   if (IV.isOverdefined()) return;
721
722   std::vector<Constant*> Operands;
723   Operands.reserve(I.getNumOperands());
724
725   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
726     InstVal &State = getValueState(I.getOperand(i));
727     if (State.isUndefined())
728       return;  // Operands are not resolved yet...
729     else if (State.isOverdefined()) {
730       markOverdefined(IV, &I);
731       return;
732     }
733     assert(State.isConstant() && "Unknown state!");
734     Operands.push_back(State.getConstant());
735   }
736
737   Constant *Ptr = Operands[0];
738   Operands.erase(Operands.begin());  // Erase the pointer from idx list...
739
740   markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, Operands));  
741 }
742
743 /// GetGEPGlobalInitializer - Given a constant and a getelementptr constantexpr,
744 /// return the constant value being addressed by the constant expression, or
745 /// null if something is funny.
746 ///
747 static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
748   if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
749     return 0;  // Do not allow stepping over the value!
750
751   // Loop over all of the operands, tracking down which value we are
752   // addressing...
753   for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
754     if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
755       ConstantStruct *CS = dyn_cast<ConstantStruct>(C);
756       if (CS == 0) return 0;
757       if (CU->getValue() >= CS->getNumOperands()) return 0;
758       C = CS->getOperand(CU->getValue());
759     } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
760       ConstantArray *CA = dyn_cast<ConstantArray>(C);
761       if (CA == 0) return 0;
762       if ((uint64_t)CS->getValue() >= CA->getNumOperands()) return 0;
763       C = CA->getOperand(CS->getValue());
764     } else
765       return 0;
766   return C;
767 }
768
769 // Handle load instructions.  If the operand is a constant pointer to a constant
770 // global, we can replace the load with the loaded constant value!
771 void SCCP::visitLoadInst(LoadInst &I) {
772   InstVal &IV = ValueState[&I];
773   if (IV.isOverdefined()) return;
774
775   InstVal &PtrVal = getValueState(I.getOperand(0));
776   if (PtrVal.isUndefined()) return;   // The pointer is not resolved yet!
777   if (PtrVal.isConstant() && !I.isVolatile()) {
778     Value *Ptr = PtrVal.getConstant();
779     if (isa<ConstantPointerNull>(Ptr)) {
780       // load null -> null
781       markConstant(IV, &I, Constant::getNullValue(I.getType()));
782       return;
783     }
784       
785     // Transform load (constant global) into the value loaded.
786     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr))
787       if (GV->isConstant() && !GV->isExternal()) {
788         markConstant(IV, &I, GV->getInitializer());
789         return;
790       }
791
792     // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
793     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
794       if (CE->getOpcode() == Instruction::GetElementPtr)
795         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
796           if (GV->isConstant() && !GV->isExternal())
797             if (Constant *V = 
798                 GetGEPGlobalInitializer(GV->getInitializer(), CE)) {
799               markConstant(IV, &I, V);
800               return;
801             }
802   }
803
804   // Otherwise we cannot say for certain what value this load will produce.
805   // Bail out.
806   markOverdefined(IV, &I);
807 }
808
809 void SCCP::visitCallInst(CallInst &I) {
810   InstVal &IV = ValueState[&I];
811   if (IV.isOverdefined()) return;
812
813   Function *F = I.getCalledFunction();
814   if (F == 0 || !canConstantFoldCallTo(F)) {
815     markOverdefined(IV, &I);
816     return;
817   }
818
819   std::vector<Constant*> Operands;
820   Operands.reserve(I.getNumOperands()-1);
821
822   for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
823     InstVal &State = getValueState(I.getOperand(i));
824     if (State.isUndefined())
825       return;  // Operands are not resolved yet...
826     else if (State.isOverdefined()) {
827       markOverdefined(IV, &I);
828       return;
829     }
830     assert(State.isConstant() && "Unknown state!");
831     Operands.push_back(State.getConstant());
832   }
833
834   if (Constant *C = ConstantFoldCall(F, Operands))
835     markConstant(IV, &I, C);
836   else
837     markOverdefined(IV, &I);
838 }