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