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