LLVM API Documentation

SCCP.cpp
Go to the documentation of this file.
00001 //===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements sparse conditional constant propagation and merging:
00011 //
00012 // Specifically, this:
00013 //   * Assumes values are constant unless proven otherwise
00014 //   * Assumes BasicBlocks are dead unless proven otherwise
00015 //   * Proves values to be constant, and replaces them with constants
00016 //   * Proves conditional branches to be unconditional
00017 //
00018 //===----------------------------------------------------------------------===//
00019 
00020 #include "llvm/Transforms/Scalar.h"
00021 #include "llvm/ADT/DenseMap.h"
00022 #include "llvm/ADT/DenseSet.h"
00023 #include "llvm/ADT/PointerIntPair.h"
00024 #include "llvm/ADT/SmallPtrSet.h"
00025 #include "llvm/ADT/SmallVector.h"
00026 #include "llvm/ADT/Statistic.h"
00027 #include "llvm/Analysis/ConstantFolding.h"
00028 #include "llvm/IR/CallSite.h"
00029 #include "llvm/IR/Constants.h"
00030 #include "llvm/IR/DataLayout.h"
00031 #include "llvm/IR/DerivedTypes.h"
00032 #include "llvm/IR/InstVisitor.h"
00033 #include "llvm/IR/Instructions.h"
00034 #include "llvm/Pass.h"
00035 #include "llvm/Support/Debug.h"
00036 #include "llvm/Support/ErrorHandling.h"
00037 #include "llvm/Support/raw_ostream.h"
00038 #include "llvm/Target/TargetLibraryInfo.h"
00039 #include "llvm/Transforms/IPO.h"
00040 #include "llvm/Transforms/Utils/Local.h"
00041 #include <algorithm>
00042 using namespace llvm;
00043 
00044 #define DEBUG_TYPE "sccp"
00045 
00046 STATISTIC(NumInstRemoved, "Number of instructions removed");
00047 STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
00048 
00049 STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
00050 STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
00051 STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
00052 
00053 namespace {
00054 /// LatticeVal class - This class represents the different lattice values that
00055 /// an LLVM value may occupy.  It is a simple class with value semantics.
00056 ///
00057 class LatticeVal {
00058   enum LatticeValueTy {
00059     /// undefined - This LLVM Value has no known value yet.
00060     undefined,
00061 
00062     /// constant - This LLVM Value has a specific constant value.
00063     constant,
00064 
00065     /// forcedconstant - This LLVM Value was thought to be undef until
00066     /// ResolvedUndefsIn.  This is treated just like 'constant', but if merged
00067     /// with another (different) constant, it goes to overdefined, instead of
00068     /// asserting.
00069     forcedconstant,
00070 
00071     /// overdefined - This instruction is not known to be constant, and we know
00072     /// it has a value.
00073     overdefined
00074   };
00075 
00076   /// Val: This stores the current lattice value along with the Constant* for
00077   /// the constant if this is a 'constant' or 'forcedconstant' value.
00078   PointerIntPair<Constant *, 2, LatticeValueTy> Val;
00079 
00080   LatticeValueTy getLatticeValue() const {
00081     return Val.getInt();
00082   }
00083 
00084 public:
00085   LatticeVal() : Val(0, undefined) {}
00086 
00087   bool isUndefined() const { return getLatticeValue() == undefined; }
00088   bool isConstant() const {
00089     return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
00090   }
00091   bool isOverdefined() const { return getLatticeValue() == overdefined; }
00092 
00093   Constant *getConstant() const {
00094     assert(isConstant() && "Cannot get the constant of a non-constant!");
00095     return Val.getPointer();
00096   }
00097 
00098   /// markOverdefined - Return true if this is a change in status.
00099   bool markOverdefined() {
00100     if (isOverdefined())
00101       return false;
00102 
00103     Val.setInt(overdefined);
00104     return true;
00105   }
00106 
00107   /// markConstant - Return true if this is a change in status.
00108   bool markConstant(Constant *V) {
00109     if (getLatticeValue() == constant) { // Constant but not forcedconstant.
00110       assert(getConstant() == V && "Marking constant with different value");
00111       return false;
00112     }
00113 
00114     if (isUndefined()) {
00115       Val.setInt(constant);
00116       assert(V && "Marking constant with NULL");
00117       Val.setPointer(V);
00118     } else {
00119       assert(getLatticeValue() == forcedconstant &&
00120              "Cannot move from overdefined to constant!");
00121       // Stay at forcedconstant if the constant is the same.
00122       if (V == getConstant()) return false;
00123 
00124       // Otherwise, we go to overdefined.  Assumptions made based on the
00125       // forced value are possibly wrong.  Assuming this is another constant
00126       // could expose a contradiction.
00127       Val.setInt(overdefined);
00128     }
00129     return true;
00130   }
00131 
00132   /// getConstantInt - If this is a constant with a ConstantInt value, return it
00133   /// otherwise return null.
00134   ConstantInt *getConstantInt() const {
00135     if (isConstant())
00136       return dyn_cast<ConstantInt>(getConstant());
00137     return 0;
00138   }
00139 
00140   void markForcedConstant(Constant *V) {
00141     assert(isUndefined() && "Can't force a defined value!");
00142     Val.setInt(forcedconstant);
00143     Val.setPointer(V);
00144   }
00145 };
00146 } // end anonymous namespace.
00147 
00148 
00149 namespace {
00150 
00151 //===----------------------------------------------------------------------===//
00152 //
00153 /// SCCPSolver - This class is a general purpose solver for Sparse Conditional
00154 /// Constant Propagation.
00155 ///
00156 class SCCPSolver : public InstVisitor<SCCPSolver> {
00157   const DataLayout *DL;
00158   const TargetLibraryInfo *TLI;
00159   SmallPtrSet<BasicBlock*, 8> BBExecutable; // The BBs that are executable.
00160   DenseMap<Value*, LatticeVal> ValueState;  // The state each value is in.
00161 
00162   /// StructValueState - This maintains ValueState for values that have
00163   /// StructType, for example for formal arguments, calls, insertelement, etc.
00164   ///
00165   DenseMap<std::pair<Value*, unsigned>, LatticeVal> StructValueState;
00166 
00167   /// GlobalValue - If we are tracking any values for the contents of a global
00168   /// variable, we keep a mapping from the constant accessor to the element of
00169   /// the global, to the currently known value.  If the value becomes
00170   /// overdefined, it's entry is simply removed from this map.
00171   DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
00172 
00173   /// TrackedRetVals - If we are tracking arguments into and the return
00174   /// value out of a function, it will have an entry in this map, indicating
00175   /// what the known return value for the function is.
00176   DenseMap<Function*, LatticeVal> TrackedRetVals;
00177 
00178   /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
00179   /// that return multiple values.
00180   DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
00181 
00182   /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
00183   /// represented here for efficient lookup.
00184   SmallPtrSet<Function*, 16> MRVFunctionsTracked;
00185 
00186   /// TrackingIncomingArguments - This is the set of functions for whose
00187   /// arguments we make optimistic assumptions about and try to prove as
00188   /// constants.
00189   SmallPtrSet<Function*, 16> TrackingIncomingArguments;
00190 
00191   /// The reason for two worklists is that overdefined is the lowest state
00192   /// on the lattice, and moving things to overdefined as fast as possible
00193   /// makes SCCP converge much faster.
00194   ///
00195   /// By having a separate worklist, we accomplish this because everything
00196   /// possibly overdefined will become overdefined at the soonest possible
00197   /// point.
00198   SmallVector<Value*, 64> OverdefinedInstWorkList;
00199   SmallVector<Value*, 64> InstWorkList;
00200 
00201 
00202   SmallVector<BasicBlock*, 64>  BBWorkList;  // The BasicBlock work list
00203 
00204   /// KnownFeasibleEdges - Entries in this set are edges which have already had
00205   /// PHI nodes retriggered.
00206   typedef std::pair<BasicBlock*, BasicBlock*> Edge;
00207   DenseSet<Edge> KnownFeasibleEdges;
00208 public:
00209   SCCPSolver(const DataLayout *DL, const TargetLibraryInfo *tli)
00210     : DL(DL), TLI(tli) {}
00211 
00212   /// MarkBlockExecutable - This method can be used by clients to mark all of
00213   /// the blocks that are known to be intrinsically live in the processed unit.
00214   ///
00215   /// This returns true if the block was not considered live before.
00216   bool MarkBlockExecutable(BasicBlock *BB) {
00217     if (!BBExecutable.insert(BB)) return false;
00218     DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << '\n');
00219     BBWorkList.push_back(BB);  // Add the block to the work list!
00220     return true;
00221   }
00222 
00223   /// TrackValueOfGlobalVariable - Clients can use this method to
00224   /// inform the SCCPSolver that it should track loads and stores to the
00225   /// specified global variable if it can.  This is only legal to call if
00226   /// performing Interprocedural SCCP.
00227   void TrackValueOfGlobalVariable(GlobalVariable *GV) {
00228     // We only track the contents of scalar globals.
00229     if (GV->getType()->getElementType()->isSingleValueType()) {
00230       LatticeVal &IV = TrackedGlobals[GV];
00231       if (!isa<UndefValue>(GV->getInitializer()))
00232         IV.markConstant(GV->getInitializer());
00233     }
00234   }
00235 
00236   /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
00237   /// and out of the specified function (which cannot have its address taken),
00238   /// this method must be called.
00239   void AddTrackedFunction(Function *F) {
00240     // Add an entry, F -> undef.
00241     if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
00242       MRVFunctionsTracked.insert(F);
00243       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
00244         TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
00245                                                      LatticeVal()));
00246     } else
00247       TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
00248   }
00249 
00250   void AddArgumentTrackedFunction(Function *F) {
00251     TrackingIncomingArguments.insert(F);
00252   }
00253 
00254   /// Solve - Solve for constants and executable blocks.
00255   ///
00256   void Solve();
00257 
00258   /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
00259   /// that branches on undef values cannot reach any of their successors.
00260   /// However, this is not a safe assumption.  After we solve dataflow, this
00261   /// method should be use to handle this.  If this returns true, the solver
00262   /// should be rerun.
00263   bool ResolvedUndefsIn(Function &F);
00264 
00265   bool isBlockExecutable(BasicBlock *BB) const {
00266     return BBExecutable.count(BB);
00267   }
00268 
00269   LatticeVal getLatticeValueFor(Value *V) const {
00270     DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
00271     assert(I != ValueState.end() && "V is not in valuemap!");
00272     return I->second;
00273   }
00274 
00275   /// getTrackedRetVals - Get the inferred return value map.
00276   ///
00277   const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
00278     return TrackedRetVals;
00279   }
00280 
00281   /// getTrackedGlobals - Get and return the set of inferred initializers for
00282   /// global variables.
00283   const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
00284     return TrackedGlobals;
00285   }
00286 
00287   void markOverdefined(Value *V) {
00288     assert(!V->getType()->isStructTy() && "Should use other method");
00289     markOverdefined(ValueState[V], V);
00290   }
00291 
00292   /// markAnythingOverdefined - Mark the specified value overdefined.  This
00293   /// works with both scalars and structs.
00294   void markAnythingOverdefined(Value *V) {
00295     if (StructType *STy = dyn_cast<StructType>(V->getType()))
00296       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
00297         markOverdefined(getStructValueState(V, i), V);
00298     else
00299       markOverdefined(V);
00300   }
00301 
00302 private:
00303   // markConstant - Make a value be marked as "constant".  If the value
00304   // is not already a constant, add it to the instruction work list so that
00305   // the users of the instruction are updated later.
00306   //
00307   void markConstant(LatticeVal &IV, Value *V, Constant *C) {
00308     if (!IV.markConstant(C)) return;
00309     DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
00310     if (IV.isOverdefined())
00311       OverdefinedInstWorkList.push_back(V);
00312     else
00313       InstWorkList.push_back(V);
00314   }
00315 
00316   void markConstant(Value *V, Constant *C) {
00317     assert(!V->getType()->isStructTy() && "Should use other method");
00318     markConstant(ValueState[V], V, C);
00319   }
00320 
00321   void markForcedConstant(Value *V, Constant *C) {
00322     assert(!V->getType()->isStructTy() && "Should use other method");
00323     LatticeVal &IV = ValueState[V];
00324     IV.markForcedConstant(C);
00325     DEBUG(dbgs() << "markForcedConstant: " << *C << ": " << *V << '\n');
00326     if (IV.isOverdefined())
00327       OverdefinedInstWorkList.push_back(V);
00328     else
00329       InstWorkList.push_back(V);
00330   }
00331 
00332 
00333   // markOverdefined - Make a value be marked as "overdefined". If the
00334   // value is not already overdefined, add it to the overdefined instruction
00335   // work list so that the users of the instruction are updated later.
00336   void markOverdefined(LatticeVal &IV, Value *V) {
00337     if (!IV.markOverdefined()) return;
00338 
00339     DEBUG(dbgs() << "markOverdefined: ";
00340           if (Function *F = dyn_cast<Function>(V))
00341             dbgs() << "Function '" << F->getName() << "'\n";
00342           else
00343             dbgs() << *V << '\n');
00344     // Only instructions go on the work list
00345     OverdefinedInstWorkList.push_back(V);
00346   }
00347 
00348   void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
00349     if (IV.isOverdefined() || MergeWithV.isUndefined())
00350       return;  // Noop.
00351     if (MergeWithV.isOverdefined())
00352       markOverdefined(IV, V);
00353     else if (IV.isUndefined())
00354       markConstant(IV, V, MergeWithV.getConstant());
00355     else if (IV.getConstant() != MergeWithV.getConstant())
00356       markOverdefined(IV, V);
00357   }
00358 
00359   void mergeInValue(Value *V, LatticeVal MergeWithV) {
00360     assert(!V->getType()->isStructTy() && "Should use other method");
00361     mergeInValue(ValueState[V], V, MergeWithV);
00362   }
00363 
00364 
00365   /// getValueState - Return the LatticeVal object that corresponds to the
00366   /// value.  This function handles the case when the value hasn't been seen yet
00367   /// by properly seeding constants etc.
00368   LatticeVal &getValueState(Value *V) {
00369     assert(!V->getType()->isStructTy() && "Should use getStructValueState");
00370 
00371     std::pair<DenseMap<Value*, LatticeVal>::iterator, bool> I =
00372       ValueState.insert(std::make_pair(V, LatticeVal()));
00373     LatticeVal &LV = I.first->second;
00374 
00375     if (!I.second)
00376       return LV;  // Common case, already in the map.
00377 
00378     if (Constant *C = dyn_cast<Constant>(V)) {
00379       // Undef values remain undefined.
00380       if (!isa<UndefValue>(V))
00381         LV.markConstant(C);          // Constants are constant
00382     }
00383 
00384     // All others are underdefined by default.
00385     return LV;
00386   }
00387 
00388   /// getStructValueState - Return the LatticeVal object that corresponds to the
00389   /// value/field pair.  This function handles the case when the value hasn't
00390   /// been seen yet by properly seeding constants etc.
00391   LatticeVal &getStructValueState(Value *V, unsigned i) {
00392     assert(V->getType()->isStructTy() && "Should use getValueState");
00393     assert(i < cast<StructType>(V->getType())->getNumElements() &&
00394            "Invalid element #");
00395 
00396     std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator,
00397               bool> I = StructValueState.insert(
00398                         std::make_pair(std::make_pair(V, i), LatticeVal()));
00399     LatticeVal &LV = I.first->second;
00400 
00401     if (!I.second)
00402       return LV;  // Common case, already in the map.
00403 
00404     if (Constant *C = dyn_cast<Constant>(V)) {
00405       Constant *Elt = C->getAggregateElement(i);
00406 
00407       if (Elt == 0)
00408         LV.markOverdefined();      // Unknown sort of constant.
00409       else if (isa<UndefValue>(Elt))
00410         ; // Undef values remain undefined.
00411       else
00412         LV.markConstant(Elt);      // Constants are constant.
00413     }
00414 
00415     // All others are underdefined by default.
00416     return LV;
00417   }
00418 
00419 
00420   /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
00421   /// work list if it is not already executable.
00422   void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
00423     if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
00424       return;  // This edge is already known to be executable!
00425 
00426     if (!MarkBlockExecutable(Dest)) {
00427       // If the destination is already executable, we just made an *edge*
00428       // feasible that wasn't before.  Revisit the PHI nodes in the block
00429       // because they have potentially new operands.
00430       DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
00431             << " -> " << Dest->getName() << '\n');
00432 
00433       PHINode *PN;
00434       for (BasicBlock::iterator I = Dest->begin();
00435            (PN = dyn_cast<PHINode>(I)); ++I)
00436         visitPHINode(*PN);
00437     }
00438   }
00439 
00440   // getFeasibleSuccessors - Return a vector of booleans to indicate which
00441   // successors are reachable from a given terminator instruction.
00442   //
00443   void getFeasibleSuccessors(TerminatorInst &TI, SmallVectorImpl<bool> &Succs);
00444 
00445   // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
00446   // block to the 'To' basic block is currently feasible.
00447   //
00448   bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
00449 
00450   // OperandChangedState - This method is invoked on all of the users of an
00451   // instruction that was just changed state somehow.  Based on this
00452   // information, we need to update the specified user of this instruction.
00453   //
00454   void OperandChangedState(Instruction *I) {
00455     if (BBExecutable.count(I->getParent()))   // Inst is executable?
00456       visit(*I);
00457   }
00458 
00459 private:
00460   friend class InstVisitor<SCCPSolver>;
00461 
00462   // visit implementations - Something changed in this instruction.  Either an
00463   // operand made a transition, or the instruction is newly executable.  Change
00464   // the value type of I to reflect these changes if appropriate.
00465   void visitPHINode(PHINode &I);
00466 
00467   // Terminators
00468   void visitReturnInst(ReturnInst &I);
00469   void visitTerminatorInst(TerminatorInst &TI);
00470 
00471   void visitCastInst(CastInst &I);
00472   void visitSelectInst(SelectInst &I);
00473   void visitBinaryOperator(Instruction &I);
00474   void visitCmpInst(CmpInst &I);
00475   void visitExtractElementInst(ExtractElementInst &I);
00476   void visitInsertElementInst(InsertElementInst &I);
00477   void visitShuffleVectorInst(ShuffleVectorInst &I);
00478   void visitExtractValueInst(ExtractValueInst &EVI);
00479   void visitInsertValueInst(InsertValueInst &IVI);
00480   void visitLandingPadInst(LandingPadInst &I) { markAnythingOverdefined(&I); }
00481 
00482   // Instructions that cannot be folded away.
00483   void visitStoreInst     (StoreInst &I);
00484   void visitLoadInst      (LoadInst &I);
00485   void visitGetElementPtrInst(GetElementPtrInst &I);
00486   void visitCallInst      (CallInst &I) {
00487     visitCallSite(&I);
00488   }
00489   void visitInvokeInst    (InvokeInst &II) {
00490     visitCallSite(&II);
00491     visitTerminatorInst(II);
00492   }
00493   void visitCallSite      (CallSite CS);
00494   void visitResumeInst    (TerminatorInst &I) { /*returns void*/ }
00495   void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
00496   void visitFenceInst     (FenceInst &I) { /*returns void*/ }
00497   void visitAtomicCmpXchgInst (AtomicCmpXchgInst &I) { markOverdefined(&I); }
00498   void visitAtomicRMWInst (AtomicRMWInst &I) { markOverdefined(&I); }
00499   void visitAllocaInst    (Instruction &I) { markOverdefined(&I); }
00500   void visitVAArgInst     (Instruction &I) { markAnythingOverdefined(&I); }
00501 
00502   void visitInstruction(Instruction &I) {
00503     // If a new instruction is added to LLVM that we don't handle.
00504     dbgs() << "SCCP: Don't know how to handle: " << I << '\n';
00505     markAnythingOverdefined(&I);   // Just in case
00506   }
00507 };
00508 
00509 } // end anonymous namespace
00510 
00511 
00512 // getFeasibleSuccessors - Return a vector of booleans to indicate which
00513 // successors are reachable from a given terminator instruction.
00514 //
00515 void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
00516                                        SmallVectorImpl<bool> &Succs) {
00517   Succs.resize(TI.getNumSuccessors());
00518   if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
00519     if (BI->isUnconditional()) {
00520       Succs[0] = true;
00521       return;
00522     }
00523 
00524     LatticeVal BCValue = getValueState(BI->getCondition());
00525     ConstantInt *CI = BCValue.getConstantInt();
00526     if (CI == 0) {
00527       // Overdefined condition variables, and branches on unfoldable constant
00528       // conditions, mean the branch could go either way.
00529       if (!BCValue.isUndefined())
00530         Succs[0] = Succs[1] = true;
00531       return;
00532     }
00533 
00534     // Constant condition variables mean the branch can only go a single way.
00535     Succs[CI->isZero()] = true;
00536     return;
00537   }
00538 
00539   if (isa<InvokeInst>(TI)) {
00540     // Invoke instructions successors are always executable.
00541     Succs[0] = Succs[1] = true;
00542     return;
00543   }
00544 
00545   if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
00546     if (!SI->getNumCases()) {
00547       Succs[0] = true;
00548       return;
00549     }
00550     LatticeVal SCValue = getValueState(SI->getCondition());
00551     ConstantInt *CI = SCValue.getConstantInt();
00552 
00553     if (CI == 0) {   // Overdefined or undefined condition?
00554       // All destinations are executable!
00555       if (!SCValue.isUndefined())
00556         Succs.assign(TI.getNumSuccessors(), true);
00557       return;
00558     }
00559 
00560     Succs[SI->findCaseValue(CI).getSuccessorIndex()] = true;
00561     return;
00562   }
00563 
00564   // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
00565   if (isa<IndirectBrInst>(&TI)) {
00566     // Just mark all destinations executable!
00567     Succs.assign(TI.getNumSuccessors(), true);
00568     return;
00569   }
00570 
00571 #ifndef NDEBUG
00572   dbgs() << "Unknown terminator instruction: " << TI << '\n';
00573 #endif
00574   llvm_unreachable("SCCP: Don't know how to handle this terminator!");
00575 }
00576 
00577 
00578 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
00579 // block to the 'To' basic block is currently feasible.
00580 //
00581 bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
00582   assert(BBExecutable.count(To) && "Dest should always be alive!");
00583 
00584   // Make sure the source basic block is executable!!
00585   if (!BBExecutable.count(From)) return false;
00586 
00587   // Check to make sure this edge itself is actually feasible now.
00588   TerminatorInst *TI = From->getTerminator();
00589   if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
00590     if (BI->isUnconditional())
00591       return true;
00592 
00593     LatticeVal BCValue = getValueState(BI->getCondition());
00594 
00595     // Overdefined condition variables mean the branch could go either way,
00596     // undef conditions mean that neither edge is feasible yet.
00597     ConstantInt *CI = BCValue.getConstantInt();
00598     if (CI == 0)
00599       return !BCValue.isUndefined();
00600 
00601     // Constant condition variables mean the branch can only go a single way.
00602     return BI->getSuccessor(CI->isZero()) == To;
00603   }
00604 
00605   // Invoke instructions successors are always executable.
00606   if (isa<InvokeInst>(TI))
00607     return true;
00608 
00609   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
00610     if (SI->getNumCases() < 1)
00611       return true;
00612 
00613     LatticeVal SCValue = getValueState(SI->getCondition());
00614     ConstantInt *CI = SCValue.getConstantInt();
00615 
00616     if (CI == 0)
00617       return !SCValue.isUndefined();
00618 
00619     return SI->findCaseValue(CI).getCaseSuccessor() == To;
00620   }
00621 
00622   // Just mark all destinations executable!
00623   // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
00624   if (isa<IndirectBrInst>(TI))
00625     return true;
00626 
00627 #ifndef NDEBUG
00628   dbgs() << "Unknown terminator instruction: " << *TI << '\n';
00629 #endif
00630   llvm_unreachable(0);
00631 }
00632 
00633 // visit Implementations - Something changed in this instruction, either an
00634 // operand made a transition, or the instruction is newly executable.  Change
00635 // the value type of I to reflect these changes if appropriate.  This method
00636 // makes sure to do the following actions:
00637 //
00638 // 1. If a phi node merges two constants in, and has conflicting value coming
00639 //    from different branches, or if the PHI node merges in an overdefined
00640 //    value, then the PHI node becomes overdefined.
00641 // 2. If a phi node merges only constants in, and they all agree on value, the
00642 //    PHI node becomes a constant value equal to that.
00643 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
00644 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
00645 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
00646 // 6. If a conditional branch has a value that is constant, make the selected
00647 //    destination executable
00648 // 7. If a conditional branch has a value that is overdefined, make all
00649 //    successors executable.
00650 //
00651 void SCCPSolver::visitPHINode(PHINode &PN) {
00652   // If this PN returns a struct, just mark the result overdefined.
00653   // TODO: We could do a lot better than this if code actually uses this.
00654   if (PN.getType()->isStructTy())
00655     return markAnythingOverdefined(&PN);
00656 
00657   if (getValueState(&PN).isOverdefined())
00658     return;  // Quick exit
00659 
00660   // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
00661   // and slow us down a lot.  Just mark them overdefined.
00662   if (PN.getNumIncomingValues() > 64)
00663     return markOverdefined(&PN);
00664 
00665   // Look at all of the executable operands of the PHI node.  If any of them
00666   // are overdefined, the PHI becomes overdefined as well.  If they are all
00667   // constant, and they agree with each other, the PHI becomes the identical
00668   // constant.  If they are constant and don't agree, the PHI is overdefined.
00669   // If there are no executable operands, the PHI remains undefined.
00670   //
00671   Constant *OperandVal = 0;
00672   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
00673     LatticeVal IV = getValueState(PN.getIncomingValue(i));
00674     if (IV.isUndefined()) continue;  // Doesn't influence PHI node.
00675 
00676     if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
00677       continue;
00678 
00679     if (IV.isOverdefined())    // PHI node becomes overdefined!
00680       return markOverdefined(&PN);
00681 
00682     if (OperandVal == 0) {   // Grab the first value.
00683       OperandVal = IV.getConstant();
00684       continue;
00685     }
00686 
00687     // There is already a reachable operand.  If we conflict with it,
00688     // then the PHI node becomes overdefined.  If we agree with it, we
00689     // can continue on.
00690 
00691     // Check to see if there are two different constants merging, if so, the PHI
00692     // node is overdefined.
00693     if (IV.getConstant() != OperandVal)
00694       return markOverdefined(&PN);
00695   }
00696 
00697   // If we exited the loop, this means that the PHI node only has constant
00698   // arguments that agree with each other(and OperandVal is the constant) or
00699   // OperandVal is null because there are no defined incoming arguments.  If
00700   // this is the case, the PHI remains undefined.
00701   //
00702   if (OperandVal)
00703     markConstant(&PN, OperandVal);      // Acquire operand value
00704 }
00705 
00706 void SCCPSolver::visitReturnInst(ReturnInst &I) {
00707   if (I.getNumOperands() == 0) return;  // ret void
00708 
00709   Function *F = I.getParent()->getParent();
00710   Value *ResultOp = I.getOperand(0);
00711 
00712   // If we are tracking the return value of this function, merge it in.
00713   if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
00714     DenseMap<Function*, LatticeVal>::iterator TFRVI =
00715       TrackedRetVals.find(F);
00716     if (TFRVI != TrackedRetVals.end()) {
00717       mergeInValue(TFRVI->second, F, getValueState(ResultOp));
00718       return;
00719     }
00720   }
00721 
00722   // Handle functions that return multiple values.
00723   if (!TrackedMultipleRetVals.empty()) {
00724     if (StructType *STy = dyn_cast<StructType>(ResultOp->getType()))
00725       if (MRVFunctionsTracked.count(F))
00726         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
00727           mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
00728                        getStructValueState(ResultOp, i));
00729 
00730   }
00731 }
00732 
00733 void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
00734   SmallVector<bool, 16> SuccFeasible;
00735   getFeasibleSuccessors(TI, SuccFeasible);
00736 
00737   BasicBlock *BB = TI.getParent();
00738 
00739   // Mark all feasible successors executable.
00740   for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
00741     if (SuccFeasible[i])
00742       markEdgeExecutable(BB, TI.getSuccessor(i));
00743 }
00744 
00745 void SCCPSolver::visitCastInst(CastInst &I) {
00746   LatticeVal OpSt = getValueState(I.getOperand(0));
00747   if (OpSt.isOverdefined())          // Inherit overdefinedness of operand
00748     markOverdefined(&I);
00749   else if (OpSt.isConstant())        // Propagate constant value
00750     markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
00751                                            OpSt.getConstant(), I.getType()));
00752 }
00753 
00754 
00755 void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
00756   // If this returns a struct, mark all elements over defined, we don't track
00757   // structs in structs.
00758   if (EVI.getType()->isStructTy())
00759     return markAnythingOverdefined(&EVI);
00760 
00761   // If this is extracting from more than one level of struct, we don't know.
00762   if (EVI.getNumIndices() != 1)
00763     return markOverdefined(&EVI);
00764 
00765   Value *AggVal = EVI.getAggregateOperand();
00766   if (AggVal->getType()->isStructTy()) {
00767     unsigned i = *EVI.idx_begin();
00768     LatticeVal EltVal = getStructValueState(AggVal, i);
00769     mergeInValue(getValueState(&EVI), &EVI, EltVal);
00770   } else {
00771     // Otherwise, must be extracting from an array.
00772     return markOverdefined(&EVI);
00773   }
00774 }
00775 
00776 void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
00777   StructType *STy = dyn_cast<StructType>(IVI.getType());
00778   if (STy == 0)
00779     return markOverdefined(&IVI);
00780 
00781   // If this has more than one index, we can't handle it, drive all results to
00782   // undef.
00783   if (IVI.getNumIndices() != 1)
00784     return markAnythingOverdefined(&IVI);
00785 
00786   Value *Aggr = IVI.getAggregateOperand();
00787   unsigned Idx = *IVI.idx_begin();
00788 
00789   // Compute the result based on what we're inserting.
00790   for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
00791     // This passes through all values that aren't the inserted element.
00792     if (i != Idx) {
00793       LatticeVal EltVal = getStructValueState(Aggr, i);
00794       mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
00795       continue;
00796     }
00797 
00798     Value *Val = IVI.getInsertedValueOperand();
00799     if (Val->getType()->isStructTy())
00800       // We don't track structs in structs.
00801       markOverdefined(getStructValueState(&IVI, i), &IVI);
00802     else {
00803       LatticeVal InVal = getValueState(Val);
00804       mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
00805     }
00806   }
00807 }
00808 
00809 void SCCPSolver::visitSelectInst(SelectInst &I) {
00810   // If this select returns a struct, just mark the result overdefined.
00811   // TODO: We could do a lot better than this if code actually uses this.
00812   if (I.getType()->isStructTy())
00813     return markAnythingOverdefined(&I);
00814 
00815   LatticeVal CondValue = getValueState(I.getCondition());
00816   if (CondValue.isUndefined())
00817     return;
00818 
00819   if (ConstantInt *CondCB = CondValue.getConstantInt()) {
00820     Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
00821     mergeInValue(&I, getValueState(OpVal));
00822     return;
00823   }
00824 
00825   // Otherwise, the condition is overdefined or a constant we can't evaluate.
00826   // See if we can produce something better than overdefined based on the T/F
00827   // value.
00828   LatticeVal TVal = getValueState(I.getTrueValue());
00829   LatticeVal FVal = getValueState(I.getFalseValue());
00830 
00831   // select ?, C, C -> C.
00832   if (TVal.isConstant() && FVal.isConstant() &&
00833       TVal.getConstant() == FVal.getConstant())
00834     return markConstant(&I, FVal.getConstant());
00835 
00836   if (TVal.isUndefined())   // select ?, undef, X -> X.
00837     return mergeInValue(&I, FVal);
00838   if (FVal.isUndefined())   // select ?, X, undef -> X.
00839     return mergeInValue(&I, TVal);
00840   markOverdefined(&I);
00841 }
00842 
00843 // Handle Binary Operators.
00844 void SCCPSolver::visitBinaryOperator(Instruction &I) {
00845   LatticeVal V1State = getValueState(I.getOperand(0));
00846   LatticeVal V2State = getValueState(I.getOperand(1));
00847 
00848   LatticeVal &IV = ValueState[&I];
00849   if (IV.isOverdefined()) return;
00850 
00851   if (V1State.isConstant() && V2State.isConstant())
00852     return markConstant(IV, &I,
00853                         ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
00854                                           V2State.getConstant()));
00855 
00856   // If something is undef, wait for it to resolve.
00857   if (!V1State.isOverdefined() && !V2State.isOverdefined())
00858     return;
00859 
00860   // Otherwise, one of our operands is overdefined.  Try to produce something
00861   // better than overdefined with some tricks.
00862 
00863   // If this is an AND or OR with 0 or -1, it doesn't matter that the other
00864   // operand is overdefined.
00865   if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
00866     LatticeVal *NonOverdefVal = 0;
00867     if (!V1State.isOverdefined())
00868       NonOverdefVal = &V1State;
00869     else if (!V2State.isOverdefined())
00870       NonOverdefVal = &V2State;
00871 
00872     if (NonOverdefVal) {
00873       if (NonOverdefVal->isUndefined()) {
00874         // Could annihilate value.
00875         if (I.getOpcode() == Instruction::And)
00876           markConstant(IV, &I, Constant::getNullValue(I.getType()));
00877         else if (VectorType *PT = dyn_cast<VectorType>(I.getType()))
00878           markConstant(IV, &I, Constant::getAllOnesValue(PT));
00879         else
00880           markConstant(IV, &I,
00881                        Constant::getAllOnesValue(I.getType()));
00882         return;
00883       }
00884 
00885       if (I.getOpcode() == Instruction::And) {
00886         // X and 0 = 0
00887         if (NonOverdefVal->getConstant()->isNullValue())
00888           return markConstant(IV, &I, NonOverdefVal->getConstant());
00889       } else {
00890         if (ConstantInt *CI = NonOverdefVal->getConstantInt())
00891           if (CI->isAllOnesValue())     // X or -1 = -1
00892             return markConstant(IV, &I, NonOverdefVal->getConstant());
00893       }
00894     }
00895   }
00896 
00897 
00898   markOverdefined(&I);
00899 }
00900 
00901 // Handle ICmpInst instruction.
00902 void SCCPSolver::visitCmpInst(CmpInst &I) {
00903   LatticeVal V1State = getValueState(I.getOperand(0));
00904   LatticeVal V2State = getValueState(I.getOperand(1));
00905 
00906   LatticeVal &IV = ValueState[&I];
00907   if (IV.isOverdefined()) return;
00908 
00909   if (V1State.isConstant() && V2State.isConstant())
00910     return markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
00911                                                          V1State.getConstant(),
00912                                                         V2State.getConstant()));
00913 
00914   // If operands are still undefined, wait for it to resolve.
00915   if (!V1State.isOverdefined() && !V2State.isOverdefined())
00916     return;
00917 
00918   markOverdefined(&I);
00919 }
00920 
00921 void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
00922   // TODO : SCCP does not handle vectors properly.
00923   return markOverdefined(&I);
00924 
00925 #if 0
00926   LatticeVal &ValState = getValueState(I.getOperand(0));
00927   LatticeVal &IdxState = getValueState(I.getOperand(1));
00928 
00929   if (ValState.isOverdefined() || IdxState.isOverdefined())
00930     markOverdefined(&I);
00931   else if(ValState.isConstant() && IdxState.isConstant())
00932     markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
00933                                                      IdxState.getConstant()));
00934 #endif
00935 }
00936 
00937 void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
00938   // TODO : SCCP does not handle vectors properly.
00939   return markOverdefined(&I);
00940 #if 0
00941   LatticeVal &ValState = getValueState(I.getOperand(0));
00942   LatticeVal &EltState = getValueState(I.getOperand(1));
00943   LatticeVal &IdxState = getValueState(I.getOperand(2));
00944 
00945   if (ValState.isOverdefined() || EltState.isOverdefined() ||
00946       IdxState.isOverdefined())
00947     markOverdefined(&I);
00948   else if(ValState.isConstant() && EltState.isConstant() &&
00949           IdxState.isConstant())
00950     markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
00951                                                     EltState.getConstant(),
00952                                                     IdxState.getConstant()));
00953   else if (ValState.isUndefined() && EltState.isConstant() &&
00954            IdxState.isConstant())
00955     markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
00956                                                    EltState.getConstant(),
00957                                                    IdxState.getConstant()));
00958 #endif
00959 }
00960 
00961 void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
00962   // TODO : SCCP does not handle vectors properly.
00963   return markOverdefined(&I);
00964 #if 0
00965   LatticeVal &V1State   = getValueState(I.getOperand(0));
00966   LatticeVal &V2State   = getValueState(I.getOperand(1));
00967   LatticeVal &MaskState = getValueState(I.getOperand(2));
00968 
00969   if (MaskState.isUndefined() ||
00970       (V1State.isUndefined() && V2State.isUndefined()))
00971     return;  // Undefined output if mask or both inputs undefined.
00972 
00973   if (V1State.isOverdefined() || V2State.isOverdefined() ||
00974       MaskState.isOverdefined()) {
00975     markOverdefined(&I);
00976   } else {
00977     // A mix of constant/undef inputs.
00978     Constant *V1 = V1State.isConstant() ?
00979         V1State.getConstant() : UndefValue::get(I.getType());
00980     Constant *V2 = V2State.isConstant() ?
00981         V2State.getConstant() : UndefValue::get(I.getType());
00982     Constant *Mask = MaskState.isConstant() ?
00983       MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
00984     markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
00985   }
00986 #endif
00987 }
00988 
00989 // Handle getelementptr instructions.  If all operands are constants then we
00990 // can turn this into a getelementptr ConstantExpr.
00991 //
00992 void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
00993   if (ValueState[&I].isOverdefined()) return;
00994 
00995   SmallVector<Constant*, 8> Operands;
00996   Operands.reserve(I.getNumOperands());
00997 
00998   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
00999     LatticeVal State = getValueState(I.getOperand(i));
01000     if (State.isUndefined())
01001       return;  // Operands are not resolved yet.
01002 
01003     if (State.isOverdefined())
01004       return markOverdefined(&I);
01005 
01006     assert(State.isConstant() && "Unknown state!");
01007     Operands.push_back(State.getConstant());
01008   }
01009 
01010   Constant *Ptr = Operands[0];
01011   ArrayRef<Constant *> Indices(Operands.begin() + 1, Operands.end());
01012   markConstant(&I, ConstantExpr::getGetElementPtr(Ptr, Indices));
01013 }
01014 
01015 void SCCPSolver::visitStoreInst(StoreInst &SI) {
01016   // If this store is of a struct, ignore it.
01017   if (SI.getOperand(0)->getType()->isStructTy())
01018     return;
01019 
01020   if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
01021     return;
01022 
01023   GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
01024   DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
01025   if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
01026 
01027   // Get the value we are storing into the global, then merge it.
01028   mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
01029   if (I->second.isOverdefined())
01030     TrackedGlobals.erase(I);      // No need to keep tracking this!
01031 }
01032 
01033 
01034 // Handle load instructions.  If the operand is a constant pointer to a constant
01035 // global, we can replace the load with the loaded constant value!
01036 void SCCPSolver::visitLoadInst(LoadInst &I) {
01037   // If this load is of a struct, just mark the result overdefined.
01038   if (I.getType()->isStructTy())
01039     return markAnythingOverdefined(&I);
01040 
01041   LatticeVal PtrVal = getValueState(I.getOperand(0));
01042   if (PtrVal.isUndefined()) return;   // The pointer is not resolved yet!
01043 
01044   LatticeVal &IV = ValueState[&I];
01045   if (IV.isOverdefined()) return;
01046 
01047   if (!PtrVal.isConstant() || I.isVolatile())
01048     return markOverdefined(IV, &I);
01049 
01050   Constant *Ptr = PtrVal.getConstant();
01051 
01052   // load null -> null
01053   if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
01054     return markConstant(IV, &I, Constant::getNullValue(I.getType()));
01055 
01056   // Transform load (constant global) into the value loaded.
01057   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
01058     if (!TrackedGlobals.empty()) {
01059       // If we are tracking this global, merge in the known value for it.
01060       DenseMap<GlobalVariable*, LatticeVal>::iterator It =
01061         TrackedGlobals.find(GV);
01062       if (It != TrackedGlobals.end()) {
01063         mergeInValue(IV, &I, It->second);
01064         return;
01065       }
01066     }
01067   }
01068 
01069   // Transform load from a constant into a constant if possible.
01070   if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, DL))
01071     return markConstant(IV, &I, C);
01072 
01073   // Otherwise we cannot say for certain what value this load will produce.
01074   // Bail out.
01075   markOverdefined(IV, &I);
01076 }
01077 
01078 void SCCPSolver::visitCallSite(CallSite CS) {
01079   Function *F = CS.getCalledFunction();
01080   Instruction *I = CS.getInstruction();
01081 
01082   // The common case is that we aren't tracking the callee, either because we
01083   // are not doing interprocedural analysis or the callee is indirect, or is
01084   // external.  Handle these cases first.
01085   if (F == 0 || F->isDeclaration()) {
01086 CallOverdefined:
01087     // Void return and not tracking callee, just bail.
01088     if (I->getType()->isVoidTy()) return;
01089 
01090     // Otherwise, if we have a single return value case, and if the function is
01091     // a declaration, maybe we can constant fold it.
01092     if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
01093         canConstantFoldCallTo(F)) {
01094 
01095       SmallVector<Constant*, 8> Operands;
01096       for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
01097            AI != E; ++AI) {
01098         LatticeVal State = getValueState(*AI);
01099 
01100         if (State.isUndefined())
01101           return;  // Operands are not resolved yet.
01102         if (State.isOverdefined())
01103           return markOverdefined(I);
01104         assert(State.isConstant() && "Unknown state!");
01105         Operands.push_back(State.getConstant());
01106       }
01107 
01108       // If we can constant fold this, mark the result of the call as a
01109       // constant.
01110       if (Constant *C = ConstantFoldCall(F, Operands, TLI))
01111         return markConstant(I, C);
01112     }
01113 
01114     // Otherwise, we don't know anything about this call, mark it overdefined.
01115     return markAnythingOverdefined(I);
01116   }
01117 
01118   // If this is a local function that doesn't have its address taken, mark its
01119   // entry block executable and merge in the actual arguments to the call into
01120   // the formal arguments of the function.
01121   if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
01122     MarkBlockExecutable(F->begin());
01123 
01124     // Propagate information from this call site into the callee.
01125     CallSite::arg_iterator CAI = CS.arg_begin();
01126     for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
01127          AI != E; ++AI, ++CAI) {
01128       // If this argument is byval, and if the function is not readonly, there
01129       // will be an implicit copy formed of the input aggregate.
01130       if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
01131         markOverdefined(AI);
01132         continue;
01133       }
01134 
01135       if (StructType *STy = dyn_cast<StructType>(AI->getType())) {
01136         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
01137           LatticeVal CallArg = getStructValueState(*CAI, i);
01138           mergeInValue(getStructValueState(AI, i), AI, CallArg);
01139         }
01140       } else {
01141         mergeInValue(AI, getValueState(*CAI));
01142       }
01143     }
01144   }
01145 
01146   // If this is a single/zero retval case, see if we're tracking the function.
01147   if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
01148     if (!MRVFunctionsTracked.count(F))
01149       goto CallOverdefined;  // Not tracking this callee.
01150 
01151     // If we are tracking this callee, propagate the result of the function
01152     // into this call site.
01153     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
01154       mergeInValue(getStructValueState(I, i), I,
01155                    TrackedMultipleRetVals[std::make_pair(F, i)]);
01156   } else {
01157     DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
01158     if (TFRVI == TrackedRetVals.end())
01159       goto CallOverdefined;  // Not tracking this callee.
01160 
01161     // If so, propagate the return value of the callee into this call result.
01162     mergeInValue(I, TFRVI->second);
01163   }
01164 }
01165 
01166 void SCCPSolver::Solve() {
01167   // Process the work lists until they are empty!
01168   while (!BBWorkList.empty() || !InstWorkList.empty() ||
01169          !OverdefinedInstWorkList.empty()) {
01170     // Process the overdefined instruction's work list first, which drives other
01171     // things to overdefined more quickly.
01172     while (!OverdefinedInstWorkList.empty()) {
01173       Value *I = OverdefinedInstWorkList.pop_back_val();
01174 
01175       DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
01176 
01177       // "I" got into the work list because it either made the transition from
01178       // bottom to constant, or to overdefined.
01179       //
01180       // Anything on this worklist that is overdefined need not be visited
01181       // since all of its users will have already been marked as overdefined
01182       // Update all of the users of this instruction's value.
01183       //
01184       for (User *U : I->users())
01185         if (Instruction *UI = dyn_cast<Instruction>(U))
01186           OperandChangedState(UI);
01187     }
01188 
01189     // Process the instruction work list.
01190     while (!InstWorkList.empty()) {
01191       Value *I = InstWorkList.pop_back_val();
01192 
01193       DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
01194 
01195       // "I" got into the work list because it made the transition from undef to
01196       // constant.
01197       //
01198       // Anything on this worklist that is overdefined need not be visited
01199       // since all of its users will have already been marked as overdefined.
01200       // Update all of the users of this instruction's value.
01201       //
01202       if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
01203         for (User *U : I->users())
01204           if (Instruction *UI = dyn_cast<Instruction>(U))
01205             OperandChangedState(UI);
01206     }
01207 
01208     // Process the basic block work list.
01209     while (!BBWorkList.empty()) {
01210       BasicBlock *BB = BBWorkList.back();
01211       BBWorkList.pop_back();
01212 
01213       DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
01214 
01215       // Notify all instructions in this basic block that they are newly
01216       // executable.
01217       visit(BB);
01218     }
01219   }
01220 }
01221 
01222 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
01223 /// that branches on undef values cannot reach any of their successors.
01224 /// However, this is not a safe assumption.  After we solve dataflow, this
01225 /// method should be use to handle this.  If this returns true, the solver
01226 /// should be rerun.
01227 ///
01228 /// This method handles this by finding an unresolved branch and marking it one
01229 /// of the edges from the block as being feasible, even though the condition
01230 /// doesn't say it would otherwise be.  This allows SCCP to find the rest of the
01231 /// CFG and only slightly pessimizes the analysis results (by marking one,
01232 /// potentially infeasible, edge feasible).  This cannot usefully modify the
01233 /// constraints on the condition of the branch, as that would impact other users
01234 /// of the value.
01235 ///
01236 /// This scan also checks for values that use undefs, whose results are actually
01237 /// defined.  For example, 'zext i8 undef to i32' should produce all zeros
01238 /// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
01239 /// even if X isn't defined.
01240 bool SCCPSolver::ResolvedUndefsIn(Function &F) {
01241   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
01242     if (!BBExecutable.count(BB))
01243       continue;
01244 
01245     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
01246       // Look for instructions which produce undef values.
01247       if (I->getType()->isVoidTy()) continue;
01248 
01249       if (StructType *STy = dyn_cast<StructType>(I->getType())) {
01250         // Only a few things that can be structs matter for undef.
01251 
01252         // Tracked calls must never be marked overdefined in ResolvedUndefsIn.
01253         if (CallSite CS = CallSite(I))
01254           if (Function *F = CS.getCalledFunction())
01255             if (MRVFunctionsTracked.count(F))
01256               continue;
01257 
01258         // extractvalue and insertvalue don't need to be marked; they are
01259         // tracked as precisely as their operands.
01260         if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I))
01261           continue;
01262 
01263         // Send the results of everything else to overdefined.  We could be
01264         // more precise than this but it isn't worth bothering.
01265         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
01266           LatticeVal &LV = getStructValueState(I, i);
01267           if (LV.isUndefined())
01268             markOverdefined(LV, I);
01269         }
01270         continue;
01271       }
01272 
01273       LatticeVal &LV = getValueState(I);
01274       if (!LV.isUndefined()) continue;
01275 
01276       // extractvalue is safe; check here because the argument is a struct.
01277       if (isa<ExtractValueInst>(I))
01278         continue;
01279 
01280       // Compute the operand LatticeVals, for convenience below.
01281       // Anything taking a struct is conservatively assumed to require
01282       // overdefined markings.
01283       if (I->getOperand(0)->getType()->isStructTy()) {
01284         markOverdefined(I);
01285         return true;
01286       }
01287       LatticeVal Op0LV = getValueState(I->getOperand(0));
01288       LatticeVal Op1LV;
01289       if (I->getNumOperands() == 2) {
01290         if (I->getOperand(1)->getType()->isStructTy()) {
01291           markOverdefined(I);
01292           return true;
01293         }
01294 
01295         Op1LV = getValueState(I->getOperand(1));
01296       }
01297       // If this is an instructions whose result is defined even if the input is
01298       // not fully defined, propagate the information.
01299       Type *ITy = I->getType();
01300       switch (I->getOpcode()) {
01301       case Instruction::Add:
01302       case Instruction::Sub:
01303       case Instruction::Trunc:
01304       case Instruction::FPTrunc:
01305       case Instruction::BitCast:
01306         break; // Any undef -> undef
01307       case Instruction::FSub:
01308       case Instruction::FAdd:
01309       case Instruction::FMul:
01310       case Instruction::FDiv:
01311       case Instruction::FRem:
01312         // Floating-point binary operation: be conservative.
01313         if (Op0LV.isUndefined() && Op1LV.isUndefined())
01314           markForcedConstant(I, Constant::getNullValue(ITy));
01315         else
01316           markOverdefined(I);
01317         return true;
01318       case Instruction::ZExt:
01319       case Instruction::SExt:
01320       case Instruction::FPToUI:
01321       case Instruction::FPToSI:
01322       case Instruction::FPExt:
01323       case Instruction::PtrToInt:
01324       case Instruction::IntToPtr:
01325       case Instruction::SIToFP:
01326       case Instruction::UIToFP:
01327         // undef -> 0; some outputs are impossible
01328         markForcedConstant(I, Constant::getNullValue(ITy));
01329         return true;
01330       case Instruction::Mul:
01331       case Instruction::And:
01332         // Both operands undef -> undef
01333         if (Op0LV.isUndefined() && Op1LV.isUndefined())
01334           break;
01335         // undef * X -> 0.   X could be zero.
01336         // undef & X -> 0.   X could be zero.
01337         markForcedConstant(I, Constant::getNullValue(ITy));
01338         return true;
01339 
01340       case Instruction::Or:
01341         // Both operands undef -> undef
01342         if (Op0LV.isUndefined() && Op1LV.isUndefined())
01343           break;
01344         // undef | X -> -1.   X could be -1.
01345         markForcedConstant(I, Constant::getAllOnesValue(ITy));
01346         return true;
01347 
01348       case Instruction::Xor:
01349         // undef ^ undef -> 0; strictly speaking, this is not strictly
01350         // necessary, but we try to be nice to people who expect this
01351         // behavior in simple cases
01352         if (Op0LV.isUndefined() && Op1LV.isUndefined()) {
01353           markForcedConstant(I, Constant::getNullValue(ITy));
01354           return true;
01355         }
01356         // undef ^ X -> undef
01357         break;
01358 
01359       case Instruction::SDiv:
01360       case Instruction::UDiv:
01361       case Instruction::SRem:
01362       case Instruction::URem:
01363         // X / undef -> undef.  No change.
01364         // X % undef -> undef.  No change.
01365         if (Op1LV.isUndefined()) break;
01366 
01367         // undef / X -> 0.   X could be maxint.
01368         // undef % X -> 0.   X could be 1.
01369         markForcedConstant(I, Constant::getNullValue(ITy));
01370         return true;
01371 
01372       case Instruction::AShr:
01373         // X >>a undef -> undef.
01374         if (Op1LV.isUndefined()) break;
01375 
01376         // undef >>a X -> all ones
01377         markForcedConstant(I, Constant::getAllOnesValue(ITy));
01378         return true;
01379       case Instruction::LShr:
01380       case Instruction::Shl:
01381         // X << undef -> undef.
01382         // X >> undef -> undef.
01383         if (Op1LV.isUndefined()) break;
01384 
01385         // undef << X -> 0
01386         // undef >> X -> 0
01387         markForcedConstant(I, Constant::getNullValue(ITy));
01388         return true;
01389       case Instruction::Select:
01390         Op1LV = getValueState(I->getOperand(1));
01391         // undef ? X : Y  -> X or Y.  There could be commonality between X/Y.
01392         if (Op0LV.isUndefined()) {
01393           if (!Op1LV.isConstant())  // Pick the constant one if there is any.
01394             Op1LV = getValueState(I->getOperand(2));
01395         } else if (Op1LV.isUndefined()) {
01396           // c ? undef : undef -> undef.  No change.
01397           Op1LV = getValueState(I->getOperand(2));
01398           if (Op1LV.isUndefined())
01399             break;
01400           // Otherwise, c ? undef : x -> x.
01401         } else {
01402           // Leave Op1LV as Operand(1)'s LatticeValue.
01403         }
01404 
01405         if (Op1LV.isConstant())
01406           markForcedConstant(I, Op1LV.getConstant());
01407         else
01408           markOverdefined(I);
01409         return true;
01410       case Instruction::Load:
01411         // A load here means one of two things: a load of undef from a global,
01412         // a load from an unknown pointer.  Either way, having it return undef
01413         // is okay.
01414         break;
01415       case Instruction::ICmp:
01416         // X == undef -> undef.  Other comparisons get more complicated.
01417         if (cast<ICmpInst>(I)->isEquality())
01418           break;
01419         markOverdefined(I);
01420         return true;
01421       case Instruction::Call:
01422       case Instruction::Invoke: {
01423         // There are two reasons a call can have an undef result
01424         // 1. It could be tracked.
01425         // 2. It could be constant-foldable.
01426         // Because of the way we solve return values, tracked calls must
01427         // never be marked overdefined in ResolvedUndefsIn.
01428         if (Function *F = CallSite(I).getCalledFunction())
01429           if (TrackedRetVals.count(F))
01430             break;
01431 
01432         // If the call is constant-foldable, we mark it overdefined because
01433         // we do not know what return values are valid.
01434         markOverdefined(I);
01435         return true;
01436       }
01437       default:
01438         // If we don't know what should happen here, conservatively mark it
01439         // overdefined.
01440         markOverdefined(I);
01441         return true;
01442       }
01443     }
01444 
01445     // Check to see if we have a branch or switch on an undefined value.  If so
01446     // we force the branch to go one way or the other to make the successor
01447     // values live.  It doesn't really matter which way we force it.
01448     TerminatorInst *TI = BB->getTerminator();
01449     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
01450       if (!BI->isConditional()) continue;
01451       if (!getValueState(BI->getCondition()).isUndefined())
01452         continue;
01453 
01454       // If the input to SCCP is actually branch on undef, fix the undef to
01455       // false.
01456       if (isa<UndefValue>(BI->getCondition())) {
01457         BI->setCondition(ConstantInt::getFalse(BI->getContext()));
01458         markEdgeExecutable(BB, TI->getSuccessor(1));
01459         return true;
01460       }
01461 
01462       // Otherwise, it is a branch on a symbolic value which is currently
01463       // considered to be undef.  Handle this by forcing the input value to the
01464       // branch to false.
01465       markForcedConstant(BI->getCondition(),
01466                          ConstantInt::getFalse(TI->getContext()));
01467       return true;
01468     }
01469 
01470     if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
01471       if (!SI->getNumCases())
01472         continue;
01473       if (!getValueState(SI->getCondition()).isUndefined())
01474         continue;
01475 
01476       // If the input to SCCP is actually switch on undef, fix the undef to
01477       // the first constant.
01478       if (isa<UndefValue>(SI->getCondition())) {
01479         SI->setCondition(SI->case_begin().getCaseValue());
01480         markEdgeExecutable(BB, SI->case_begin().getCaseSuccessor());
01481         return true;
01482       }
01483 
01484       markForcedConstant(SI->getCondition(), SI->case_begin().getCaseValue());
01485       return true;
01486     }
01487   }
01488 
01489   return false;
01490 }
01491 
01492 
01493 namespace {
01494   //===--------------------------------------------------------------------===//
01495   //
01496   /// SCCP Class - This class uses the SCCPSolver to implement a per-function
01497   /// Sparse Conditional Constant Propagator.
01498   ///
01499   struct SCCP : public FunctionPass {
01500     void getAnalysisUsage(AnalysisUsage &AU) const override {
01501       AU.addRequired<TargetLibraryInfo>();
01502     }
01503     static char ID; // Pass identification, replacement for typeid
01504     SCCP() : FunctionPass(ID) {
01505       initializeSCCPPass(*PassRegistry::getPassRegistry());
01506     }
01507 
01508     // runOnFunction - Run the Sparse Conditional Constant Propagation
01509     // algorithm, and return true if the function was modified.
01510     //
01511     bool runOnFunction(Function &F) override;
01512   };
01513 } // end anonymous namespace
01514 
01515 char SCCP::ID = 0;
01516 INITIALIZE_PASS(SCCP, "sccp",
01517                 "Sparse Conditional Constant Propagation", false, false)
01518 
01519 // createSCCPPass - This is the public interface to this file.
01520 FunctionPass *llvm::createSCCPPass() {
01521   return new SCCP();
01522 }
01523 
01524 static void DeleteInstructionInBlock(BasicBlock *BB) {
01525   DEBUG(dbgs() << "  BasicBlock Dead:" << *BB);
01526   ++NumDeadBlocks;
01527 
01528   // Check to see if there are non-terminating instructions to delete.
01529   if (isa<TerminatorInst>(BB->begin()))
01530     return;
01531 
01532   // Delete the instructions backwards, as it has a reduced likelihood of having
01533   // to update as many def-use and use-def chains.
01534   Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
01535   while (EndInst != BB->begin()) {
01536     // Delete the next to last instruction.
01537     BasicBlock::iterator I = EndInst;
01538     Instruction *Inst = --I;
01539     if (!Inst->use_empty())
01540       Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
01541     if (isa<LandingPadInst>(Inst)) {
01542       EndInst = Inst;
01543       continue;
01544     }
01545     BB->getInstList().erase(Inst);
01546     ++NumInstRemoved;
01547   }
01548 }
01549 
01550 // runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
01551 // and return true if the function was modified.
01552 //
01553 bool SCCP::runOnFunction(Function &F) {
01554   if (skipOptnoneFunction(F))
01555     return false;
01556 
01557   DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
01558   const DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
01559   const DataLayout *DL = DLP ? &DLP->getDataLayout() : 0;
01560   const TargetLibraryInfo *TLI = &getAnalysis<TargetLibraryInfo>();
01561   SCCPSolver Solver(DL, TLI);
01562 
01563   // Mark the first block of the function as being executable.
01564   Solver.MarkBlockExecutable(F.begin());
01565 
01566   // Mark all arguments to the function as being overdefined.
01567   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
01568     Solver.markAnythingOverdefined(AI);
01569 
01570   // Solve for constants.
01571   bool ResolvedUndefs = true;
01572   while (ResolvedUndefs) {
01573     Solver.Solve();
01574     DEBUG(dbgs() << "RESOLVING UNDEFs\n");
01575     ResolvedUndefs = Solver.ResolvedUndefsIn(F);
01576   }
01577 
01578   bool MadeChanges = false;
01579 
01580   // If we decided that there are basic blocks that are dead in this function,
01581   // delete their contents now.  Note that we cannot actually delete the blocks,
01582   // as we cannot modify the CFG of the function.
01583 
01584   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
01585     if (!Solver.isBlockExecutable(BB)) {
01586       DeleteInstructionInBlock(BB);
01587       MadeChanges = true;
01588       continue;
01589     }
01590 
01591     // Iterate over all of the instructions in a function, replacing them with
01592     // constants if we have found them to be of constant values.
01593     //
01594     for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
01595       Instruction *Inst = BI++;
01596       if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
01597         continue;
01598 
01599       // TODO: Reconstruct structs from their elements.
01600       if (Inst->getType()->isStructTy())
01601         continue;
01602 
01603       LatticeVal IV = Solver.getLatticeValueFor(Inst);
01604       if (IV.isOverdefined())
01605         continue;
01606 
01607       Constant *Const = IV.isConstant()
01608         ? IV.getConstant() : UndefValue::get(Inst->getType());
01609       DEBUG(dbgs() << "  Constant: " << *Const << " = " << *Inst << '\n');
01610 
01611       // Replaces all of the uses of a variable with uses of the constant.
01612       Inst->replaceAllUsesWith(Const);
01613 
01614       // Delete the instruction.
01615       Inst->eraseFromParent();
01616 
01617       // Hey, we just changed something!
01618       MadeChanges = true;
01619       ++NumInstRemoved;
01620     }
01621   }
01622 
01623   return MadeChanges;
01624 }
01625 
01626 namespace {
01627   //===--------------------------------------------------------------------===//
01628   //
01629   /// IPSCCP Class - This class implements interprocedural Sparse Conditional
01630   /// Constant Propagation.
01631   ///
01632   struct IPSCCP : public ModulePass {
01633     void getAnalysisUsage(AnalysisUsage &AU) const override {
01634       AU.addRequired<TargetLibraryInfo>();
01635     }
01636     static char ID;
01637     IPSCCP() : ModulePass(ID) {
01638       initializeIPSCCPPass(*PassRegistry::getPassRegistry());
01639     }
01640     bool runOnModule(Module &M) override;
01641   };
01642 } // end anonymous namespace
01643 
01644 char IPSCCP::ID = 0;
01645 INITIALIZE_PASS_BEGIN(IPSCCP, "ipsccp",
01646                 "Interprocedural Sparse Conditional Constant Propagation",
01647                 false, false)
01648 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
01649 INITIALIZE_PASS_END(IPSCCP, "ipsccp",
01650                 "Interprocedural Sparse Conditional Constant Propagation",
01651                 false, false)
01652 
01653 // createIPSCCPPass - This is the public interface to this file.
01654 ModulePass *llvm::createIPSCCPPass() {
01655   return new IPSCCP();
01656 }
01657 
01658 
01659 static bool AddressIsTaken(const GlobalValue *GV) {
01660   // Delete any dead constantexpr klingons.
01661   GV->removeDeadConstantUsers();
01662 
01663   for (const Use &U : GV->uses()) {
01664     const User *UR = U.getUser();
01665     if (const StoreInst *SI = dyn_cast<StoreInst>(UR)) {
01666       if (SI->getOperand(0) == GV || SI->isVolatile())
01667         return true;  // Storing addr of GV.
01668     } else if (isa<InvokeInst>(UR) || isa<CallInst>(UR)) {
01669       // Make sure we are calling the function, not passing the address.
01670       ImmutableCallSite CS(cast<Instruction>(UR));
01671       if (!CS.isCallee(&U))
01672         return true;
01673     } else if (const LoadInst *LI = dyn_cast<LoadInst>(UR)) {
01674       if (LI->isVolatile())
01675         return true;
01676     } else if (isa<BlockAddress>(UR)) {
01677       // blockaddress doesn't take the address of the function, it takes addr
01678       // of label.
01679     } else {
01680       return true;
01681     }
01682   }
01683   return false;
01684 }
01685 
01686 bool IPSCCP::runOnModule(Module &M) {
01687   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
01688   const DataLayout *DL = DLP ? &DLP->getDataLayout() : 0;
01689   const TargetLibraryInfo *TLI = &getAnalysis<TargetLibraryInfo>();
01690   SCCPSolver Solver(DL, TLI);
01691 
01692   // AddressTakenFunctions - This set keeps track of the address-taken functions
01693   // that are in the input.  As IPSCCP runs through and simplifies code,
01694   // functions that were address taken can end up losing their
01695   // address-taken-ness.  Because of this, we keep track of their addresses from
01696   // the first pass so we can use them for the later simplification pass.
01697   SmallPtrSet<Function*, 32> AddressTakenFunctions;
01698 
01699   // Loop over all functions, marking arguments to those with their addresses
01700   // taken or that are external as overdefined.
01701   //
01702   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
01703     if (F->isDeclaration())
01704       continue;
01705 
01706     // If this is a strong or ODR definition of this function, then we can
01707     // propagate information about its result into callsites of it.
01708     if (!F->mayBeOverridden())
01709       Solver.AddTrackedFunction(F);
01710 
01711     // If this function only has direct calls that we can see, we can track its
01712     // arguments and return value aggressively, and can assume it is not called
01713     // unless we see evidence to the contrary.
01714     if (F->hasLocalLinkage()) {
01715       if (AddressIsTaken(F))
01716         AddressTakenFunctions.insert(F);
01717       else {
01718         Solver.AddArgumentTrackedFunction(F);
01719         continue;
01720       }
01721     }
01722 
01723     // Assume the function is called.
01724     Solver.MarkBlockExecutable(F->begin());
01725 
01726     // Assume nothing about the incoming arguments.
01727     for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
01728          AI != E; ++AI)
01729       Solver.markAnythingOverdefined(AI);
01730   }
01731 
01732   // Loop over global variables.  We inform the solver about any internal global
01733   // variables that do not have their 'addresses taken'.  If they don't have
01734   // their addresses taken, we can propagate constants through them.
01735   for (Module::global_iterator G = M.global_begin(), E = M.global_end();
01736        G != E; ++G)
01737     if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
01738       Solver.TrackValueOfGlobalVariable(G);
01739 
01740   // Solve for constants.
01741   bool ResolvedUndefs = true;
01742   while (ResolvedUndefs) {
01743     Solver.Solve();
01744 
01745     DEBUG(dbgs() << "RESOLVING UNDEFS\n");
01746     ResolvedUndefs = false;
01747     for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
01748       ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
01749   }
01750 
01751   bool MadeChanges = false;
01752 
01753   // Iterate over all of the instructions in the module, replacing them with
01754   // constants if we have found them to be of constant values.
01755   //
01756   SmallVector<BasicBlock*, 512> BlocksToErase;
01757 
01758   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
01759     if (Solver.isBlockExecutable(F->begin())) {
01760       for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
01761            AI != E; ++AI) {
01762         if (AI->use_empty() || AI->getType()->isStructTy()) continue;
01763 
01764         // TODO: Could use getStructLatticeValueFor to find out if the entire
01765         // result is a constant and replace it entirely if so.
01766 
01767         LatticeVal IV = Solver.getLatticeValueFor(AI);
01768         if (IV.isOverdefined()) continue;
01769 
01770         Constant *CST = IV.isConstant() ?
01771         IV.getConstant() : UndefValue::get(AI->getType());
01772         DEBUG(dbgs() << "***  Arg " << *AI << " = " << *CST <<"\n");
01773 
01774         // Replaces all of the uses of a variable with uses of the
01775         // constant.
01776         AI->replaceAllUsesWith(CST);
01777         ++IPNumArgsElimed;
01778       }
01779     }
01780 
01781     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
01782       if (!Solver.isBlockExecutable(BB)) {
01783         DeleteInstructionInBlock(BB);
01784         MadeChanges = true;
01785 
01786         TerminatorInst *TI = BB->getTerminator();
01787         for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
01788           BasicBlock *Succ = TI->getSuccessor(i);
01789           if (!Succ->empty() && isa<PHINode>(Succ->begin()))
01790             TI->getSuccessor(i)->removePredecessor(BB);
01791         }
01792         if (!TI->use_empty())
01793           TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
01794         TI->eraseFromParent();
01795 
01796         if (&*BB != &F->front())
01797           BlocksToErase.push_back(BB);
01798         else
01799           new UnreachableInst(M.getContext(), BB);
01800         continue;
01801       }
01802 
01803       for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
01804         Instruction *Inst = BI++;
01805         if (Inst->getType()->isVoidTy() || Inst->getType()->isStructTy())
01806           continue;
01807 
01808         // TODO: Could use getStructLatticeValueFor to find out if the entire
01809         // result is a constant and replace it entirely if so.
01810 
01811         LatticeVal IV = Solver.getLatticeValueFor(Inst);
01812         if (IV.isOverdefined())
01813           continue;
01814 
01815         Constant *Const = IV.isConstant()
01816           ? IV.getConstant() : UndefValue::get(Inst->getType());
01817         DEBUG(dbgs() << "  Constant: " << *Const << " = " << *Inst << '\n');
01818 
01819         // Replaces all of the uses of a variable with uses of the
01820         // constant.
01821         Inst->replaceAllUsesWith(Const);
01822 
01823         // Delete the instruction.
01824         if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
01825           Inst->eraseFromParent();
01826 
01827         // Hey, we just changed something!
01828         MadeChanges = true;
01829         ++IPNumInstRemoved;
01830       }
01831     }
01832 
01833     // Now that all instructions in the function are constant folded, erase dead
01834     // blocks, because we can now use ConstantFoldTerminator to get rid of
01835     // in-edges.
01836     for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
01837       // If there are any PHI nodes in this successor, drop entries for BB now.
01838       BasicBlock *DeadBB = BlocksToErase[i];
01839       for (Value::user_iterator UI = DeadBB->user_begin(),
01840                                 UE = DeadBB->user_end();
01841            UI != UE;) {
01842         // Grab the user and then increment the iterator early, as the user
01843         // will be deleted. Step past all adjacent uses from the same user.
01844         Instruction *I = dyn_cast<Instruction>(*UI);
01845         do { ++UI; } while (UI != UE && *UI == I);
01846 
01847         // Ignore blockaddress users; BasicBlock's dtor will handle them.
01848         if (!I) continue;
01849 
01850         bool Folded = ConstantFoldTerminator(I->getParent());
01851         if (!Folded) {
01852           // The constant folder may not have been able to fold the terminator
01853           // if this is a branch or switch on undef.  Fold it manually as a
01854           // branch to the first successor.
01855 #ifndef NDEBUG
01856           if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
01857             assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
01858                    "Branch should be foldable!");
01859           } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
01860             assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
01861           } else {
01862             llvm_unreachable("Didn't fold away reference to block!");
01863           }
01864 #endif
01865 
01866           // Make this an uncond branch to the first successor.
01867           TerminatorInst *TI = I->getParent()->getTerminator();
01868           BranchInst::Create(TI->getSuccessor(0), TI);
01869 
01870           // Remove entries in successor phi nodes to remove edges.
01871           for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
01872             TI->getSuccessor(i)->removePredecessor(TI->getParent());
01873 
01874           // Remove the old terminator.
01875           TI->eraseFromParent();
01876         }
01877       }
01878 
01879       // Finally, delete the basic block.
01880       F->getBasicBlockList().erase(DeadBB);
01881     }
01882     BlocksToErase.clear();
01883   }
01884 
01885   // If we inferred constant or undef return values for a function, we replaced
01886   // all call uses with the inferred value.  This means we don't need to bother
01887   // actually returning anything from the function.  Replace all return
01888   // instructions with return undef.
01889   //
01890   // Do this in two stages: first identify the functions we should process, then
01891   // actually zap their returns.  This is important because we can only do this
01892   // if the address of the function isn't taken.  In cases where a return is the
01893   // last use of a function, the order of processing functions would affect
01894   // whether other functions are optimizable.
01895   SmallVector<ReturnInst*, 8> ReturnsToZap;
01896 
01897   // TODO: Process multiple value ret instructions also.
01898   const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
01899   for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
01900        E = RV.end(); I != E; ++I) {
01901     Function *F = I->first;
01902     if (I->second.isOverdefined() || F->getReturnType()->isVoidTy())
01903       continue;
01904 
01905     // We can only do this if we know that nothing else can call the function.
01906     if (!F->hasLocalLinkage() || AddressTakenFunctions.count(F))
01907       continue;
01908 
01909     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
01910       if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
01911         if (!isa<UndefValue>(RI->getOperand(0)))
01912           ReturnsToZap.push_back(RI);
01913   }
01914 
01915   // Zap all returns which we've identified as zap to change.
01916   for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
01917     Function *F = ReturnsToZap[i]->getParent()->getParent();
01918     ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
01919   }
01920 
01921   // If we inferred constant or undef values for globals variables, we can
01922   // delete the global and any stores that remain to it.
01923   const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
01924   for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
01925          E = TG.end(); I != E; ++I) {
01926     GlobalVariable *GV = I->first;
01927     assert(!I->second.isOverdefined() &&
01928            "Overdefined values should have been taken out of the map!");
01929     DEBUG(dbgs() << "Found that GV '" << GV->getName() << "' is constant!\n");
01930     while (!GV->use_empty()) {
01931       StoreInst *SI = cast<StoreInst>(GV->user_back());
01932       SI->eraseFromParent();
01933     }
01934     M.getGlobalList().erase(GV);
01935     ++IPNumGlobalConst;
01936   }
01937 
01938   return MadeChanges;
01939 }