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