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