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