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