Invoke SimplifyIndVar when we partially unroll a loop. Fixes PR10534.
[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 is distributed under the University of Illinois Open Source
6 // 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 //===----------------------------------------------------------------------===//
19
20 #define DEBUG_TYPE "sccp"
21 #include "llvm/Transforms/Scalar.h"
22 #include "llvm/Transforms/IPO.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Analysis/ConstantFolding.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/Transforms/Utils/Local.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Support/CallSite.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/InstVisitor.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/ADT/DenseMap.h"
37 #include "llvm/ADT/DenseSet.h"
38 #include "llvm/ADT/PointerIntPair.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/SmallVector.h"
41 #include "llvm/ADT/Statistic.h"
42 #include "llvm/ADT/STLExtras.h"
43 #include <algorithm>
44 #include <map>
45 using namespace llvm;
46
47 STATISTIC(NumInstRemoved, "Number of instructions removed");
48 STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
49
50 STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
51 STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
52 STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
53
54 namespace {
55 /// LatticeVal class - This class represents the different lattice values that
56 /// an LLVM value may occupy.  It is a simple class with value semantics.
57 ///
58 class LatticeVal {
59   enum LatticeValueTy {
60     /// undefined - This LLVM Value has no known value yet.
61     undefined,
62     
63     /// constant - This LLVM Value has a specific constant value.
64     constant,
65
66     /// forcedconstant - This LLVM Value was thought to be undef until
67     /// ResolvedUndefsIn.  This is treated just like 'constant', but if merged
68     /// with another (different) constant, it goes to overdefined, instead of
69     /// asserting.
70     forcedconstant,
71     
72     /// overdefined - This instruction is not known to be constant, and we know
73     /// it has a value.
74     overdefined
75   };
76
77   /// Val: This stores the current lattice value along with the Constant* for
78   /// the constant if this is a 'constant' or 'forcedconstant' value.
79   PointerIntPair<Constant *, 2, LatticeValueTy> Val;
80   
81   LatticeValueTy getLatticeValue() const {
82     return Val.getInt();
83   }
84   
85 public:
86   LatticeVal() : Val(0, undefined) {}
87   
88   bool isUndefined() const { return getLatticeValue() == undefined; }
89   bool isConstant() const {
90     return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
91   }
92   bool isOverdefined() const { return getLatticeValue() == overdefined; }
93   
94   Constant *getConstant() const {
95     assert(isConstant() && "Cannot get the constant of a non-constant!");
96     return Val.getPointer();
97   }
98   
99   /// markOverdefined - Return true if this is a change in status.
100   bool markOverdefined() {
101     if (isOverdefined())
102       return false;
103     
104     Val.setInt(overdefined);
105     return true;
106   }
107
108   /// markConstant - Return true if this is a change in status.
109   bool markConstant(Constant *V) {
110     if (getLatticeValue() == constant) { // Constant but not forcedconstant.
111       assert(getConstant() == V && "Marking constant with different value");
112       return false;
113     }
114     
115     if (isUndefined()) {
116       Val.setInt(constant);
117       assert(V && "Marking constant with NULL");
118       Val.setPointer(V);
119     } else {
120       assert(getLatticeValue() == forcedconstant && 
121              "Cannot move from overdefined to constant!");
122       // Stay at forcedconstant if the constant is the same.
123       if (V == getConstant()) return false;
124       
125       // Otherwise, we go to overdefined.  Assumptions made based on the
126       // forced value are possibly wrong.  Assuming this is another constant
127       // could expose a contradiction.
128       Val.setInt(overdefined);
129     }
130     return true;
131   }
132
133   /// getConstantInt - If this is a constant with a ConstantInt value, return it
134   /// otherwise return null.
135   ConstantInt *getConstantInt() const {
136     if (isConstant())
137       return dyn_cast<ConstantInt>(getConstant());
138     return 0;
139   }
140   
141   void markForcedConstant(Constant *V) {
142     assert(isUndefined() && "Can't force a defined value!");
143     Val.setInt(forcedconstant);
144     Val.setPointer(V);
145   }
146 };
147 } // end anonymous namespace.
148
149
150 namespace {
151
152 //===----------------------------------------------------------------------===//
153 //
154 /// SCCPSolver - This class is a general purpose solver for Sparse Conditional
155 /// Constant Propagation.
156 ///
157 class SCCPSolver : public InstVisitor<SCCPSolver> {
158   const TargetData *TD;
159   SmallPtrSet<BasicBlock*, 8> BBExecutable; // The BBs that are executable.
160   DenseMap<Value*, LatticeVal> ValueState;  // The state each value is in.
161
162   /// StructValueState - This maintains ValueState for values that have
163   /// StructType, for example for formal arguments, calls, insertelement, etc.
164   ///
165   DenseMap<std::pair<Value*, unsigned>, LatticeVal> StructValueState;
166   
167   /// GlobalValue - If we are tracking any values for the contents of a global
168   /// variable, we keep a mapping from the constant accessor to the element of
169   /// the global, to the currently known value.  If the value becomes
170   /// overdefined, it's entry is simply removed from this map.
171   DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
172
173   /// TrackedRetVals - If we are tracking arguments into and the return
174   /// value out of a function, it will have an entry in this map, indicating
175   /// what the known return value for the function is.
176   DenseMap<Function*, LatticeVal> TrackedRetVals;
177
178   /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
179   /// that return multiple values.
180   DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
181   
182   /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
183   /// represented here for efficient lookup.
184   SmallPtrSet<Function*, 16> MRVFunctionsTracked;
185
186   /// TrackingIncomingArguments - This is the set of functions for whose
187   /// arguments we make optimistic assumptions about and try to prove as
188   /// constants.
189   SmallPtrSet<Function*, 16> TrackingIncomingArguments;
190   
191   /// The reason for two worklists is that overdefined is the lowest state
192   /// on the lattice, and moving things to overdefined as fast as possible
193   /// makes SCCP converge much faster.
194   ///
195   /// By having a separate worklist, we accomplish this because everything
196   /// possibly overdefined will become overdefined at the soonest possible
197   /// point.
198   SmallVector<Value*, 64> OverdefinedInstWorkList;
199   SmallVector<Value*, 64> InstWorkList;
200
201
202   SmallVector<BasicBlock*, 64>  BBWorkList;  // The BasicBlock work list
203
204   /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
205   /// overdefined, despite the fact that the PHI node is overdefined.
206   std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
207
208   /// KnownFeasibleEdges - Entries in this set are edges which have already had
209   /// PHI nodes retriggered.
210   typedef std::pair<BasicBlock*, BasicBlock*> Edge;
211   DenseSet<Edge> KnownFeasibleEdges;
212 public:
213   SCCPSolver(const TargetData *td) : TD(td) {}
214
215   /// MarkBlockExecutable - This method can be used by clients to mark all of
216   /// the blocks that are known to be intrinsically live in the processed unit.
217   ///
218   /// This returns true if the block was not considered live before.
219   bool MarkBlockExecutable(BasicBlock *BB) {
220     if (!BBExecutable.insert(BB)) return false;
221     DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << "\n");
222     BBWorkList.push_back(BB);  // Add the block to the work list!
223     return true;
224   }
225
226   /// TrackValueOfGlobalVariable - Clients can use this method to
227   /// inform the SCCPSolver that it should track loads and stores to the
228   /// specified global variable if it can.  This is only legal to call if
229   /// performing Interprocedural SCCP.
230   void TrackValueOfGlobalVariable(GlobalVariable *GV) {
231     // We only track the contents of scalar globals.
232     if (GV->getType()->getElementType()->isSingleValueType()) {
233       LatticeVal &IV = TrackedGlobals[GV];
234       if (!isa<UndefValue>(GV->getInitializer()))
235         IV.markConstant(GV->getInitializer());
236     }
237   }
238
239   /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
240   /// and out of the specified function (which cannot have its address taken),
241   /// this method must be called.
242   void AddTrackedFunction(Function *F) {
243     // Add an entry, F -> undef.
244     if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
245       MRVFunctionsTracked.insert(F);
246       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
247         TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
248                                                      LatticeVal()));
249     } else
250       TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
251   }
252
253   void AddArgumentTrackedFunction(Function *F) {
254     TrackingIncomingArguments.insert(F);
255   }
256   
257   /// Solve - Solve for constants and executable blocks.
258   ///
259   void Solve();
260
261   /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
262   /// that branches on undef values cannot reach any of their successors.
263   /// However, this is not a safe assumption.  After we solve dataflow, this
264   /// method should be use to handle this.  If this returns true, the solver
265   /// should be rerun.
266   bool ResolvedUndefsIn(Function &F);
267
268   bool isBlockExecutable(BasicBlock *BB) const {
269     return BBExecutable.count(BB);
270   }
271
272   LatticeVal getLatticeValueFor(Value *V) const {
273     DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
274     assert(I != ValueState.end() && "V is not in valuemap!");
275     return I->second;
276   }
277   
278   /*LatticeVal getStructLatticeValueFor(Value *V, unsigned i) const {
279     DenseMap<std::pair<Value*, unsigned>, LatticeVal>::const_iterator I = 
280       StructValueState.find(std::make_pair(V, i));
281     assert(I != StructValueState.end() && "V is not in valuemap!");
282     return I->second;
283   }*/
284
285   /// getTrackedRetVals - Get the inferred return value map.
286   ///
287   const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
288     return TrackedRetVals;
289   }
290
291   /// getTrackedGlobals - Get and return the set of inferred initializers for
292   /// global variables.
293   const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
294     return TrackedGlobals;
295   }
296
297   void markOverdefined(Value *V) {
298     assert(!V->getType()->isStructTy() && "Should use other method");
299     markOverdefined(ValueState[V], V);
300   }
301
302   /// markAnythingOverdefined - Mark the specified value overdefined.  This
303   /// works with both scalars and structs.
304   void markAnythingOverdefined(Value *V) {
305     if (StructType *STy = dyn_cast<StructType>(V->getType()))
306       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
307         markOverdefined(getStructValueState(V, i), V);
308     else
309       markOverdefined(V);
310   }
311   
312 private:
313   // markConstant - Make a value be marked as "constant".  If the value
314   // is not already a constant, add it to the instruction work list so that
315   // the users of the instruction are updated later.
316   //
317   void markConstant(LatticeVal &IV, Value *V, Constant *C) {
318     if (!IV.markConstant(C)) return;
319     DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
320     if (IV.isOverdefined())
321       OverdefinedInstWorkList.push_back(V);
322     else
323       InstWorkList.push_back(V);
324   }
325   
326   void markConstant(Value *V, Constant *C) {
327     assert(!V->getType()->isStructTy() && "Should use other method");
328     markConstant(ValueState[V], V, C);
329   }
330
331   void markForcedConstant(Value *V, Constant *C) {
332     assert(!V->getType()->isStructTy() && "Should use other method");
333     LatticeVal &IV = ValueState[V];
334     IV.markForcedConstant(C);
335     DEBUG(dbgs() << "markForcedConstant: " << *C << ": " << *V << '\n');
336     if (IV.isOverdefined())
337       OverdefinedInstWorkList.push_back(V);
338     else
339       InstWorkList.push_back(V);
340   }
341   
342   
343   // markOverdefined - Make a value be marked as "overdefined". If the
344   // value is not already overdefined, add it to the overdefined instruction
345   // work list so that the users of the instruction are updated later.
346   void markOverdefined(LatticeVal &IV, Value *V) {
347     if (!IV.markOverdefined()) return;
348     
349     DEBUG(dbgs() << "markOverdefined: ";
350           if (Function *F = dyn_cast<Function>(V))
351             dbgs() << "Function '" << F->getName() << "'\n";
352           else
353             dbgs() << *V << '\n');
354     // Only instructions go on the work list
355     OverdefinedInstWorkList.push_back(V);
356   }
357
358   void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
359     if (IV.isOverdefined() || MergeWithV.isUndefined())
360       return;  // Noop.
361     if (MergeWithV.isOverdefined())
362       markOverdefined(IV, V);
363     else if (IV.isUndefined())
364       markConstant(IV, V, MergeWithV.getConstant());
365     else if (IV.getConstant() != MergeWithV.getConstant())
366       markOverdefined(IV, V);
367   }
368   
369   void mergeInValue(Value *V, LatticeVal MergeWithV) {
370     assert(!V->getType()->isStructTy() && "Should use other method");
371     mergeInValue(ValueState[V], V, MergeWithV);
372   }
373
374
375   /// getValueState - Return the LatticeVal object that corresponds to the
376   /// value.  This function handles the case when the value hasn't been seen yet
377   /// by properly seeding constants etc.
378   LatticeVal &getValueState(Value *V) {
379     assert(!V->getType()->isStructTy() && "Should use getStructValueState");
380
381     std::pair<DenseMap<Value*, LatticeVal>::iterator, bool> I =
382       ValueState.insert(std::make_pair(V, LatticeVal()));
383     LatticeVal &LV = I.first->second;
384
385     if (!I.second)
386       return LV;  // Common case, already in the map.
387
388     if (Constant *C = dyn_cast<Constant>(V)) {
389       // Undef values remain undefined.
390       if (!isa<UndefValue>(V))
391         LV.markConstant(C);          // Constants are constant
392     }
393     
394     // All others are underdefined by default.
395     return LV;
396   }
397
398   /// getStructValueState - Return the LatticeVal object that corresponds to the
399   /// value/field pair.  This function handles the case when the value hasn't
400   /// been seen yet by properly seeding constants etc.
401   LatticeVal &getStructValueState(Value *V, unsigned i) {
402     assert(V->getType()->isStructTy() && "Should use getValueState");
403     assert(i < cast<StructType>(V->getType())->getNumElements() &&
404            "Invalid element #");
405
406     std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator,
407               bool> I = StructValueState.insert(
408                         std::make_pair(std::make_pair(V, i), LatticeVal()));
409     LatticeVal &LV = I.first->second;
410
411     if (!I.second)
412       return LV;  // Common case, already in the map.
413
414     if (Constant *C = dyn_cast<Constant>(V)) {
415       if (isa<UndefValue>(C))
416         ; // Undef values remain undefined.
417       else if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C))
418         LV.markConstant(CS->getOperand(i));      // Constants are constant.
419       else if (isa<ConstantAggregateZero>(C)) {
420         Type *FieldTy = cast<StructType>(V->getType())->getElementType(i);
421         LV.markConstant(Constant::getNullValue(FieldTy));
422       } else
423         LV.markOverdefined();      // Unknown sort of constant.
424     }
425     
426     // All others are underdefined by default.
427     return LV;
428   }
429   
430
431   /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
432   /// work list if it is not already executable.
433   void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
434     if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
435       return;  // This edge is already known to be executable!
436
437     if (!MarkBlockExecutable(Dest)) {
438       // If the destination is already executable, we just made an *edge*
439       // feasible that wasn't before.  Revisit the PHI nodes in the block
440       // because they have potentially new operands.
441       DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
442             << " -> " << Dest->getName() << "\n");
443
444       PHINode *PN;
445       for (BasicBlock::iterator I = Dest->begin();
446            (PN = dyn_cast<PHINode>(I)); ++I)
447         visitPHINode(*PN);
448     }
449   }
450
451   // getFeasibleSuccessors - Return a vector of booleans to indicate which
452   // successors are reachable from a given terminator instruction.
453   //
454   void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
455
456   // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
457   // block to the 'To' basic block is currently feasible.
458   //
459   bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
460
461   // OperandChangedState - This method is invoked on all of the users of an
462   // instruction that was just changed state somehow.  Based on this
463   // information, we need to update the specified user of this instruction.
464   //
465   void OperandChangedState(Instruction *I) {
466     if (BBExecutable.count(I->getParent()))   // Inst is executable?
467       visit(*I);
468   }
469   
470   /// RemoveFromOverdefinedPHIs - If I has any entries in the
471   /// UsersOfOverdefinedPHIs map for PN, remove them now.
472   void RemoveFromOverdefinedPHIs(Instruction *I, PHINode *PN) {
473     if (UsersOfOverdefinedPHIs.empty()) return;
474     typedef std::multimap<PHINode*, Instruction*>::iterator ItTy;
475     std::pair<ItTy, ItTy> Range = UsersOfOverdefinedPHIs.equal_range(PN);
476     for (ItTy It = Range.first, E = Range.second; It != E;) {
477       if (It->second == I)
478         UsersOfOverdefinedPHIs.erase(It++);
479       else
480         ++It;
481     }
482   }
483
484   /// InsertInOverdefinedPHIs - Insert an entry in the UsersOfOverdefinedPHIS
485   /// map for I and PN, but if one is there already, do not create another.
486   /// (Duplicate entries do not break anything directly, but can lead to
487   /// exponential growth of the table in rare cases.)
488   void InsertInOverdefinedPHIs(Instruction *I, PHINode *PN) {
489     typedef std::multimap<PHINode*, Instruction*>::iterator ItTy;
490     std::pair<ItTy, ItTy> Range = UsersOfOverdefinedPHIs.equal_range(PN);
491     for (ItTy J = Range.first, E = Range.second; J != E; ++J)
492       if (J->second == I)
493         return;
494     UsersOfOverdefinedPHIs.insert(std::make_pair(PN, I));
495   }
496
497 private:
498   friend class InstVisitor<SCCPSolver>;
499
500   // visit implementations - Something changed in this instruction.  Either an
501   // operand made a transition, or the instruction is newly executable.  Change
502   // the value type of I to reflect these changes if appropriate.
503   void visitPHINode(PHINode &I);
504
505   // Terminators
506   void visitReturnInst(ReturnInst &I);
507   void visitTerminatorInst(TerminatorInst &TI);
508
509   void visitCastInst(CastInst &I);
510   void visitSelectInst(SelectInst &I);
511   void visitBinaryOperator(Instruction &I);
512   void visitCmpInst(CmpInst &I);
513   void visitExtractElementInst(ExtractElementInst &I);
514   void visitInsertElementInst(InsertElementInst &I);
515   void visitShuffleVectorInst(ShuffleVectorInst &I);
516   void visitExtractValueInst(ExtractValueInst &EVI);
517   void visitInsertValueInst(InsertValueInst &IVI);
518
519   // Instructions that cannot be folded away.
520   void visitStoreInst     (StoreInst &I);
521   void visitLoadInst      (LoadInst &I);
522   void visitGetElementPtrInst(GetElementPtrInst &I);
523   void visitCallInst      (CallInst &I) {
524     visitCallSite(&I);
525   }
526   void visitInvokeInst    (InvokeInst &II) {
527     visitCallSite(&II);
528     visitTerminatorInst(II);
529   }
530   void visitCallSite      (CallSite CS);
531   void visitResumeInst    (TerminatorInst &I) { /*returns void*/ }
532   void visitUnwindInst    (TerminatorInst &I) { /*returns void*/ }
533   void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
534   void visitFenceInst     (FenceInst &I) { /*returns void*/ }
535   void visitAtomicCmpXchgInst (AtomicCmpXchgInst &I) { markOverdefined(&I); }
536   void visitAtomicRMWInst (AtomicRMWInst &I) { markOverdefined(&I); }
537   void visitAllocaInst    (Instruction &I) { markOverdefined(&I); }
538   void visitVAArgInst     (Instruction &I) { markAnythingOverdefined(&I); }
539
540   void visitInstruction(Instruction &I) {
541     // If a new instruction is added to LLVM that we don't handle.
542     dbgs() << "SCCP: Don't know how to handle: " << I;
543     markAnythingOverdefined(&I);   // Just in case
544   }
545 };
546
547 } // end anonymous namespace
548
549
550 // getFeasibleSuccessors - Return a vector of booleans to indicate which
551 // successors are reachable from a given terminator instruction.
552 //
553 void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
554                                        SmallVector<bool, 16> &Succs) {
555   Succs.resize(TI.getNumSuccessors());
556   if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
557     if (BI->isUnconditional()) {
558       Succs[0] = true;
559       return;
560     }
561     
562     LatticeVal BCValue = getValueState(BI->getCondition());
563     ConstantInt *CI = BCValue.getConstantInt();
564     if (CI == 0) {
565       // Overdefined condition variables, and branches on unfoldable constant
566       // conditions, mean the branch could go either way.
567       if (!BCValue.isUndefined())
568         Succs[0] = Succs[1] = true;
569       return;
570     }
571     
572     // Constant condition variables mean the branch can only go a single way.
573     Succs[CI->isZero()] = true;
574     return;
575   }
576   
577   if (isa<InvokeInst>(TI)) {
578     // Invoke instructions successors are always executable.
579     Succs[0] = Succs[1] = true;
580     return;
581   }
582   
583   if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
584     LatticeVal SCValue = getValueState(SI->getCondition());
585     ConstantInt *CI = SCValue.getConstantInt();
586     
587     if (CI == 0) {   // Overdefined or undefined condition?
588       // All destinations are executable!
589       if (!SCValue.isUndefined())
590         Succs.assign(TI.getNumSuccessors(), true);
591       return;
592     }
593       
594     Succs[SI->findCaseValue(CI)] = true;
595     return;
596   }
597   
598   // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
599   if (isa<IndirectBrInst>(&TI)) {
600     // Just mark all destinations executable!
601     Succs.assign(TI.getNumSuccessors(), true);
602     return;
603   }
604   
605 #ifndef NDEBUG
606   dbgs() << "Unknown terminator instruction: " << TI << '\n';
607 #endif
608   llvm_unreachable("SCCP: Don't know how to handle this terminator!");
609 }
610
611
612 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
613 // block to the 'To' basic block is currently feasible.
614 //
615 bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
616   assert(BBExecutable.count(To) && "Dest should always be alive!");
617
618   // Make sure the source basic block is executable!!
619   if (!BBExecutable.count(From)) return false;
620
621   // Check to make sure this edge itself is actually feasible now.
622   TerminatorInst *TI = From->getTerminator();
623   if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
624     if (BI->isUnconditional())
625       return true;
626     
627     LatticeVal BCValue = getValueState(BI->getCondition());
628
629     // Overdefined condition variables mean the branch could go either way,
630     // undef conditions mean that neither edge is feasible yet.
631     ConstantInt *CI = BCValue.getConstantInt();
632     if (CI == 0)
633       return !BCValue.isUndefined();
634     
635     // Constant condition variables mean the branch can only go a single way.
636     return BI->getSuccessor(CI->isZero()) == To;
637   }
638   
639   // Invoke instructions successors are always executable.
640   if (isa<InvokeInst>(TI))
641     return true;
642   
643   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
644     LatticeVal SCValue = getValueState(SI->getCondition());
645     ConstantInt *CI = SCValue.getConstantInt();
646     
647     if (CI == 0)
648       return !SCValue.isUndefined();
649
650     // Make sure to skip the "default value" which isn't a value
651     for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
652       if (SI->getSuccessorValue(i) == CI) // Found the taken branch.
653         return SI->getSuccessor(i) == To;
654
655     // If the constant value is not equal to any of the branches, we must
656     // execute default branch.
657     return SI->getDefaultDest() == To;
658   }
659   
660   // Just mark all destinations executable!
661   // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
662   if (isa<IndirectBrInst>(TI))
663     return true;
664   
665 #ifndef NDEBUG
666   dbgs() << "Unknown terminator instruction: " << *TI << '\n';
667 #endif
668   llvm_unreachable(0);
669 }
670
671 // visit Implementations - Something changed in this instruction, either an
672 // operand made a transition, or the instruction is newly executable.  Change
673 // the value type of I to reflect these changes if appropriate.  This method
674 // makes sure to do the following actions:
675 //
676 // 1. If a phi node merges two constants in, and has conflicting value coming
677 //    from different branches, or if the PHI node merges in an overdefined
678 //    value, then the PHI node becomes overdefined.
679 // 2. If a phi node merges only constants in, and they all agree on value, the
680 //    PHI node becomes a constant value equal to that.
681 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
682 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
683 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
684 // 6. If a conditional branch has a value that is constant, make the selected
685 //    destination executable
686 // 7. If a conditional branch has a value that is overdefined, make all
687 //    successors executable.
688 //
689 void SCCPSolver::visitPHINode(PHINode &PN) {
690   // If this PN returns a struct, just mark the result overdefined.
691   // TODO: We could do a lot better than this if code actually uses this.
692   if (PN.getType()->isStructTy())
693     return markAnythingOverdefined(&PN);
694   
695   if (getValueState(&PN).isOverdefined()) {
696     // There may be instructions using this PHI node that are not overdefined
697     // themselves.  If so, make sure that they know that the PHI node operand
698     // changed.
699     typedef std::multimap<PHINode*, Instruction*>::iterator ItTy;
700     std::pair<ItTy, ItTy> Range = UsersOfOverdefinedPHIs.equal_range(&PN);
701     
702     if (Range.first == Range.second)
703       return;
704     
705     SmallVector<Instruction*, 16> Users;
706     for (ItTy I = Range.first, E = Range.second; I != E; ++I)
707       Users.push_back(I->second);
708     while (!Users.empty())
709       visit(Users.pop_back_val());
710     return;  // Quick exit
711   }
712
713   // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
714   // and slow us down a lot.  Just mark them overdefined.
715   if (PN.getNumIncomingValues() > 64)
716     return markOverdefined(&PN);
717   
718   // Look at all of the executable operands of the PHI node.  If any of them
719   // are overdefined, the PHI becomes overdefined as well.  If they are all
720   // constant, and they agree with each other, the PHI becomes the identical
721   // constant.  If they are constant and don't agree, the PHI is overdefined.
722   // If there are no executable operands, the PHI remains undefined.
723   //
724   Constant *OperandVal = 0;
725   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
726     LatticeVal IV = getValueState(PN.getIncomingValue(i));
727     if (IV.isUndefined()) continue;  // Doesn't influence PHI node.
728
729     if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
730       continue;
731     
732     if (IV.isOverdefined())    // PHI node becomes overdefined!
733       return markOverdefined(&PN);
734
735     if (OperandVal == 0) {   // Grab the first value.
736       OperandVal = IV.getConstant();
737       continue;
738     }
739     
740     // There is already a reachable operand.  If we conflict with it,
741     // then the PHI node becomes overdefined.  If we agree with it, we
742     // can continue on.
743     
744     // Check to see if there are two different constants merging, if so, the PHI
745     // node is overdefined.
746     if (IV.getConstant() != OperandVal)
747       return markOverdefined(&PN);
748   }
749
750   // If we exited the loop, this means that the PHI node only has constant
751   // arguments that agree with each other(and OperandVal is the constant) or
752   // OperandVal is null because there are no defined incoming arguments.  If
753   // this is the case, the PHI remains undefined.
754   //
755   if (OperandVal)
756     markConstant(&PN, OperandVal);      // Acquire operand value
757 }
758
759
760
761
762 void SCCPSolver::visitReturnInst(ReturnInst &I) {
763   if (I.getNumOperands() == 0) return;  // ret void
764
765   Function *F = I.getParent()->getParent();
766   Value *ResultOp = I.getOperand(0);
767   
768   // If we are tracking the return value of this function, merge it in.
769   if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
770     DenseMap<Function*, LatticeVal>::iterator TFRVI =
771       TrackedRetVals.find(F);
772     if (TFRVI != TrackedRetVals.end()) {
773       mergeInValue(TFRVI->second, F, getValueState(ResultOp));
774       return;
775     }
776   }
777   
778   // Handle functions that return multiple values.
779   if (!TrackedMultipleRetVals.empty()) {
780     if (StructType *STy = dyn_cast<StructType>(ResultOp->getType()))
781       if (MRVFunctionsTracked.count(F))
782         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
783           mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
784                        getStructValueState(ResultOp, i));
785     
786   }
787 }
788
789 void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
790   SmallVector<bool, 16> SuccFeasible;
791   getFeasibleSuccessors(TI, SuccFeasible);
792
793   BasicBlock *BB = TI.getParent();
794
795   // Mark all feasible successors executable.
796   for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
797     if (SuccFeasible[i])
798       markEdgeExecutable(BB, TI.getSuccessor(i));
799 }
800
801 void SCCPSolver::visitCastInst(CastInst &I) {
802   LatticeVal OpSt = getValueState(I.getOperand(0));
803   if (OpSt.isOverdefined())          // Inherit overdefinedness of operand
804     markOverdefined(&I);
805   else if (OpSt.isConstant())        // Propagate constant value
806     markConstant(&I, ConstantExpr::getCast(I.getOpcode(), 
807                                            OpSt.getConstant(), I.getType()));
808 }
809
810
811 void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
812   // If this returns a struct, mark all elements over defined, we don't track
813   // structs in structs.
814   if (EVI.getType()->isStructTy())
815     return markAnythingOverdefined(&EVI);
816     
817   // If this is extracting from more than one level of struct, we don't know.
818   if (EVI.getNumIndices() != 1)
819     return markOverdefined(&EVI);
820
821   Value *AggVal = EVI.getAggregateOperand();
822   if (AggVal->getType()->isStructTy()) {
823     unsigned i = *EVI.idx_begin();
824     LatticeVal EltVal = getStructValueState(AggVal, i);
825     mergeInValue(getValueState(&EVI), &EVI, EltVal);
826   } else {
827     // Otherwise, must be extracting from an array.
828     return markOverdefined(&EVI);
829   }
830 }
831
832 void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
833   StructType *STy = dyn_cast<StructType>(IVI.getType());
834   if (STy == 0)
835     return markOverdefined(&IVI);
836   
837   // If this has more than one index, we can't handle it, drive all results to
838   // undef.
839   if (IVI.getNumIndices() != 1)
840     return markAnythingOverdefined(&IVI);
841   
842   Value *Aggr = IVI.getAggregateOperand();
843   unsigned Idx = *IVI.idx_begin();
844   
845   // Compute the result based on what we're inserting.
846   for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
847     // This passes through all values that aren't the inserted element.
848     if (i != Idx) {
849       LatticeVal EltVal = getStructValueState(Aggr, i);
850       mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
851       continue;
852     }
853     
854     Value *Val = IVI.getInsertedValueOperand();
855     if (Val->getType()->isStructTy())
856       // We don't track structs in structs.
857       markOverdefined(getStructValueState(&IVI, i), &IVI);
858     else {
859       LatticeVal InVal = getValueState(Val);
860       mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
861     }
862   }
863 }
864
865 void SCCPSolver::visitSelectInst(SelectInst &I) {
866   // If this select returns a struct, just mark the result overdefined.
867   // TODO: We could do a lot better than this if code actually uses this.
868   if (I.getType()->isStructTy())
869     return markAnythingOverdefined(&I);
870   
871   LatticeVal CondValue = getValueState(I.getCondition());
872   if (CondValue.isUndefined())
873     return;
874   
875   if (ConstantInt *CondCB = CondValue.getConstantInt()) {
876     Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
877     mergeInValue(&I, getValueState(OpVal));
878     return;
879   }
880   
881   // Otherwise, the condition is overdefined or a constant we can't evaluate.
882   // See if we can produce something better than overdefined based on the T/F
883   // value.
884   LatticeVal TVal = getValueState(I.getTrueValue());
885   LatticeVal FVal = getValueState(I.getFalseValue());
886   
887   // select ?, C, C -> C.
888   if (TVal.isConstant() && FVal.isConstant() && 
889       TVal.getConstant() == FVal.getConstant())
890     return markConstant(&I, FVal.getConstant());
891
892   if (TVal.isUndefined())   // select ?, undef, X -> X.
893     return mergeInValue(&I, FVal);
894   if (FVal.isUndefined())   // select ?, X, undef -> X.
895     return mergeInValue(&I, TVal);
896   markOverdefined(&I);
897 }
898
899 // Handle Binary Operators.
900 void SCCPSolver::visitBinaryOperator(Instruction &I) {
901   LatticeVal V1State = getValueState(I.getOperand(0));
902   LatticeVal V2State = getValueState(I.getOperand(1));
903   
904   LatticeVal &IV = ValueState[&I];
905   if (IV.isOverdefined()) return;
906
907   if (V1State.isConstant() && V2State.isConstant())
908     return markConstant(IV, &I,
909                         ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
910                                           V2State.getConstant()));
911   
912   // If something is undef, wait for it to resolve.
913   if (!V1State.isOverdefined() && !V2State.isOverdefined())
914     return;
915   
916   // Otherwise, one of our operands is overdefined.  Try to produce something
917   // better than overdefined with some tricks.
918   
919   // If this is an AND or OR with 0 or -1, it doesn't matter that the other
920   // operand is overdefined.
921   if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
922     LatticeVal *NonOverdefVal = 0;
923     if (!V1State.isOverdefined())
924       NonOverdefVal = &V1State;
925     else if (!V2State.isOverdefined())
926       NonOverdefVal = &V2State;
927
928     if (NonOverdefVal) {
929       if (NonOverdefVal->isUndefined()) {
930         // Could annihilate value.
931         if (I.getOpcode() == Instruction::And)
932           markConstant(IV, &I, Constant::getNullValue(I.getType()));
933         else if (VectorType *PT = dyn_cast<VectorType>(I.getType()))
934           markConstant(IV, &I, Constant::getAllOnesValue(PT));
935         else
936           markConstant(IV, &I,
937                        Constant::getAllOnesValue(I.getType()));
938         return;
939       }
940       
941       if (I.getOpcode() == Instruction::And) {
942         // X and 0 = 0
943         if (NonOverdefVal->getConstant()->isNullValue())
944           return markConstant(IV, &I, NonOverdefVal->getConstant());
945       } else {
946         if (ConstantInt *CI = NonOverdefVal->getConstantInt())
947           if (CI->isAllOnesValue())     // X or -1 = -1
948             return markConstant(IV, &I, NonOverdefVal->getConstant());
949       }
950     }
951   }
952
953
954   // If both operands are PHI nodes, it is possible that this instruction has
955   // a constant value, despite the fact that the PHI node doesn't.  Check for
956   // this condition now.
957   if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
958     if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
959       if (PN1->getParent() == PN2->getParent()) {
960         // Since the two PHI nodes are in the same basic block, they must have
961         // entries for the same predecessors.  Walk the predecessor list, and
962         // if all of the incoming values are constants, and the result of
963         // evaluating this expression with all incoming value pairs is the
964         // same, then this expression is a constant even though the PHI node
965         // is not a constant!
966         LatticeVal Result;
967         for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
968           LatticeVal In1 = getValueState(PN1->getIncomingValue(i));
969           BasicBlock *InBlock = PN1->getIncomingBlock(i);
970           LatticeVal In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
971
972           if (In1.isOverdefined() || In2.isOverdefined()) {
973             Result.markOverdefined();
974             break;  // Cannot fold this operation over the PHI nodes!
975           }
976           
977           if (In1.isConstant() && In2.isConstant()) {
978             Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
979                                             In2.getConstant());
980             if (Result.isUndefined())
981               Result.markConstant(V);
982             else if (Result.isConstant() && Result.getConstant() != V) {
983               Result.markOverdefined();
984               break;
985             }
986           }
987         }
988
989         // If we found a constant value here, then we know the instruction is
990         // constant despite the fact that the PHI nodes are overdefined.
991         if (Result.isConstant()) {
992           markConstant(IV, &I, Result.getConstant());
993           // Remember that this instruction is virtually using the PHI node
994           // operands. 
995           InsertInOverdefinedPHIs(&I, PN1);
996           InsertInOverdefinedPHIs(&I, PN2);
997           return;
998         }
999         
1000         if (Result.isUndefined())
1001           return;
1002
1003         // Okay, this really is overdefined now.  Since we might have
1004         // speculatively thought that this was not overdefined before, and
1005         // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
1006         // make sure to clean out any entries that we put there, for
1007         // efficiency.
1008         RemoveFromOverdefinedPHIs(&I, PN1);
1009         RemoveFromOverdefinedPHIs(&I, PN2);
1010       }
1011
1012   markOverdefined(&I);
1013 }
1014
1015 // Handle ICmpInst instruction.
1016 void SCCPSolver::visitCmpInst(CmpInst &I) {
1017   LatticeVal V1State = getValueState(I.getOperand(0));
1018   LatticeVal V2State = getValueState(I.getOperand(1));
1019
1020   LatticeVal &IV = ValueState[&I];
1021   if (IV.isOverdefined()) return;
1022
1023   if (V1State.isConstant() && V2State.isConstant())
1024     return markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(), 
1025                                                          V1State.getConstant(), 
1026                                                         V2State.getConstant()));
1027   
1028   // If operands are still undefined, wait for it to resolve.
1029   if (!V1State.isOverdefined() && !V2State.isOverdefined())
1030     return;
1031   
1032   // If something is overdefined, use some tricks to avoid ending up and over
1033   // defined if we can.
1034   
1035   // If both operands are PHI nodes, it is possible that this instruction has
1036   // a constant value, despite the fact that the PHI node doesn't.  Check for
1037   // this condition now.
1038   if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
1039     if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
1040       if (PN1->getParent() == PN2->getParent()) {
1041         // Since the two PHI nodes are in the same basic block, they must have
1042         // entries for the same predecessors.  Walk the predecessor list, and
1043         // if all of the incoming values are constants, and the result of
1044         // evaluating this expression with all incoming value pairs is the
1045         // same, then this expression is a constant even though the PHI node
1046         // is not a constant!
1047         LatticeVal Result;
1048         for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
1049           LatticeVal In1 = getValueState(PN1->getIncomingValue(i));
1050           BasicBlock *InBlock = PN1->getIncomingBlock(i);
1051           LatticeVal In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
1052
1053           if (In1.isOverdefined() || In2.isOverdefined()) {
1054             Result.markOverdefined();
1055             break;  // Cannot fold this operation over the PHI nodes!
1056           }
1057           
1058           if (In1.isConstant() && In2.isConstant()) {
1059             Constant *V = ConstantExpr::getCompare(I.getPredicate(), 
1060                                                    In1.getConstant(), 
1061                                                    In2.getConstant());
1062             if (Result.isUndefined())
1063               Result.markConstant(V);
1064             else if (Result.isConstant() && Result.getConstant() != V) {
1065               Result.markOverdefined();
1066               break;
1067             }
1068           }
1069         }
1070
1071         // If we found a constant value here, then we know the instruction is
1072         // constant despite the fact that the PHI nodes are overdefined.
1073         if (Result.isConstant()) {
1074           markConstant(&I, Result.getConstant());
1075           // Remember that this instruction is virtually using the PHI node
1076           // operands.
1077           InsertInOverdefinedPHIs(&I, PN1);
1078           InsertInOverdefinedPHIs(&I, PN2);
1079           return;
1080         }
1081         
1082         if (Result.isUndefined())
1083           return;
1084
1085         // Okay, this really is overdefined now.  Since we might have
1086         // speculatively thought that this was not overdefined before, and
1087         // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
1088         // make sure to clean out any entries that we put there, for
1089         // efficiency.
1090         RemoveFromOverdefinedPHIs(&I, PN1);
1091         RemoveFromOverdefinedPHIs(&I, PN2);
1092       }
1093
1094   markOverdefined(&I);
1095 }
1096
1097 void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
1098   // TODO : SCCP does not handle vectors properly.
1099   return markOverdefined(&I);
1100
1101 #if 0
1102   LatticeVal &ValState = getValueState(I.getOperand(0));
1103   LatticeVal &IdxState = getValueState(I.getOperand(1));
1104
1105   if (ValState.isOverdefined() || IdxState.isOverdefined())
1106     markOverdefined(&I);
1107   else if(ValState.isConstant() && IdxState.isConstant())
1108     markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
1109                                                      IdxState.getConstant()));
1110 #endif
1111 }
1112
1113 void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
1114   // TODO : SCCP does not handle vectors properly.
1115   return markOverdefined(&I);
1116 #if 0
1117   LatticeVal &ValState = getValueState(I.getOperand(0));
1118   LatticeVal &EltState = getValueState(I.getOperand(1));
1119   LatticeVal &IdxState = getValueState(I.getOperand(2));
1120
1121   if (ValState.isOverdefined() || EltState.isOverdefined() ||
1122       IdxState.isOverdefined())
1123     markOverdefined(&I);
1124   else if(ValState.isConstant() && EltState.isConstant() &&
1125           IdxState.isConstant())
1126     markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
1127                                                     EltState.getConstant(),
1128                                                     IdxState.getConstant()));
1129   else if (ValState.isUndefined() && EltState.isConstant() &&
1130            IdxState.isConstant()) 
1131     markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
1132                                                    EltState.getConstant(),
1133                                                    IdxState.getConstant()));
1134 #endif
1135 }
1136
1137 void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
1138   // TODO : SCCP does not handle vectors properly.
1139   return markOverdefined(&I);
1140 #if 0
1141   LatticeVal &V1State   = getValueState(I.getOperand(0));
1142   LatticeVal &V2State   = getValueState(I.getOperand(1));
1143   LatticeVal &MaskState = getValueState(I.getOperand(2));
1144
1145   if (MaskState.isUndefined() ||
1146       (V1State.isUndefined() && V2State.isUndefined()))
1147     return;  // Undefined output if mask or both inputs undefined.
1148   
1149   if (V1State.isOverdefined() || V2State.isOverdefined() ||
1150       MaskState.isOverdefined()) {
1151     markOverdefined(&I);
1152   } else {
1153     // A mix of constant/undef inputs.
1154     Constant *V1 = V1State.isConstant() ? 
1155         V1State.getConstant() : UndefValue::get(I.getType());
1156     Constant *V2 = V2State.isConstant() ? 
1157         V2State.getConstant() : UndefValue::get(I.getType());
1158     Constant *Mask = MaskState.isConstant() ? 
1159       MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1160     markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1161   }
1162 #endif
1163 }
1164
1165 // Handle getelementptr instructions.  If all operands are constants then we
1166 // can turn this into a getelementptr ConstantExpr.
1167 //
1168 void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
1169   if (ValueState[&I].isOverdefined()) return;
1170
1171   SmallVector<Constant*, 8> Operands;
1172   Operands.reserve(I.getNumOperands());
1173
1174   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1175     LatticeVal State = getValueState(I.getOperand(i));
1176     if (State.isUndefined())
1177       return;  // Operands are not resolved yet.
1178     
1179     if (State.isOverdefined())
1180       return markOverdefined(&I);
1181
1182     assert(State.isConstant() && "Unknown state!");
1183     Operands.push_back(State.getConstant());
1184   }
1185
1186   Constant *Ptr = Operands[0];
1187   ArrayRef<Constant *> Indices(Operands.begin() + 1, Operands.end());
1188   markConstant(&I, ConstantExpr::getGetElementPtr(Ptr, Indices));
1189 }
1190
1191 void SCCPSolver::visitStoreInst(StoreInst &SI) {
1192   // If this store is of a struct, ignore it.
1193   if (SI.getOperand(0)->getType()->isStructTy())
1194     return;
1195   
1196   if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1197     return;
1198   
1199   GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1200   DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
1201   if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1202
1203   // Get the value we are storing into the global, then merge it.
1204   mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
1205   if (I->second.isOverdefined())
1206     TrackedGlobals.erase(I);      // No need to keep tracking this!
1207 }
1208
1209
1210 // Handle load instructions.  If the operand is a constant pointer to a constant
1211 // global, we can replace the load with the loaded constant value!
1212 void SCCPSolver::visitLoadInst(LoadInst &I) {
1213   // If this load is of a struct, just mark the result overdefined.
1214   if (I.getType()->isStructTy())
1215     return markAnythingOverdefined(&I);
1216   
1217   LatticeVal PtrVal = getValueState(I.getOperand(0));
1218   if (PtrVal.isUndefined()) return;   // The pointer is not resolved yet!
1219   
1220   LatticeVal &IV = ValueState[&I];
1221   if (IV.isOverdefined()) return;
1222
1223   if (!PtrVal.isConstant() || I.isVolatile())
1224     return markOverdefined(IV, &I);
1225     
1226   Constant *Ptr = PtrVal.getConstant();
1227
1228   // load null -> null
1229   if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
1230     return markConstant(IV, &I, Constant::getNullValue(I.getType()));
1231   
1232   // Transform load (constant global) into the value loaded.
1233   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1234     if (!TrackedGlobals.empty()) {
1235       // If we are tracking this global, merge in the known value for it.
1236       DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1237         TrackedGlobals.find(GV);
1238       if (It != TrackedGlobals.end()) {
1239         mergeInValue(IV, &I, It->second);
1240         return;
1241       }
1242     }
1243   }
1244
1245   // Transform load from a constant into a constant if possible.
1246   if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, TD))
1247     return markConstant(IV, &I, C);
1248
1249   // Otherwise we cannot say for certain what value this load will produce.
1250   // Bail out.
1251   markOverdefined(IV, &I);
1252 }
1253
1254 void SCCPSolver::visitCallSite(CallSite CS) {
1255   Function *F = CS.getCalledFunction();
1256   Instruction *I = CS.getInstruction();
1257   
1258   // The common case is that we aren't tracking the callee, either because we
1259   // are not doing interprocedural analysis or the callee is indirect, or is
1260   // external.  Handle these cases first.
1261   if (F == 0 || F->isDeclaration()) {
1262 CallOverdefined:
1263     // Void return and not tracking callee, just bail.
1264     if (I->getType()->isVoidTy()) return;
1265     
1266     // Otherwise, if we have a single return value case, and if the function is
1267     // a declaration, maybe we can constant fold it.
1268     if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
1269         canConstantFoldCallTo(F)) {
1270       
1271       SmallVector<Constant*, 8> Operands;
1272       for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1273            AI != E; ++AI) {
1274         LatticeVal State = getValueState(*AI);
1275         
1276         if (State.isUndefined())
1277           return;  // Operands are not resolved yet.
1278         if (State.isOverdefined())
1279           return markOverdefined(I);
1280         assert(State.isConstant() && "Unknown state!");
1281         Operands.push_back(State.getConstant());
1282       }
1283      
1284       // If we can constant fold this, mark the result of the call as a
1285       // constant.
1286       if (Constant *C = ConstantFoldCall(F, Operands))
1287         return markConstant(I, C);
1288     }
1289
1290     // Otherwise, we don't know anything about this call, mark it overdefined.
1291     return markAnythingOverdefined(I);
1292   }
1293
1294   // If this is a local function that doesn't have its address taken, mark its
1295   // entry block executable and merge in the actual arguments to the call into
1296   // the formal arguments of the function.
1297   if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
1298     MarkBlockExecutable(F->begin());
1299     
1300     // Propagate information from this call site into the callee.
1301     CallSite::arg_iterator CAI = CS.arg_begin();
1302     for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1303          AI != E; ++AI, ++CAI) {
1304       // If this argument is byval, and if the function is not readonly, there
1305       // will be an implicit copy formed of the input aggregate.
1306       if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
1307         markOverdefined(AI);
1308         continue;
1309       }
1310       
1311       if (StructType *STy = dyn_cast<StructType>(AI->getType())) {
1312         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1313           LatticeVal CallArg = getStructValueState(*CAI, i);
1314           mergeInValue(getStructValueState(AI, i), AI, CallArg);
1315         }
1316       } else {
1317         mergeInValue(AI, getValueState(*CAI));
1318       }
1319     }
1320   }
1321   
1322   // If this is a single/zero retval case, see if we're tracking the function.
1323   if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
1324     if (!MRVFunctionsTracked.count(F))
1325       goto CallOverdefined;  // Not tracking this callee.
1326     
1327     // If we are tracking this callee, propagate the result of the function
1328     // into this call site.
1329     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1330       mergeInValue(getStructValueState(I, i), I, 
1331                    TrackedMultipleRetVals[std::make_pair(F, i)]);
1332   } else {
1333     DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1334     if (TFRVI == TrackedRetVals.end())
1335       goto CallOverdefined;  // Not tracking this callee.
1336       
1337     // If so, propagate the return value of the callee into this call result.
1338     mergeInValue(I, TFRVI->second);
1339   }
1340 }
1341
1342 void SCCPSolver::Solve() {
1343   // Process the work lists until they are empty!
1344   while (!BBWorkList.empty() || !InstWorkList.empty() ||
1345          !OverdefinedInstWorkList.empty()) {
1346     // Process the overdefined instruction's work list first, which drives other
1347     // things to overdefined more quickly.
1348     while (!OverdefinedInstWorkList.empty()) {
1349       Value *I = OverdefinedInstWorkList.pop_back_val();
1350
1351       DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
1352
1353       // "I" got into the work list because it either made the transition from
1354       // bottom to constant
1355       //
1356       // Anything on this worklist that is overdefined need not be visited
1357       // since all of its users will have already been marked as overdefined
1358       // Update all of the users of this instruction's value.
1359       //
1360       for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1361            UI != E; ++UI)
1362         if (Instruction *I = dyn_cast<Instruction>(*UI))
1363           OperandChangedState(I);
1364     }
1365     
1366     // Process the instruction work list.
1367     while (!InstWorkList.empty()) {
1368       Value *I = InstWorkList.pop_back_val();
1369
1370       DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
1371
1372       // "I" got into the work list because it made the transition from undef to
1373       // constant.
1374       //
1375       // Anything on this worklist that is overdefined need not be visited
1376       // since all of its users will have already been marked as overdefined.
1377       // Update all of the users of this instruction's value.
1378       //
1379       if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
1380         for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1381              UI != E; ++UI)
1382           if (Instruction *I = dyn_cast<Instruction>(*UI))
1383             OperandChangedState(I);
1384     }
1385
1386     // Process the basic block work list.
1387     while (!BBWorkList.empty()) {
1388       BasicBlock *BB = BBWorkList.back();
1389       BBWorkList.pop_back();
1390
1391       DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
1392
1393       // Notify all instructions in this basic block that they are newly
1394       // executable.
1395       visit(BB);
1396     }
1397   }
1398 }
1399
1400 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1401 /// that branches on undef values cannot reach any of their successors.
1402 /// However, this is not a safe assumption.  After we solve dataflow, this
1403 /// method should be use to handle this.  If this returns true, the solver
1404 /// should be rerun.
1405 ///
1406 /// This method handles this by finding an unresolved branch and marking it one
1407 /// of the edges from the block as being feasible, even though the condition
1408 /// doesn't say it would otherwise be.  This allows SCCP to find the rest of the
1409 /// CFG and only slightly pessimizes the analysis results (by marking one,
1410 /// potentially infeasible, edge feasible).  This cannot usefully modify the
1411 /// constraints on the condition of the branch, as that would impact other users
1412 /// of the value.
1413 ///
1414 /// This scan also checks for values that use undefs, whose results are actually
1415 /// defined.  For example, 'zext i8 undef to i32' should produce all zeros
1416 /// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1417 /// even if X isn't defined.
1418 bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1419   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1420     if (!BBExecutable.count(BB))
1421       continue;
1422     
1423     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1424       // Look for instructions which produce undef values.
1425       if (I->getType()->isVoidTy()) continue;
1426       
1427       if (StructType *STy = dyn_cast<StructType>(I->getType())) {
1428         // Only a few things that can be structs matter for undef.  Just send
1429         // all their results to overdefined.  We could be more precise than this
1430         // but it isn't worth bothering.
1431         if (isa<CallInst>(I) || isa<SelectInst>(I)) {
1432           for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1433             LatticeVal &LV = getStructValueState(I, i);
1434             if (LV.isUndefined())
1435               markOverdefined(LV, I);
1436           }
1437         }
1438         continue;
1439       }
1440       
1441       LatticeVal &LV = getValueState(I);
1442       if (!LV.isUndefined()) continue;
1443
1444       // No instructions using structs need disambiguation.
1445       if (I->getOperand(0)->getType()->isStructTy())
1446         continue;
1447
1448       // Get the lattice values of the first two operands for use below.
1449       LatticeVal Op0LV = getValueState(I->getOperand(0));
1450       LatticeVal Op1LV;
1451       if (I->getNumOperands() == 2) {
1452         // No instructions using structs need disambiguation.
1453         if (I->getOperand(1)->getType()->isStructTy())
1454           continue;
1455         
1456         // If this is a two-operand instruction, and if both operands are
1457         // undefs, the result stays undef.
1458         Op1LV = getValueState(I->getOperand(1));
1459         if (Op0LV.isUndefined() && Op1LV.isUndefined())
1460           continue;
1461       }
1462       
1463       // If this is an instructions whose result is defined even if the input is
1464       // not fully defined, propagate the information.
1465       Type *ITy = I->getType();
1466       switch (I->getOpcode()) {
1467       default: break;          // Leave the instruction as an undef.
1468       case Instruction::ZExt:
1469         // After a zero extend, we know the top part is zero.  SExt doesn't have
1470         // to be handled here, because we don't know whether the top part is 1's
1471         // or 0's.
1472       case Instruction::SIToFP:  // some FP values are not possible, just use 0.
1473       case Instruction::UIToFP:  // some FP values are not possible, just use 0.
1474         markForcedConstant(I, Constant::getNullValue(ITy));
1475         return true;
1476       case Instruction::Mul:
1477       case Instruction::And:
1478         // undef * X -> 0.   X could be zero.
1479         // undef & X -> 0.   X could be zero.
1480         markForcedConstant(I, Constant::getNullValue(ITy));
1481         return true;
1482
1483       case Instruction::Or:
1484         // undef | X -> -1.   X could be -1.
1485         markForcedConstant(I, Constant::getAllOnesValue(ITy));
1486         return true;
1487
1488       case Instruction::SDiv:
1489       case Instruction::UDiv:
1490       case Instruction::SRem:
1491       case Instruction::URem:
1492         // X / undef -> undef.  No change.
1493         // X % undef -> undef.  No change.
1494         if (Op1LV.isUndefined()) break;
1495         
1496         // undef / X -> 0.   X could be maxint.
1497         // undef % X -> 0.   X could be 1.
1498         markForcedConstant(I, Constant::getNullValue(ITy));
1499         return true;
1500         
1501       case Instruction::AShr:
1502         // undef >>s X -> undef.  No change.
1503         if (Op0LV.isUndefined()) break;
1504         
1505         // X >>s undef -> X.  X could be 0, X could have the high-bit known set.
1506         if (Op0LV.isConstant())
1507           markForcedConstant(I, Op0LV.getConstant());
1508         else
1509           markOverdefined(I);
1510         return true;
1511       case Instruction::LShr:
1512       case Instruction::Shl:
1513         // undef >> X -> undef.  No change.
1514         // undef << X -> undef.  No change.
1515         if (Op0LV.isUndefined()) break;
1516         
1517         // X >> undef -> 0.  X could be 0.
1518         // X << undef -> 0.  X could be 0.
1519         markForcedConstant(I, Constant::getNullValue(ITy));
1520         return true;
1521       case Instruction::Select:
1522         // undef ? X : Y  -> X or Y.  There could be commonality between X/Y.
1523         if (Op0LV.isUndefined()) {
1524           if (!Op1LV.isConstant())  // Pick the constant one if there is any.
1525             Op1LV = getValueState(I->getOperand(2));
1526         } else if (Op1LV.isUndefined()) {
1527           // c ? undef : undef -> undef.  No change.
1528           Op1LV = getValueState(I->getOperand(2));
1529           if (Op1LV.isUndefined())
1530             break;
1531           // Otherwise, c ? undef : x -> x.
1532         } else {
1533           // Leave Op1LV as Operand(1)'s LatticeValue.
1534         }
1535         
1536         if (Op1LV.isConstant())
1537           markForcedConstant(I, Op1LV.getConstant());
1538         else
1539           markOverdefined(I);
1540         return true;
1541       case Instruction::Call:
1542         // If a call has an undef result, it is because it is constant foldable
1543         // but one of the inputs was undef.  Just force the result to
1544         // overdefined.
1545         markOverdefined(I);
1546         return true;
1547       }
1548     }
1549   
1550     // Check to see if we have a branch or switch on an undefined value.  If so
1551     // we force the branch to go one way or the other to make the successor
1552     // values live.  It doesn't really matter which way we force it.
1553     TerminatorInst *TI = BB->getTerminator();
1554     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1555       if (!BI->isConditional()) continue;
1556       if (!getValueState(BI->getCondition()).isUndefined())
1557         continue;
1558     
1559       // If the input to SCCP is actually branch on undef, fix the undef to
1560       // false.
1561       if (isa<UndefValue>(BI->getCondition())) {
1562         BI->setCondition(ConstantInt::getFalse(BI->getContext()));
1563         markEdgeExecutable(BB, TI->getSuccessor(1));
1564         return true;
1565       }
1566       
1567       // Otherwise, it is a branch on a symbolic value which is currently
1568       // considered to be undef.  Handle this by forcing the input value to the
1569       // branch to false.
1570       markForcedConstant(BI->getCondition(),
1571                          ConstantInt::getFalse(TI->getContext()));
1572       return true;
1573     }
1574     
1575     if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1576       if (SI->getNumSuccessors() < 2)   // no cases
1577         continue;
1578       if (!getValueState(SI->getCondition()).isUndefined())
1579         continue;
1580       
1581       // If the input to SCCP is actually switch on undef, fix the undef to
1582       // the first constant.
1583       if (isa<UndefValue>(SI->getCondition())) {
1584         SI->setCondition(SI->getCaseValue(1));
1585         markEdgeExecutable(BB, TI->getSuccessor(1));
1586         return true;
1587       }
1588       
1589       markForcedConstant(SI->getCondition(), SI->getCaseValue(1));
1590       return true;
1591     }
1592   }
1593
1594   return false;
1595 }
1596
1597
1598 namespace {
1599   //===--------------------------------------------------------------------===//
1600   //
1601   /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1602   /// Sparse Conditional Constant Propagator.
1603   ///
1604   struct SCCP : public FunctionPass {
1605     static char ID; // Pass identification, replacement for typeid
1606     SCCP() : FunctionPass(ID) {
1607       initializeSCCPPass(*PassRegistry::getPassRegistry());
1608     }
1609
1610     // runOnFunction - Run the Sparse Conditional Constant Propagation
1611     // algorithm, and return true if the function was modified.
1612     //
1613     bool runOnFunction(Function &F);
1614   };
1615 } // end anonymous namespace
1616
1617 char SCCP::ID = 0;
1618 INITIALIZE_PASS(SCCP, "sccp",
1619                 "Sparse Conditional Constant Propagation", false, false)
1620
1621 // createSCCPPass - This is the public interface to this file.
1622 FunctionPass *llvm::createSCCPPass() {
1623   return new SCCP();
1624 }
1625
1626 static void DeleteInstructionInBlock(BasicBlock *BB) {
1627   DEBUG(dbgs() << "  BasicBlock Dead:" << *BB);
1628   ++NumDeadBlocks;
1629   
1630   // Delete the instructions backwards, as it has a reduced likelihood of
1631   // having to update as many def-use and use-def chains.
1632   while (!isa<TerminatorInst>(BB->begin())) {
1633     Instruction *I = --BasicBlock::iterator(BB->getTerminator());
1634     
1635     if (!I->use_empty())
1636       I->replaceAllUsesWith(UndefValue::get(I->getType()));
1637     BB->getInstList().erase(I);
1638     ++NumInstRemoved;
1639   }
1640 }
1641
1642 // runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1643 // and return true if the function was modified.
1644 //
1645 bool SCCP::runOnFunction(Function &F) {
1646   DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
1647   SCCPSolver Solver(getAnalysisIfAvailable<TargetData>());
1648
1649   // Mark the first block of the function as being executable.
1650   Solver.MarkBlockExecutable(F.begin());
1651
1652   // Mark all arguments to the function as being overdefined.
1653   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
1654     Solver.markAnythingOverdefined(AI);
1655
1656   // Solve for constants.
1657   bool ResolvedUndefs = true;
1658   while (ResolvedUndefs) {
1659     Solver.Solve();
1660     DEBUG(dbgs() << "RESOLVING UNDEFs\n");
1661     ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1662   }
1663
1664   bool MadeChanges = false;
1665
1666   // If we decided that there are basic blocks that are dead in this function,
1667   // delete their contents now.  Note that we cannot actually delete the blocks,
1668   // as we cannot modify the CFG of the function.
1669
1670   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1671     if (!Solver.isBlockExecutable(BB)) {
1672       DeleteInstructionInBlock(BB);
1673       MadeChanges = true;
1674       continue;
1675     }
1676   
1677     // Iterate over all of the instructions in a function, replacing them with
1678     // constants if we have found them to be of constant values.
1679     //
1680     for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1681       Instruction *Inst = BI++;
1682       if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1683         continue;
1684       
1685       // TODO: Reconstruct structs from their elements.
1686       if (Inst->getType()->isStructTy())
1687         continue;
1688       
1689       LatticeVal IV = Solver.getLatticeValueFor(Inst);
1690       if (IV.isOverdefined())
1691         continue;
1692       
1693       Constant *Const = IV.isConstant()
1694         ? IV.getConstant() : UndefValue::get(Inst->getType());
1695       DEBUG(dbgs() << "  Constant: " << *Const << " = " << *Inst);
1696
1697       // Replaces all of the uses of a variable with uses of the constant.
1698       Inst->replaceAllUsesWith(Const);
1699       
1700       // Delete the instruction.
1701       Inst->eraseFromParent();
1702       
1703       // Hey, we just changed something!
1704       MadeChanges = true;
1705       ++NumInstRemoved;
1706     }
1707   }
1708
1709   return MadeChanges;
1710 }
1711
1712 namespace {
1713   //===--------------------------------------------------------------------===//
1714   //
1715   /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1716   /// Constant Propagation.
1717   ///
1718   struct IPSCCP : public ModulePass {
1719     static char ID;
1720     IPSCCP() : ModulePass(ID) {
1721       initializeIPSCCPPass(*PassRegistry::getPassRegistry());
1722     }
1723     bool runOnModule(Module &M);
1724   };
1725 } // end anonymous namespace
1726
1727 char IPSCCP::ID = 0;
1728 INITIALIZE_PASS(IPSCCP, "ipsccp",
1729                 "Interprocedural Sparse Conditional Constant Propagation",
1730                 false, false)
1731
1732 // createIPSCCPPass - This is the public interface to this file.
1733 ModulePass *llvm::createIPSCCPPass() {
1734   return new IPSCCP();
1735 }
1736
1737
1738 static bool AddressIsTaken(const GlobalValue *GV) {
1739   // Delete any dead constantexpr klingons.
1740   GV->removeDeadConstantUsers();
1741
1742   for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1743        UI != E; ++UI) {
1744     const User *U = *UI;
1745     if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
1746       if (SI->getOperand(0) == GV || SI->isVolatile())
1747         return true;  // Storing addr of GV.
1748     } else if (isa<InvokeInst>(U) || isa<CallInst>(U)) {
1749       // Make sure we are calling the function, not passing the address.
1750       ImmutableCallSite CS(cast<Instruction>(U));
1751       if (!CS.isCallee(UI))
1752         return true;
1753     } else if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
1754       if (LI->isVolatile())
1755         return true;
1756     } else if (isa<BlockAddress>(U)) {
1757       // blockaddress doesn't take the address of the function, it takes addr
1758       // of label.
1759     } else {
1760       return true;
1761     }
1762   }
1763   return false;
1764 }
1765
1766 bool IPSCCP::runOnModule(Module &M) {
1767   SCCPSolver Solver(getAnalysisIfAvailable<TargetData>());
1768
1769   // AddressTakenFunctions - This set keeps track of the address-taken functions
1770   // that are in the input.  As IPSCCP runs through and simplifies code,
1771   // functions that were address taken can end up losing their
1772   // address-taken-ness.  Because of this, we keep track of their addresses from
1773   // the first pass so we can use them for the later simplification pass.
1774   SmallPtrSet<Function*, 32> AddressTakenFunctions;
1775   
1776   // Loop over all functions, marking arguments to those with their addresses
1777   // taken or that are external as overdefined.
1778   //
1779   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1780     if (F->isDeclaration())
1781       continue;
1782     
1783     // If this is a strong or ODR definition of this function, then we can
1784     // propagate information about its result into callsites of it.
1785     if (!F->mayBeOverridden())
1786       Solver.AddTrackedFunction(F);
1787     
1788     // If this function only has direct calls that we can see, we can track its
1789     // arguments and return value aggressively, and can assume it is not called
1790     // unless we see evidence to the contrary.
1791     if (F->hasLocalLinkage()) {
1792       if (AddressIsTaken(F))
1793         AddressTakenFunctions.insert(F);
1794       else {
1795         Solver.AddArgumentTrackedFunction(F);
1796         continue;
1797       }
1798     }
1799
1800     // Assume the function is called.
1801     Solver.MarkBlockExecutable(F->begin());
1802     
1803     // Assume nothing about the incoming arguments.
1804     for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1805          AI != E; ++AI)
1806       Solver.markAnythingOverdefined(AI);
1807   }
1808
1809   // Loop over global variables.  We inform the solver about any internal global
1810   // variables that do not have their 'addresses taken'.  If they don't have
1811   // their addresses taken, we can propagate constants through them.
1812   for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1813        G != E; ++G)
1814     if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
1815       Solver.TrackValueOfGlobalVariable(G);
1816
1817   // Solve for constants.
1818   bool ResolvedUndefs = true;
1819   while (ResolvedUndefs) {
1820     Solver.Solve();
1821
1822     DEBUG(dbgs() << "RESOLVING UNDEFS\n");
1823     ResolvedUndefs = false;
1824     for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1825       ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
1826   }
1827
1828   bool MadeChanges = false;
1829
1830   // Iterate over all of the instructions in the module, replacing them with
1831   // constants if we have found them to be of constant values.
1832   //
1833   SmallVector<BasicBlock*, 512> BlocksToErase;
1834
1835   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1836     if (Solver.isBlockExecutable(F->begin())) {
1837       for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1838            AI != E; ++AI) {
1839         if (AI->use_empty() || AI->getType()->isStructTy()) continue;
1840         
1841         // TODO: Could use getStructLatticeValueFor to find out if the entire
1842         // result is a constant and replace it entirely if so.
1843
1844         LatticeVal IV = Solver.getLatticeValueFor(AI);
1845         if (IV.isOverdefined()) continue;
1846         
1847         Constant *CST = IV.isConstant() ?
1848         IV.getConstant() : UndefValue::get(AI->getType());
1849         DEBUG(dbgs() << "***  Arg " << *AI << " = " << *CST <<"\n");
1850         
1851         // Replaces all of the uses of a variable with uses of the
1852         // constant.
1853         AI->replaceAllUsesWith(CST);
1854         ++IPNumArgsElimed;
1855       }
1856     }
1857
1858     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
1859       if (!Solver.isBlockExecutable(BB)) {
1860         DeleteInstructionInBlock(BB);
1861         MadeChanges = true;
1862
1863         TerminatorInst *TI = BB->getTerminator();
1864         for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1865           BasicBlock *Succ = TI->getSuccessor(i);
1866           if (!Succ->empty() && isa<PHINode>(Succ->begin()))
1867             TI->getSuccessor(i)->removePredecessor(BB);
1868         }
1869         if (!TI->use_empty())
1870           TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1871         TI->eraseFromParent();
1872
1873         if (&*BB != &F->front())
1874           BlocksToErase.push_back(BB);
1875         else
1876           new UnreachableInst(M.getContext(), BB);
1877         continue;
1878       }
1879       
1880       for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1881         Instruction *Inst = BI++;
1882         if (Inst->getType()->isVoidTy() || Inst->getType()->isStructTy())
1883           continue;
1884         
1885         // TODO: Could use getStructLatticeValueFor to find out if the entire
1886         // result is a constant and replace it entirely if so.
1887         
1888         LatticeVal IV = Solver.getLatticeValueFor(Inst);
1889         if (IV.isOverdefined())
1890           continue;
1891         
1892         Constant *Const = IV.isConstant()
1893           ? IV.getConstant() : UndefValue::get(Inst->getType());
1894         DEBUG(dbgs() << "  Constant: " << *Const << " = " << *Inst);
1895
1896         // Replaces all of the uses of a variable with uses of the
1897         // constant.
1898         Inst->replaceAllUsesWith(Const);
1899         
1900         // Delete the instruction.
1901         if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1902           Inst->eraseFromParent();
1903
1904         // Hey, we just changed something!
1905         MadeChanges = true;
1906         ++IPNumInstRemoved;
1907       }
1908     }
1909
1910     // Now that all instructions in the function are constant folded, erase dead
1911     // blocks, because we can now use ConstantFoldTerminator to get rid of
1912     // in-edges.
1913     for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1914       // If there are any PHI nodes in this successor, drop entries for BB now.
1915       BasicBlock *DeadBB = BlocksToErase[i];
1916       for (Value::use_iterator UI = DeadBB->use_begin(), UE = DeadBB->use_end();
1917            UI != UE; ) {
1918         // Grab the user and then increment the iterator early, as the user
1919         // will be deleted. Step past all adjacent uses from the same user.
1920         Instruction *I = dyn_cast<Instruction>(*UI);
1921         do { ++UI; } while (UI != UE && *UI == I);
1922
1923         // Ignore blockaddress users; BasicBlock's dtor will handle them.
1924         if (!I) continue;
1925
1926         bool Folded = ConstantFoldTerminator(I->getParent());
1927         if (!Folded) {
1928           // The constant folder may not have been able to fold the terminator
1929           // if this is a branch or switch on undef.  Fold it manually as a
1930           // branch to the first successor.
1931 #ifndef NDEBUG
1932           if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1933             assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1934                    "Branch should be foldable!");
1935           } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1936             assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1937           } else {
1938             llvm_unreachable("Didn't fold away reference to block!");
1939           }
1940 #endif
1941           
1942           // Make this an uncond branch to the first successor.
1943           TerminatorInst *TI = I->getParent()->getTerminator();
1944           BranchInst::Create(TI->getSuccessor(0), TI);
1945           
1946           // Remove entries in successor phi nodes to remove edges.
1947           for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1948             TI->getSuccessor(i)->removePredecessor(TI->getParent());
1949           
1950           // Remove the old terminator.
1951           TI->eraseFromParent();
1952         }
1953       }
1954
1955       // Finally, delete the basic block.
1956       F->getBasicBlockList().erase(DeadBB);
1957     }
1958     BlocksToErase.clear();
1959   }
1960
1961   // If we inferred constant or undef return values for a function, we replaced
1962   // all call uses with the inferred value.  This means we don't need to bother
1963   // actually returning anything from the function.  Replace all return
1964   // instructions with return undef.
1965   //
1966   // Do this in two stages: first identify the functions we should process, then
1967   // actually zap their returns.  This is important because we can only do this
1968   // if the address of the function isn't taken.  In cases where a return is the
1969   // last use of a function, the order of processing functions would affect
1970   // whether other functions are optimizable.
1971   SmallVector<ReturnInst*, 8> ReturnsToZap;
1972   
1973   // TODO: Process multiple value ret instructions also.
1974   const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
1975   for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
1976        E = RV.end(); I != E; ++I) {
1977     Function *F = I->first;
1978     if (I->second.isOverdefined() || F->getReturnType()->isVoidTy())
1979       continue;
1980   
1981     // We can only do this if we know that nothing else can call the function.
1982     if (!F->hasLocalLinkage() || AddressTakenFunctions.count(F))
1983       continue;
1984     
1985     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1986       if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1987         if (!isa<UndefValue>(RI->getOperand(0)))
1988           ReturnsToZap.push_back(RI);
1989   }
1990
1991   // Zap all returns which we've identified as zap to change.
1992   for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
1993     Function *F = ReturnsToZap[i]->getParent()->getParent();
1994     ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
1995   }
1996     
1997   // If we inferred constant or undef values for globals variables, we can delete
1998   // the global and any stores that remain to it.
1999   const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
2000   for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
2001          E = TG.end(); I != E; ++I) {
2002     GlobalVariable *GV = I->first;
2003     assert(!I->second.isOverdefined() &&
2004            "Overdefined values should have been taken out of the map!");
2005     DEBUG(dbgs() << "Found that GV '" << GV->getName() << "' is constant!\n");
2006     while (!GV->use_empty()) {
2007       StoreInst *SI = cast<StoreInst>(GV->use_back());
2008       SI->eraseFromParent();
2009     }
2010     M.getGlobalList().erase(GV);
2011     ++IPNumGlobalConst;
2012   }
2013
2014   return MadeChanges;
2015 }